<?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 Mina Suntea on Medium]]></title>
        <description><![CDATA[Stories by Mina Suntea on Medium]]></description>
        <link>https://medium.com/@minasuntea?source=rss-5edc935bf437------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jOzEGHakUwJwrHRJrvtyng.jpeg</url>
            <title>Stories by Mina Suntea on Medium</title>
            <link>https://medium.com/@minasuntea?source=rss-5edc935bf437------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 07:24:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@minasuntea/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[Data Story 2]]></title>
            <link>https://medium.datadriveninvestor.com/data-story-2-f1c7ea29366e?source=rss-5edc935bf437------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1c7ea29366e</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Mina Suntea]]></dc:creator>
            <pubDate>Fri, 29 Jan 2021 15:29:02 GMT</pubDate>
            <atom:updated>2021-01-29T15:37:07.905Z</atom:updated>
            <content:encoded><![CDATA[<h4>Inferring information from visualized data</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lxO7nkviHJr4Zw-2" /><figcaption>Photo by <a href="https://unsplash.com/@kmuza?utm_source=medium&amp;utm_medium=referral">Carlos Muza</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As announced in the last part of <a href="https://minasuntea.medium.com/data-story-1-2068def504df">Data Story 1</a> a new stance will be discussed in this Data Story about the same data set, namely the <em>FIFA 19 complete player dataset</em>. The stance taken in this article is as follows:</p><blockquote>The market value of a soccer player is determined more by the club he is playing in than his actual qualities</blockquote><p>With data from approximately 18000 soccer players, this stance is proved by various graphs.</p><h4>Choropleth Worldmap</h4><p>First an overall picture is sketched of the market value per country around the world using a Choropleth Worldmap. For this visualization the <em>value</em> column of the data set is used, in which the market values are stored. However, to be able to use this data, it must first get cleaned just like the <em>wage</em> column in <a href="https://minasuntea.medium.com/data-story-1-2068def504df">Data Story 1</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*xRWqTuURyF_tUOSZGpTbuQ.png" /></figure><p>Now the average market value per country can be obtained by grouping the dataframe by the <em>nationality</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*13sF1_pkSoWZ55hKVD5eUw.png" /></figure><p>Next, the data should be defined:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*hzFGDVenahwf3imyHcDicA.png" /></figure><p>The layout should be described, in which the size and type of the graph are specified. In the layout of this visualization, all the longitudes and latitudes are also defined as well as the sliders that make the plot interactive and make you move the plot around to look at all countries:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*PT7Pemyq-Dh4wVBqWQmNPA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RV-OtjOkLoi-rUZ4TiQoag.png" /><figcaption>Rotation value specified per longitude value</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LVx1Ug4Tp4HS7R9VO04ABQ.png" /><figcaption>The rest of the longitudes</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sLrAUzVT-RD-lS3_QC3bIA.png" /><figcaption>Rotation value specified per latitude value</figcaption></figure><p>Now, the figure is ready to be visualized:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*Gbruy9DWmfauf3E5CdKaZw.png" /></figure><iframe src="https://share.getcloudapp.com/Z4u6eyzN?embed=true" width="1023" height="720" frameborder="0" scrolling="no"><a href="https://medium.com/media/cdd5e51ad68830e95221870064070a11/href">https://medium.com/media/cdd5e51ad68830e95221870064070a11/href</a></iframe><p>There are some infamous soccer players, like Neymar, Messi, Ronaldo etc. They all also have a high market value, like Neymar with a market value of 118.5 million euros and Messi with a market value of 110.5 million euros. The question that now remains is if these high market values are the product of fame or their qualities.</p><p>The Choropleth Worldmap provides some context for this question, as it can be derived that the countries these players come from have a high average market value. Countries like Brasil and Argentina for example have a high average market value.</p><h4>Line Graph &amp; Bar Plot</h4><p>To further investigate this stance I zoomed in on the 10 Dutch soccer players with the highest <em>overall</em> rating. For this a small dataframe was extracted from the big dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*Isk_Doiz-es_DaNKPo-18Q.png" /><figcaption>The data set is already sorted on overall rating so sorting is not necessary</figcaption></figure><p>Now the <em>potential</em> and <em>overall</em> ratings must be obtained, for that is the data that will be visualized. These 2 ratings will be compared to each other in the line graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*S_sztV8hXk7aF5UOgygBRA.png" /></figure><p>Next, the layout of the line graph must be defined after which it can be plotted:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-qJDLCzgK2yKEGyi-BGozg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*a-MXB7YkDUPu1-fJ2P4HOg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ELlE_MUqMwv6OA9bSWLryQ.png" /></figure><p>In the line graph illustrated above, the <em>potential</em> and <em>overall</em> ratings are compared to each other per soccer player. The striking thing is that the <em>potential</em> of a soccer player is approximated to a higher rating when the soccer player plays for a topclub.</p><p>Hovering over the data points makes the club the soccer player is in visible. The differences between the <em>overall</em> ratings of these soccer players are not so big, but still the <em>potential</em> ratings differ a lot from each other. The fluctuations in the <em>potential</em> rating is caused by the difference in club.</p><p>With this same data a bar plot is made in which the market value is compared with the wages of the soccer players. For this the <em>new_value </em>and the <em>new_wage</em> columns are used that consist of clean data, without euro signs, K’s and M’s. For the cleaning of the <em>wage</em> column and creating the <em>new_wage</em> column, take a look at <a href="https://medium.com/datadriveninvestor/data-story-1-2068def504df">Data Story 1</a>:</p><p>This visualization is constructed in the same way like the line graph by defining the data and the layout:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*KDiJNZWe0o8pvuNi8jANdw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*6qttvyApPIQVPqrmEF_wrA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*IhtZE8BTzz0us3lbH3WBQQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jqiHz-XqG-oDjWtu0l1Njw.png" /></figure><p>This bar plot further backs up the stance, for the wages and market values also differ a whole lot in the most cases. This is thought to be highly influenced by the club of the soccer player. The soccer player <strong><em>M. de Ligt </em></strong>for example has a wage of 11000 euros, but a market value of 27 million euros. By hovering over the bars and the line it can be derived that, the more famous the clubs the soccer players play for, the higher the market value. So the market value is not solely based on their skill.</p><h4>Scatter Plot</h4><p>The correlation between a club and market value of the soccer player is further visualized with this scatter plot. There are over 18000 soccer players, so to make the plot readable only the 1000 best players were used for this plot. For this a small dataframe is created with only these 1000 top soccer players and some additional features that is needed for the visualization:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gXNLcUoxvPEjgo9L1bzzng.png" /></figure><p>Now that the dataframe is provided, the same steps will be executed to form the scatter plot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*0KD0GlchE6E4GwufLiur6w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*WO7ZDcdKs9ksrKFm6mQe5w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*E7FvbAUc3obHBrXjUoNfeA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mXuJdXeFoHgQc7wfjqaDmA.png" /></figure><p>Every data point in the scatter plot above represents one of the top 1000 soccer players of this data set. The soccer clubs that are displayed were sorted by the <em>overall</em> rating of the best players of that club. By hovering over the different data points, the corresponding club and market value are also shown. This plot visualizes that the correlation between notoriety of a soccer club and the market value of soccer players in that club is positive.</p><h4>Bubble Plot</h4><p>Looking at the average <em>overall</em> rating and notoriety of soccer clubs, some further insights can be offered in the correlation between notoriety and market value. To establish the notoriety of a club, the <em>international reputation</em>, <em>overall</em> and <em>market value</em> are used. First the <em>international reputation</em> should be scaled to 100 just like the <em>overall</em> values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*o6ztV5_JhL5FlJNjm3cw_w.png" /></figure><p>Now the necessary data can be accumulated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WD-sjvpw2mczbIePlmojjg.png" /></figure><p>There are over 600 soccer clubs embedded in this data set, so to make the graph readable, the clubs that are displayed are determined by which clubs have the highest and lowest market value per interval of 2.5 on the x axis. These are then displayed in the bubble plot. For this some auxiliary variables are defined:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*WgIuPfnZrasyUVXo521x6Q.png" /></figure><p>Now that we have all the necessary information, the data and layout can be defined after which the bubble plot can be visualized:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*zZgKHEF6B-c_7vQfNeq-PA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qq99nmZeoDU-NjA8IxvT4w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*2IODyEDUKEgKw85hEAKlGA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ndeyn2MOsTufUkn-b17msw.png" /><figcaption>The size of the bubble represents the notoriety of the club</figcaption></figure><p>This graph proves that the reputation of a club influences the market value of a club and that the market value is not based on pure skill of the soccer players. Here it is shown that the bubbles of the same size, with (approximately) the same <em>overall</em> rating still differ in market value. By hovering over the bubbles, the <em>overall</em> rating and market value can be seen per club.</p><h4>Radar Chart</h4><p>Zooming in on the 2 soccer clubs <em>Atlético Madrid</em> and <em>SC Braga</em>, the stance is supported further. To visualize only the important features, a small dataframe is created with only the <em>club</em>, <em>overall</em>, <em>potential</em>, <em>market value </em>and <em>international reputation</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*vtV__R7g1XQrYLq_q3Vhiw.png" /></figure><p>Now, the information from the 2 clubs should be gathered:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*1mFNRnJlt2L94Ur_MSWClA.png" /></figure><p>The only thing left to do now is defining the data and layout and plot the radar chart:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hM1_0v3DU6ClfGuGZ-P4Vw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*GRt-fvwFkvqU3cOIb0_vjA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*QMTwGeqsZzkaiLotYRJ2ow.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fTlRsD8yaDuaPi9Nl--g1w.png" /></figure><p>This radar chart is a strong piece of evidence that contributes to the credibility of the stance. The <em>overall</em> and <em>potential</em> ratings of the clubs don’t differ a lot from each other, yet their <em>international reputation</em> and especially their market value differ a lot. This makes the soccer players of <em>Atlético Madrid</em> approximately 3x more valuable than the soccer players of <em>SC Braga</em>, while their qualities are almost equal.</p><p>All in all these visualizations did add to the credibility of the taken stance. The club a soccer player plays in influences his market value more than his individual qualities. Therefore the market value of notorious clubs and soccer players are consistently higher than from less notorious clubs and soccer players.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1c7ea29366e" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/data-story-2-f1c7ea29366e">Data Story 2</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Story 1]]></title>
            <link>https://medium.datadriveninvestor.com/data-story-1-2068def504df?source=rss-5edc935bf437------2</link>
            <guid isPermaLink="false">https://medium.com/p/2068def504df</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Mina Suntea]]></dc:creator>
            <pubDate>Tue, 26 Jan 2021 16:26:42 GMT</pubDate>
            <atom:updated>2021-01-27T14:12:38.226Z</atom:updated>
            <content:encoded><![CDATA[<h4>Inferring information from visualized data</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nP9l617fXZgjbn4n" /><figcaption>Photo by <a href="https://unsplash.com/@goumbik?utm_source=medium&amp;utm_medium=referral">Lukas Blazek</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Data, data, data, so cheap and easy to obtain, yet so valuable in the eyes of a Data Scientist, Machine Learning engineer or Computer Scientist. The reason behind this is that a whole story can be told from this data, a very valuable story in fact, from which useful conclusions can be drawn.</p><p>A data story provides insights about, for example, sales, depending on the kind of data set. In this article I will be discussing a data story I made, which I will be running you through to show how much information can be extracted from data.</p><h4>Getting familiar with the data</h4><p>In this data story and the next the dataset <em>FIFA 19 complete player dataset </em>is used which was downloaded from a free open dataset source called <a href="https://www.kaggle.com/datasets">kaggle</a>. First and foremost, one must take a look at the data, so the dataset must first be loaded in and visualized. Here the <em>pandas</em> library has been used for that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*DoT2F3H2mSQCIJzdult9HA.png" /></figure><p>By printing the dataframe, the data is illustrated in an ordered way so you can take a look at the amount and types of rows and columns:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ttgx9zfbLuMwFU2Ge-Jw1A.png" /></figure><p>At the bottom left corner the size of the dataset is displayed, 18207 rows × 89 columns. Because of the huge size of this dataset, not all columns and rows are shown, but it is good enough to get familiar with the data. To view all column names or some specific rows, there are functions included in the <em>pandas</em> libraries that can be used.</p><h4>Taking a Stance</h4><p>After studying this dataset, a stance can be taken about the ideal age of soccer players. The stance that was taken was as follows:</p><blockquote>The age of 31 is the ideal age for a soccer player</blockquote><p>To back up this stance, derived from this data set, several visualizations have been created in which multiple features are set out against the age. Before setting out features against the age, the data set is first grouped by age to make things easier:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*U97TpSagu3KXE5V0pUR-TQ.png" /></figure><h4>Interactive Linegraph</h4><p>The first feature that was looked at to set out against the age was the <em>overall rating</em>. Now that the dataframe is grouped by age, all the information can be split per age. This way the <em>overall ratings</em> can be retrieved per age:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*zQiTOsFVzyoGSyM2Y2B6Ow.png" /><figcaption>From the small dataframes per age, only the overall ratings are extracted</figcaption></figure><p>Using the lists of <em>overall ratings</em> per age, the average, maximum and minimum <em>overall rating</em> per age can be retrieved:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*m7w8PT5E8bhJ-HNWOz3y6Q.png" /></figure><p>Now these can be visualized in an interactive graph to make some statements about the ideal age:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*PzppF67gurAo0LIdxhs4fA.png" /><figcaption>Define the lines for the linegraph</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*mJ8EmQclyxlTs7hDKcDfkA.png" /><figcaption>Defining the data as the three defined lines</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*EMp9ZmNWnf3_i0HxTEYZ6w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*CCTP50CN5AX_3sDTKJogFg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*-p5nfZhK18M_oiZkN8f22w.png" /></figure><iframe src="https://share.getcloudapp.com/GGu6nRoz?embed=true" width="1432" height="720" frameborder="0" scrolling="no"><a href="https://medium.com/media/acb9616e25c34efe7b6e13754929ebfd/href">https://medium.com/media/acb9616e25c34efe7b6e13754929ebfd/href</a></iframe><p>What becomes clear from this plot, is that the <em>overall rating</em> is relatively low at a young age, but increases with age. Eventually at the age of 31 a peak is reached and after this age, the <em>overall rating</em> drops. Quite remarkable are the sudden peaks at 40 and higher, but this can be explained because of some exceptional players with high <em>overall ratings</em> like <strong><em>O. Pérez</em></strong><em>,</em> who caused the peak at the age of 45.</p><h4><strong>Interactive Radar Chart</strong></h4><p>Next, the average ratings of 7 features are shown in a Radar Chart. The features for this visualizations are determined in such a way that they apply on both the defenders and the strikers. This is done so that no big outliers are detected that create a distorted picture of the truth as they excel in different features.</p><p>First a dataframe is created with all the information for 31-year-old soccer players:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*PlPQeTmJnDV4FnrFEoULJg.png" /></figure><p>Next, the data that is going to be used for the plot should be defined, as well as the buttons and the layout just like in the interactive linegraph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-s1uo7LFFuPQvNWDlVUSdg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*3_LCYk4zCMpFuJmzTWvnNg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aM567kOvYNyZbtyDJHlj-w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*D4vraZlqxsSBQM0ScixhRQ.png" /></figure><iframe src="https://share.getcloudapp.com/WnuB2j0J?embed=true" width="1320" height="720" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d78e87d8e5e3ff318f8d694eccddcf7/href">https://medium.com/media/6d78e87d8e5e3ff318f8d694eccddcf7/href</a></iframe><p>The Radar Chart proves that soccer players are in best shape at the age of 31, as they score higher in 6 of the 7 ratings. <em>Agility</em> seems to remain the same and is not remarkably better at the age of 31.</p><h4>Linegraph</h4><p>Some additional proof for the taken stance is found in visualizing the course of the average of the <em>potential ratings</em> and the <em>overall ratings</em> over the years. This is done in a very similar way as the plots shown above.</p><p>For this plot yet another part of the dataframe is being used, which has to be extracted. In this visualization only the information from all soccer players younger than 40 years old are used:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*gNn1uhnRY16fiSNtrSXNgw.png" /></figure><p>Now again the data and the layout are defined after which the linegraph is plotted:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*5rRwvUAnKrnKoadcvc5rUQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*JwBO4KgNQonAQ6HRjdVlZA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*4liaqgC2-DqSuYJ2Db98QQ.png" /></figure><iframe src="https://share.getcloudapp.com/9Zu8l71b?embed=true" width="1464" height="718" frameborder="0" scrolling="no"><a href="https://medium.com/media/a110d850029fd4f2f785685cea1a91c8/href">https://medium.com/media/a110d850029fd4f2f785685cea1a91c8/href</a></iframe><p>In this graph the negative correlation between the <em>potential rating</em> and the age can be seen. The younger the soccer player, the higher the <em>potential rating</em>. However, the <em>overall rating</em> has a positive correlation with the age. These 2 ratings coincide at the age of 31, which implies that the peak of potention is reached at that age.</p><h4>Pie Chart</h4><p>Another valuable column of the data set that can be used to back up the stance, is the <em>international reputation</em>. The <em>international reputation </em>is defined with numbers from 1 to 5. In this case only the players are used who have a <em>international reputation</em> that’s higher than 3. Then the <em>skill moves</em> are summed per age, which are also indicated with values 1 to 5:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*72wiHvWZ4npsjxe0Je-3lw.png" /></figure><p>Then again, the data and the layout are defined and the Pie Chart is plotted:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*OY4cDN4kH6MYqh1iMbZ5Jw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*tZ61Ohveakj1k-UGYEf6Zg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*WsxEPhPp0-vCURZVKelejg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TjEbJwiz1WJCmwfKPsS8Lg.png" /></figure><p>In this Pie Chart it is shown that the most players with a high <em>international reputation</em> are 31 years old, with 9 players and 15.8%. So again it is proven that 31 is the ideal age for a soccer player. By hovering over the Pie Chart the same specifications, that are shown in the figure above for the age of 31, can be seen for every age.</p><h4>Bar plot</h4><p>The final visualization illustrates the average income per age for all soccer players who have at least 4 <em>skill moves</em>. Before the income could be used, the data had to be cleaned. The data set contained euro signs and K’s to indicate the amount of money, so the whole column had to be converted and added to the dataframe for usage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*BAv6WdkA_ykUwOvWaFnYNA.png" /></figure><p>Now that the incomes can be used, first the average income per age is obtained:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*Diyr6roohLI5_PIPaS2IEw.png" /></figure><p>Just like before, the data and layout must be defined so that the figure can be plotted:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*qYF9Q_XyCNAF2LcdWNP9vA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*DMBYdoDQHI7zUTU0nIZZuQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*nAMPldzxS-mJnR6F8jjyUA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v_e1Nx8WGNlLBoZnlyTcwQ.png" /></figure><p>Here the peak in average income is illustrated for the age of 31. This again backs up the stance taken about 31-year-old soccer players being at their best. Just like at the Pie Chart, the specifications of the other bars can be seen by hovering over them. The striking peak at the age of 45 is yet again because of the exceptional soccer player <strong><em>O. Perez</em></strong>. He is the only 45-year-old in this data set and therefore there is no average.</p><p>All in all it can be concluded that the taken stance can be deemed as true, looking at the 5 visualizations shown in this article. From these plots it can be derived that 31-year-old exceed soccer players from younger and older age on qualities, prestige and income.</p><p>In the second Data Story another stance is taken and discussed from this same data set. In this new data story new data visualizations are used which give an insight on how diverse and informative plots can be when used right.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2068def504df" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/data-story-1-2068def504df">Data Story 1</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ANN without an “E” — part II]]></title>
            <link>https://ai.plainenglish.io/ann-without-an-e-part-ii-a11ac1f8f149?source=rss-5edc935bf437------2</link>
            <guid isPermaLink="false">https://medium.com/p/a11ac1f8f149</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Mina Suntea]]></dc:creator>
            <pubDate>Fri, 22 Jan 2021 13:36:11 GMT</pubDate>
            <atom:updated>2021-01-22T14:08:20.546Z</atom:updated>
            <content:encoded><![CDATA[<h3>ANN without an “E” — part II</h3><h4>Implementing an Artificial Multilayer Neural Network using Linear Regression Analysis</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Zfb-DK8sA2Yk_7DK" /><figcaption>Photo by <a href="https://unsplash.com/@averey?utm_source=medium&amp;utm_medium=referral">Robina Weermeijer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In <a href="https://minasuntea.medium.com/ann-without-an-e-part-i-13803e0da1ca">part I</a> on of the easiest Neural Networks was introduced as well as some widely used methods and algorithms. However, to tackle the optimizing problem, a more complex model is needed. This model concerns the Multilayer Neural Network, which uses the same methods and algorithms as a basis but in this article there will be further elaborated on them.</p><h4>Multilayer Neural Network</h4><p>By combining the functions already discussed in <a href="https://minasuntea.medium.com/ann-without-an-e-part-i-13803e0da1ca">part I</a> an actual NN computation model can be built. Note that this model will for now only be able to compute an output given some input together with a matrix of weights. For this multilayer case, the outputs from the previous layer become the inputs for the layer after that. This combined input is the sum of the activations multiplied by their weights:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*DBESeGQf9A9V9CJkkmTf_g.png" /></figure><p>The activations for each node is then computed by taking the <em>Sigmoid</em> function over the combined node input:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/176/1*HFUU7g7RKMy2dnT9ICJEEQ.png" /></figure><p>This can again be used as input for the next layer until the output layer is reached. Then, expanding the single layer network from before to a 2 layer network looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*EeUynyiBWmjjy0qvWPZEuQ.png" /><figcaption>Wherein layer 1 is the hidden layer</figcaption></figure><p>In order to make a multilayer model, a complete matrix Θ is needed. First a function is needed that takes in a list of the layer sizes and returns an array of randomly initialized weight matrices of the corresponding dimensions to connect the layers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*k6BodKa3nBDtUDww4REZhg.png" /></figure><p>Next, a function is needed that takes in a matrix X and an array of matrices Θ and returns the final output layer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*zQd3bZDa_cgzZiKs2Z0AZA.png" /></figure><p>As discussed in the <a href="https://minasuntea.medium.com/ann-without-an-e-part-i-13803e0da1ca">previous part</a> of this series, the <em>Gradient Descent </em>is computed to minimize the error so the classification is as accurate as possible. This was easily computed having only a one layer network, for only the errors of the output nodes were needed. However, optimizing a multilayer network is more complex, as the errors of the hidden nodes in the hidden layers must also be computed. For this the <em>Backpropagation</em> algorithm is needed, which is defined by the equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*ge47YGMg0Y9H6n37y2E91g.png" /><figcaption>The δ’s take the δ’s of the next layer and propagate them backwards, hence the name :)</figcaption></figure><p>The <em>Backpropagation</em> algorithm is implemented by writing the function <em>hidden_delta</em>, which computes the matrix of δ values for one hidden layer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*528tEnj4QVGtvIow8JAgNA.png" /></figure><p>Now, all that is left to do, is combining the functions into a multilayer network, just like the function <em>one_layer_training</em> in <a href="https://minasuntea.medium.com/ann-without-an-e-part-i-13803e0da1ca">part I</a>, but this time for mulitple layers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*WKYQVoJFrxbPFo4vuJ53dg.png" /></figure><p>The functions <em>add_bias</em>, <em>compute_layer</em> and <em>weight_update</em> are all discussed in <a href="https://minasuntea.medium.com/ann-without-an-e-part-i-13803e0da1ca">part I</a>, so to take a look at the implementation and get a better understanding you should head over there.</p><p>I hope you enjoyed this series in which I discussed 2 basic Artificial Neural Networks. Keep track of my blog for more series like this!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a11ac1f8f149" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/ann-without-an-e-part-ii-a11ac1f8f149">ANN without an “E” — part II</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ANN without an “E” — part I]]></title>
            <link>https://ai.plainenglish.io/ann-without-an-e-part-i-13803e0da1ca?source=rss-5edc935bf437------2</link>
            <guid isPermaLink="false">https://medium.com/p/13803e0da1ca</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[classification-algorithms]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Mina Suntea]]></dc:creator>
            <pubDate>Thu, 21 Jan 2021 01:02:31 GMT</pubDate>
            <atom:updated>2021-01-21T16:42:58.852Z</atom:updated>
            <content:encoded><![CDATA[<h3>ANN without an “E” — part I</h3><h4>Implementing a basic Artificial Neural Network using Logistic Regression Analysis</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i4cnmJM0TYxHXS-T" /><figcaption>Photo by <a href="https://unsplash.com/@averey?utm_source=medium&amp;utm_medium=referral">Robina Weermeijer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Artificial Neural Networks (ANN), simply known as Neural Networks (NN), are a set of algorithms that mimic the processes of the human brain. This is a form of reinforcement learning which, at the basic level, consists out of inputs, weights, a threshold and an output. This way the NN learns to improve its performance by itself.</p><p>The most popular and widely used learning algorithm used for NN’s is Logistic Regression, that solves classification problems <strong>(HUH? Regression for classification??? Yes, the naming of this algorithm is confusing but this name was given for historical reasons)</strong>. The Linear Regression analysis estimates the coefficients of the linear equation, involving prediction of a value of a dependent variable using independent variable(s).</p><p>In this article the construction of a basic Artificial Neural Network will be shown step by step. Let’s get started on the most basic level, the parameters of just one single node in the whole NN. Just like in the human brain, activation is needed to let the neurons make connections. To mimic this in the NN, an activation function is needed and the most common type is the <em>Sigmoid</em> activation function, which is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/223/1*8qmL71Hi6-j90E5Vx--f3Q.png" /></figure><p>This is implemented in Python in a way that x can either be a single value or an array of values. This can easily be implemented using the <em>Numpy</em> built-in functions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*p5I9qlmCB0lYx4B2kHc9jw.png" /></figure><p>The model for Logistic Regression used here is the model described by <em>Ethem Alpaydin</em> in his book <em>Introduction to Machine Learning third edition</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*uWaKqd4rZqGyCrP5IEXjgg.png" /></figure><p>This model computes every dependent variable given a matrix X, but this equation can be simplified by expanding the matrix X with a column filled with ones, representing the bias inputs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*uceGwKzP3PRDqPhVJkg0KA.png" /></figure><p>Now the model for a single perceptron with 2 input variables becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*qBoC7e2CK6VV0eabOfltyQ.png" /></figure><p>With this new simplified model, Y can simply be computed with a matrix multiplication in which all the single node outputs are stored.</p><p>To expand the X matrix by adding bias inputs, the function <em>add_bias</em> is written:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*ZhlCPlcfVJ5-csePrrfRoA.png" /></figure><p>Note that until now only single node outputs have been considered, but NN’s are built from layers of these nodes. These layers consists of a combination of one or more <em>Sigmoid</em> nodes. By using multiple nodes on the output layer, it is possible to classify multiple classes, instead of having only binary classifications using a single node.</p><p>Each of the <em>Sigmoid</em> nodes will be needing a set of weights based on their inputs. Now that there will be one layer, the weights will be a matrix of the shape (<em>n</em>, <em>m+1</em>), where <em>n</em> is the node and <em>m</em> is the number of inputs plus the bias node. This matrix will be named Θ, where each row contains the weights for a <em>Sigmoid</em> node.</p><p>A single layer network, defining Θ⁰, looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*aNFDr_ApSQDX3we6xuF4cg.png" /><figcaption>3 input nodes plus 1 bias node, so it can distinguish 3 classes.</figcaption></figure><p>With the example given above, the matrix Θ⁰ will be of the size <em>3x4</em>. In a more complex network the Θ matrix is indexed like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/98/1*aLwgDK-4fTo2wPG40cPySA.png" /><figcaption>Which is the weight from node i in layer j to node k in layer j+1.</figcaption></figure><p>With the <em>one_layer_init </em>function the matrix Θ⁰ is created given the input and output size. It is important to randomly initialize the weights because partial derivatives will be used to find the optimal values and therefore every node should have a different derivative:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*ESUdgLX1L8F1B7oVVGgQMQ.png" /></figure><p>Now it is time to implement the functions that compute the activations for a single layer. Therefore the functions <em>compute_layer</em> and <em>one_layer_output</em> are written. The <em>compute_layer</em> function takes the matrix Aʲ and Θʲ and returns the following A matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*A_jRW7siV5R7PF7sIR7KFw.png" /></figure><p>The <em>one_layer_output</em> takes a matrix X, that consists of training samples, and Θ⁰ and returns a matrix of outputs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*rkl0n9vrI49D5Jx3Rp-rrw.png" /></figure><h4>Gradient Descent</h4><p>To obtain the best fit possible the cost function must be minimalized. With this more complex model, just computing the partial derivative won’t be sufficient. In the case of Linear Regression <em>Gradient Descent</em> is used to incrementally move all parameters to the gradient to minimize the cost. This cost function is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*mUFzNfnif2fNxZIgDT7aEg.png" /><figcaption>Where M is all training samples, K is all different outputs and where the current output is compared to the target output.</figcaption></figure><p>Implementing this in Python looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*-MBExgGWPm_XVo_2dI7MHA.png" /></figure><h4>The Delta Rule</h4><p>To minimize the cost function, the partial derivatives of each parameter must be taken. First δ is defined, which contains the partial derivatives of the cost function with respect to the nodes input. This is defined for each node <strong><em>i</em></strong> in each layer <strong><em>j</em></strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/1*dsI8EzCYrTDA782Mlu0HQw.png" /></figure><p>For the output layer δ is defines as (<strong><em>j</em></strong> is the last layer):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/189/1*HTPtFyzuAT6q2ZHXctLI7g.png" /></figure><p>To compute this, the function <em>output_delta</em> is written:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*Vwc1zJkjsT6QnEwBrepJsw.png" /></figure><p>After computing the δ terms, the derivatives can be computed. The weight update is defined by the following equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*wKH7LkSJXmIvmNCC0QcUzg.png" /></figure><p>When all the resulting values are summed over all M training samples, this will result in the overall gradient on the cost function for all parameters in one layer, also known as <em>Batch Gradient Descent</em>. The actual update of the weight is then just equal to the standard <em>Gradient Descent </em>method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*WNdi3PovNF7syovhi36tRQ.png" /></figure><p>Implementing this for the weight update of one layer gives:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*dxwZ3tj2bwXmh6lYJUQIfQ.png" /></figure><p>With all of these additional functions combined, the single layer network can be trained. Given a training data set, the outputs will just repeatedly be computed for each training input. Then de corresponding δ’s will be computed based on the training outputs, after which, lastly, the weights will be updated. The more iterations, the better the outcome and thus the lower the error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*phZsJt77BnDsSfHOWV69gw.png" /></figure><p>Now the single layer network is completed, but we can do better! In the next article a more complex model will be implemented and discussed, that optimizes better than this basic single layer network.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13803e0da1ca" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/ann-without-an-e-part-i-13803e0da1ca">ANN without an “E” — part I</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decisions, Decisions… — part II]]></title>
            <link>https://ai.plainenglish.io/decisions-decisions-part-ii-114df52f883f?source=rss-5edc935bf437------2</link>
            <guid isPermaLink="false">https://medium.com/p/114df52f883f</guid>
            <category><![CDATA[decision-tree]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Mina Suntea]]></dc:creator>
            <pubDate>Mon, 18 Jan 2021 20:53:51 GMT</pubDate>
            <atom:updated>2021-01-18T21:40:53.649Z</atom:updated>
            <content:encoded><![CDATA[<h3>Decisions, Decisions… — part II</h3><h4>The Numerical Decision Tree + Random Forest method</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pC7igqwHfBc7cVm-" /><figcaption>Photo by <a href="https://unsplash.com/@garri?utm_source=medium&amp;utm_medium=referral">Vladislav Babienko</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In <a href="https://medium.com/ai-in-plain-english/decisions-decisions-part-i-f509f2130991">the previous part of this series</a> (the implementation of) the Categorical Decision tree was discussed, but there are also Numerical Decision trees and that is what this article is covering today!</p><h4>The Numerical Decision Tree</h4><p>The definition of ID3 described in <a href="https://medium.com/ai-in-plain-english/decisions-decisions-part-i-f509f2130991">part I</a> of this series is restricted to taking on a discrete set of values. The target value, that is learned by the decision tree, as well as the attributes that are tested in the decision nodes must be discrete valued. But it is possible to extend the Categorical Decision Tree to also include numerical boundaries, so continuous-valued decision attributes can also be incorporated in the decision tree. These boundaries can be used to select the best <em>Information Gain</em> for both the categorical and numerical splits.</p><p>The most important difference between categorical and numerical decision trees is the splitting of the data. With categorical data, the data is split into categories. This is impossible to do with numerical data, for there are an infinite amount of categories. Therefore the Categorical Decision tree uses binary splits, also known as boundary splits, where a new branches are created each split (one for values smaller than the boundary and one for values larger than or equal to the boundary).</p><p>By applying repeated binary splits on a numeric variable, different decisions regions can be created. This means that the feature that was split on, will not be ignored in further splits in a Numerical Decision tree, unlike in a Categorical Decision tree. So, in other words, this way of splitting even improves the accuracy.</p><p>This time the tree won’t be constructed from scratch, but the <em>scikit-learn</em> library will be used. The <em>DecisionTreeClassifier</em> from this library can build a Decision tree from numerical data. The numerical part of the data split before (in <a href="https://medium.com/ai-in-plain-english/decisions-decisions-part-i-f509f2130991">part I</a>) will be trained and the accuracies of both the training and test set will be visualized:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*iJuz2pOc_50rXjXeXbwD3g.png" /><figcaption>Using the fit and predict functions</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*qt_RAXuL2RQZsYCeAJ2lxA.png" /></figure><p>The <em>scikit-learn </em>Decision trees implementation is only fit for numerical features, so it does not actually support categorical data. This implementation can still be made to work by numbering the categories. <strong>This is actually strongly discouraged as it will make suggestions about the categorical data, namely their numerical order. </strong>Since <a href="https://medium.com/ai-in-plain-english/decisions-decisions-part-i-f509f2130991">the used data</a> already has numbers for each category, this implementation can be used.</p><p>From this the training and test accuracies can also be printed as well as from the complete mixed data, numerical and categorical:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*lQ_rYApkOy2Rf5g6TMLhtA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*eJpgiIDmvHa5vInnVP4ZXA.png" /></figure><p>Trees learn by beginning with the full training set and greedily adding conditions that maximize the following node’s label purity. This way the leaf nodes grow exponentially as more depth is added to the tree. This way the trees are prone to overfit, which can be solved by pruning the tree or setting a threshold on the minimum of the <em>Information Gain</em>.</p><p>With <em>DecisionTreeClassifier</em> from the <em>scikit-learn</em> library the <em>min_samples_split</em> function can be used to set the minimum number of samples that are required to be in a node before splitting. That way it stops splitting and makes the predicted label the most common label.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*1Ibwtx1R3880uVpPQ0SW1w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*41iXraISnzIAKas-L7UWfA.png" /></figure><p>The physical tree can also be plotted with another argument of the <em>DesicionTreeClassifier</em>, with which the <em>max_depth</em> can be set so the tree will stay readable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*fJmNYmg901YlPVYORNtsfw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7xyHg7Vbz57QijCjnvTFEg.png" /><figcaption>It’s more readable in Jupyter Notebook :)</figcaption></figure><p>However, reducing overfitting can also be realised by applying the ensemble approach. One of the most common ensemble methods for decision trees is the Random Forest method. This method leads to a better model performance, for in this method a lot of decision trees are being trained on a random subset of the data after which they all predict an unseen sample and the majority vote is used as the final prediction. A single tree is highly sensitive to noise in the training data, unlike the average of many decision trees trained on similar data.</p><p>A simple but effective implementation of the Random Forest will be shown, also using the <em>DecisionTreeClassifier</em>. This way first a function called <em>create_forest</em> that accepts the number of trees that should be in the forest and returns a list containing all the <em>DecisionTreeCalssifier</em> objects:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*mQ-9rGrtDMtDMh9o2x1I5A.png" /><figcaption>Maximum amount of features changed to the square root of the number of features</figcaption></figure><p>Next, the <em>train_forest</em> function is written that accepts the forest and trains each of the trees using the ratio samples from the data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*NXVOkj3yCE88ZQq5JZjHMA.png" /></figure><p>To predict the target label for the given data, the <em>predict_forest</em> function is written. This function accepts a forest and the data and returns the predicted target label:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*7JPVmV19V_KMmZ0xXcJq6Q.png" /><figcaption>In this case there are only 2 possible predictions, True or False, which are equal to 1 or 0. The predictions can therefore just be added to each other and devided by the number of trees so the average vote can be rounded to either 1 or 0</figcaption></figure><p>Now a random forest can be created. In this case 1000 trees are created, that each only use 3 or 4 features and train each forest with a 50% random sample of the complete data set. Using these values, the training and test accuracies can be printed out for both the Random Forest method and 1 tree:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zy86AJz_9GOmw_43wguL-A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*_GLm2wa04kFj8Ghc3JRDdQ.png" /></figure><p>As can be derived from comparing the training and test accuracy, the Random Forest method does perform better. This brings me to the end of the Decision Tree series where I discussed both the Categorical Decision tree as well as the Numerical Decision tree. I hope you have a better understanding of what Decision Trees are and how they work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=114df52f883f" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/decisions-decisions-part-ii-114df52f883f">Decisions, Decisions… — part II</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decisions, Decisions… — part I]]></title>
            <link>https://ai.plainenglish.io/decisions-decisions-part-i-f509f2130991?source=rss-5edc935bf437------2</link>
            <guid isPermaLink="false">https://medium.com/p/f509f2130991</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[decision-tree]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Mina Suntea]]></dc:creator>
            <pubDate>Fri, 15 Jan 2021 16:25:07 GMT</pubDate>
            <atom:updated>2021-01-16T22:22:12.863Z</atom:updated>
            <content:encoded><![CDATA[<h3>Decisions, Decisions… — part I</h3><h4>Building a Categorical Decision Tree using ID3 algorithm</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*M8qK9LsbPIcZqc3A" /><figcaption>Photo by <a href="https://unsplash.com/@leliejens?utm_source=medium&amp;utm_medium=referral">Jens Lelie</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Decision tree learning is a supervised learning method for both classification and regression tasks. A decision tree visualizes decision making in a form of a tree, which can also be represented in if-then rules for the sake of readability.</p><p>This method seeks to approximate discrete-valued functions, is able to work with messy data and is capable of working with disjunctive expressions. Decision trees are widely used for inductive inference which makes the decision tree method one of the most popular inductive inference algorithms.</p><p>There are a lot of different decision tree algorithms like C4.5, ASSISTANT and ID3, which are all different in their capabilities and requirements. Despite these differences in the decision tree algorithms, there are general problems for which decision tree learning in general is best suited for, namely:</p><ul><li><em>Instances are represented by attribute-value pairs, categorical values as well as numerical values.</em></li><li><em>Target function has discrete output values</em></li><li><em>It must be possible to provide disjunctive descriptions</em></li><li><em>The data may contain errors or missing values</em></li></ul><p>In this first part of this series the implementation of the ID3-algorithm will be shown step by step, as well as the preprocessing of the data. The data for the Numerical Decision tree in part II contains heart diagnosis results from 4 different hospitals, that can be found at: <a href="https://archive.ics.uci.edu/ml/machine-learning-databases/heart-disease/">https://archive.ics.uci.edu/ml/machine-learning-databases/heart-disease/</a>. This dataset will also be used for the Categorical Decision Tree as well as a small self-made test dataframe.</p><p>It is recommended to first take a look at the <em>heart-disease.names</em> file, which contains a description of the dataset and explanations about the variables. Looking at this dataset the first thing that can be derived, is that it consists out of categorical and numerical data as well as target features. A whole mix of data types…</p><h4>Getting familiar with the data</h4><p>First, the 4 <em>processed.X.data</em> files must be downloaded. For clear visualization of the data, using the Python library <em>Pandas</em>, is recommended with which the data can be loaded into a <em>DataFrame</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pkp72Mv0o_jkBNbqpgJLnA.png" /><figcaption>Names of columns are manually set using heart_disease.names</figcaption></figure><p>By printing the variable <em>data</em>, the heart disease data set can be looked at and understood by using the <em>heart_disease.names</em> file.</p><h4>Preprocessing the data</h4><p>The variable <em>data</em> contains the 4 dataframes of the 4 files. Printing <em>data</em> should result into noticing unexpected values, namely question marks. These values indicate missing values, which are not convenient to have amidst your data. There are different ways to solve this problem, like replacing the missing values, or handling them in a separate way. The easiest way is to just remove all the rows with the missing values. The handiest approach for this is to concatenate the 4 separate dataframes into 1 big dataframe first and delete all the rows with missing values in them afterwards:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*cJAwA3tVMwHIHjHGIIIniA.png" /><figcaption>Turned all question marks into NaN-values so dropna() function could be used</figcaption></figure><p>With <em>Counter</em> from the <em>collections</em> library the occurrence of each label in the target variables can be retrieved:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*el95yOS4plDt-XWgz9-86A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*vhh7j2GuVj0ITk1vzJfwsA.png" /></figure><p>The number of each of the labels differ a lot, which is not advantageous for any classification task, for the classifier will be biased towards the most common class (in this case 0). In the <em>heart_disease.names</em> file the definition of these labels are given. For the sake of the distribution, the focus lies on classifying the difference between 0 and the rest of the higher values. So now the target column can be simplified by changing the labels to Boolean values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*SyChrHomFjgNAE_CED5qzA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*KQua5-NSPOAHqK2bTIrxsQ.png" /><figcaption>Using Counter again to visualize the amount of True and False values</figcaption></figure><h4>Categorical Decision Tree</h4><p>Constructing a Decision Tree using the ID3 algorithm is a bottom-up process, also known as pruning to improve accuracy, where first the feature containing the most information is sought out. When the most important feature is found, the data set gets split along the rows of that feature that have the same value. This process keeps repeating itself until a stopping criterium is achieved. The implementation discussed in this article consists of 4 steps.</p><h4>Step 1: Split</h4><p>First the split process of the data must be defined as a function and for this the unique values of each column must be determined, using the <em>unique_values</em> function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*H_nbbXVIC4kq83fsdnTlSw.png" /></figure><p>Now this function can be used in the <em>create_split</em> function, which returns a dictionary given a dataframe and a column name. The unique column values are being used as keys and the split dataframes as values. So the dataframe rows are grouped by each of the different unique values from that column:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*L_2sFc1VqkMSRi2I-DBwAg.png" /></figure><h4>Step 2: Entropy</h4><p>Second, the entropy must be computed. Entropy has different definitions, but for decision trees the information theoretic entropy is applicable. The information theoretic entropy, also known as Shannon entropy, says something about the amount of information contained in a distribution of the data. So the less intricate the distribution, the less bits are needed on average to express the distribution.</p><p>This measure of entropy will be used to compare the decisions of the decision tree and establish which contains the most information. After simplifying the data, by changing the labels to Boolean values, only 2 classes are left and for a problem with 2 classes the entropy is defined as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*jRh89Nf1vaoUvyrPh4vSXg.png" /><figcaption>Where <strong>p</strong> is the ratio between the labels for the 2 classes</figcaption></figure><p>To construct the <em>entropy</em> function and implement this equation in Python, the equation is separated into 3 parts:</p><ol><li>calculate the ratio <strong><em>p</em></strong>:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*UscNXn1_wrxQv7YAf2E28g.png" /></figure><p>2. Compute all values of the log product and return 0 in the case <strong><em>p</em></strong> = 0:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*TuWiu7-D7kU0cyYb4kgykA.png" /></figure><p>3. Finally, combine the functions of part 1 and part 2 to implement the entropy equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*Fh4zddhZ4CcY8YOPjfOBVg.png" /><figcaption>Note that it is being checked if p = 1, for the second part of the equation will then be multiplicated by zero</figcaption></figure><p>To check if the entropy function works correctly a <em>plot_entropy</em> function is written to plot the entropy. The plot should look like a parabola with the opening downwards:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*sVO-Ku_Qg7R863sVFxcMdQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*w_IuVklXFvOu7FBlYiQIsA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*-KIKIdQPzwGUsA7jHGEH4g.png" /></figure><h4>Step 3: Information Gain</h4><p>Next, a metric must be computed to assess how good the splits are in the decision tree. In this implementation the <em>Information Gain</em> is used, which is defined as the entropy of the original distribution <strong><em>Φ(p)</em></strong> minus the entropy of the split distribution <strong><em>Iₘ </em></strong>resulting from the split on <strong><em>m</em></strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*_l7YRbrx-XgvovHYqkacZQ.png" /></figure><p>This metric keeps track of how much the entropy changes after making a specific split, so it measures the gain in predictability of the data as a result of making a distribution based on a specific variable. When a set of target labels is split on a specific variable, 2 or more lists are created with their own entropy. Combining the resulting entropies from a split into new sets afterwards is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*e5EoWHUd3aGSdniL-G0y7w.png" /><figcaption>Where <em>Nⱼ is the size of the jth split distribution and N is the size of the distribution before the split</em></figcaption></figure><p>Implementing this equation in Python to compute <strong><em>Iₘ</em></strong>, using a function called <em>split_entropy</em> looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*_0nimF8GpXwCxG-4jByHjA.png" /></figure><p>The <em>get_split_labels</em> function is needed to convert the dictionary, that <em>create_split</em> returns, into a list of lists containing the target labels of each of the splits. The format should be preserved so it can be used directly as input for the <em>split_entropy</em> function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*uNtpTraMYEh5xPQ9w1EAKg.png" /></figure><p>Now the <em>Information Gain</em> function can be implemented using the <em>entropy</em>, <em>split_entropy </em>and <em>split_labels</em> functions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*y3e4tD8M0KE3317oJGHK_Q.png" /><figcaption>Concatenated the list of lists split_labels so <strong><em>p </em></strong>could be computed directly</figcaption></figure><h4>Step 4: ID3</h4><p>All the tools for constructing the ID3 algorithm are provided now. First, to make things more clear, a named-tuple <em>Node</em> is created, that carries the selected split column, the most common label in this node and a dictionary mapping to results of the split:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*duB17ibutuz3bePAJurJxA.png" /></figure><p>The steps of the ID3 algorithm can be simply explained in 7 steps:</p><ul><li>Use <em>unique_values</em> function to return the pure label.</li><li>Return the most common label <em>mode()</em> if there are no more possible columns to split.</li><li>Calculate the <em>Information Gain</em> for each possible split in the dataset.</li><li>Pick split with highest <em>Information Gain</em>.</li><li>Create a Node for new/current branch of the tree</li><li>Recursively call ID3 with the sub-dataset to create sub-tree and use it as branches for the tree of the step before</li><li>Return Decision Tree</li></ul><p>First the test dataframe is manually programmed and a test target is set, like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4dlMh_UyhzVekmLaVnxSMg.png" /></figure><p>Now all the 7 steps can be computed to create the ID3-algorithm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*iVVE-SVvHIoq-iapCqPpJw.png" /></figure><p>Putting the test dataframe into the ID3 function thus results in the following “tree”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*4gknW2TeXP9z9NLdVuNJdQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ur5QGFzNSl2DE331_bOuaA.png" /></figure><p>Now that a tree is built, it is important to realise that the ID3-algorithm does NOT search the entire space of possible trees to find the best possible decision tree. Instead looks at the best decision per node, making locally optimizing choices, which are not always globally optimal.</p><h4>Classifying</h4><p>The tree can be now used to classify a given row of the dataframe. Per branch there are 3 choices:</p><ol><li>When there is a Node attached to this branch, look further.</li><li>When a leaf node (last node of a branch) is encountered, return it.</li><li>If the value from the column in the row doesn’t have a corresponding branch in that node, then return the most common label in that node.</li></ol><p>The function <em>classify</em> was written for this, which takes a tree and a row which has to be classified:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*NzmDSTsz5TOwVkhsH4Xrkw.png" /></figure><h4>Validation</h4><p>Now that everything is complete, the ID3-algorithm can be applied on the heart disease dataset. First, a validation split must be created to create a training and test set. This can easily be done by using <em>train_test_split</em> from the <em>sklearn.model_selection</em> library:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*iEhEecTR4FfmQpimrqWd7A.png" /></figure><p>Next, a function is needed to split the categorical from the numerical data and create training and test sets from both datasets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*Do0vl2nZD8HyvUYfYUsRww.png" /></figure><p>Finally, a <em>validate </em>function is written that takes a decision tree, a dataframe and the target column name. It should first classify all rows in the dataframe using the decision tree and then return the percentage that was classified correctly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*QqtSv1QmDEBO7hrxdz---g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*wEUXozcrfFPq-xbvo5i-pw.png" /></figure><p>The Categorical Decision Tree is officially done! In the next part of this series I will be discussing the Numerical Decision Tree.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f509f2130991" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/decisions-decisions-part-i-f509f2130991">Decisions, Decisions… — part I</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting the future using Machine Learning part VI]]></title>
            <link>https://medium.com/analytics-vidhya/predicting-the-future-using-machine-learning-part-vi-ab2d1a4f9c3d?source=rss-5edc935bf437------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab2d1a4f9c3d</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[clustering]]></category>
            <dc:creator><![CDATA[Mina Suntea]]></dc:creator>
            <pubDate>Wed, 13 Jan 2021 13:00:09 GMT</pubDate>
            <atom:updated>2021-01-14T21:20:45.498Z</atom:updated>
            <content:encoded><![CDATA[<h4>K-means and Elbow Method + implementation in Python</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HmSQuT6OjB1KZOUh" /><figcaption>Photo by <a href="https://unsplash.com/@oskaryil?utm_source=medium&amp;utm_medium=referral">Oskar Yildiz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>After completing the main types of supervised Machine Learning algorithms, it is time to discuss a unsupervised Machine Learning algorithm. A classic example of unsupervised learning is the K-means algorithm, which I will be discussing in this final article of this series as well as the Elbow Method.</p><h4>K-means</h4><p>For the K-means algorithm we don’t have a target output we are trying to model, but instead we are just trying to extract a pattern from the whole dataset. The goal of the K-means algorithm is to find <em>k</em> amount of clusters within the dataset, which are represented by their centers. This clustering method seeks to find similarities between instances and group instances in contrast to the dimensionality reduction method, which seeks to find correlations between features and group features (<a href="https://medium.com/analytics-vidhya/predicting-the-future-using-machine-learning-part-iv-8747b319be5c">part IV</a> and <a href="https://minasuntea.medium.com/predicting-the-future-using-machine-learning-part-v-d8e9c54ef415">part V</a>).</p><p>I implemented this algorithm by creating 7 functions and to illustrate and test my final K-means algorithm, I used the last 2 variables of the <em>Iris</em> dataset just like in <a href="https://medium.com/analytics-vidhya/predicting-the-future-using-machine-learning-part-v-d8e9c54ef415">part V</a>.</p><p><em>init_clusters</em>: random initialization of the means from the data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*6ANWDe0bwPNx8Gu0ypdPtg.png" /></figure><p><em>distance</em>: computes the distance between 2 points</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*D4aiF-l-beSGMy69s0Udcw.png" /></figure><p><em>cluster_assignment</em>: computes a matrix <strong>b, </strong>which contains the assignments of points to clusters, based on the current means</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*wUhd3qeVETj96VK2hQreYA.png" /></figure><p><em>compute_means</em>: computes the matrix <strong>m</strong> containing the computed mean vectors, based on the current assignments of clusters</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*1I_OF8JyTwddVbRtcN5jXg.png" /></figure><p><em>plot_clusters</em>: plots the means and their assigned points with different colors per cluster</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*TP_YKh7J1bUZ-u_1yovAqw.png" /></figure><p><em>is_converged</em>: determines if the algorithm has converged based in the sets of current and new means (minimum Error value has been reached), using a threshold</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*WohGHcBXYLtrZ9LQvdFm_Q.png" /></figure><p><em>k_means</em>: creating the k-means function by combining all functions above</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*BrQDXEkn6cb9gIRjBVrG3w.png" /></figure><p>Testing the <em>k_means</em> algorithm with the <em>Iris</em> dataset gives;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*50NhEUT9BrocZ_E20SRNew.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*JypyZxBlYJovsN-eJNbmpw.png" /></figure><p>In the graphs shown above, I chose a value of 1 for k and plotted 1 step of the algorithm. Where the means of the previous step and the step after that one is visualized. In this case the last step where the means have converged. This way you can see how the mean moves as it iterates. When choosing a higher value for the 3ʳᵈ argument of the k_means algorithm, more iterations can be visualized.</p><h4><strong>Elbow Method</strong></h4><p>By using the <em>Iris</em> dataset, we had the advantage of knowing beforehand how many clusters there are. But even without knowing the number of clusters in a dataset, there are still ways to solve the clustering problem. One such possible approach is the Elbow Method.</p><p>For this method only 2 additional functions had to be constructed, namely a sensible <em>cost</em> function that is minimized and an <em>average_cost</em> function, which computes the average cost for <em>k</em> values 1 to a determined number and combines them in a plot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*aMM6cgCDFe-gQYLPBk67bg.png" /><figcaption>Computed the cost 20 times to determine the average cost</figcaption></figure><p>The only thing left to do now is plotting the average cost per <em>k</em> value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*AMYt2bqPmMfE4oTzPzclXg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*D_jJckovW7gSTnewQWmznQ.png" /><figcaption>Looks like an elbow! Hence the name</figcaption></figure><p>With this article I have reached the end of this series! I have shown and discussed the main types of Machine Learning algorithms, supervised as well as unsupervised. With these algorithms you already come a long way in trying to make accurate predictions using Machine Learning. I hope you enjoyed this series and keep track of my page for more (upcoming) series like this!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab2d1a4f9c3d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/predicting-the-future-using-machine-learning-part-vi-ab2d1a4f9c3d">Predicting the future using Machine Learning part VI</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting the future using Machine Learning part V]]></title>
            <link>https://medium.com/analytics-vidhya/predicting-the-future-using-machine-learning-part-v-d8e9c54ef415?source=rss-5edc935bf437------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8e9c54ef415</guid>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Mina Suntea]]></dc:creator>
            <pubDate>Tue, 12 Jan 2021 13:09:30 GMT</pubDate>
            <atom:updated>2021-01-12T16:06:54.384Z</atom:updated>
            <content:encoded><![CDATA[<h4>Multivariate and full bivariate distributions + implementations in Python</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7drc1Tki7CUClbYH" /><figcaption>Photo by <a href="https://unsplash.com/@dlanor_s?utm_source=medium&amp;utm_medium=referral">Dlanor S</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://minasuntea.medium.com/predicting-the-future-using-machine-learning-part-iv-8747b319be5c">Part IV</a> of this series discussed a classification algorithm using a univariate model, but in this article we will take it one step further by building an even better classification algorithm. I will be introducing multivariate distributions, which work with more than 1 variable. Therefore these models result into better outcomes.</p><h4>Multivariate distributions</h4><p>We will still be using the probability density function for normal distributions, but now we need the multi-variate version, which looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*3i3muou5bvnkvRNaXxJ_jA.png" /><figcaption>Where <strong><em>x</em></strong><em> is a d-dimensional vector drawn from the Normal distribution with mean vector μ and covariance matrix Σ.</em></figcaption></figure><p>Now it would be possible to use all 4 variables from the <em>Iris</em> dataset and compute the vector of means and the covariance matrix for each class. These can then be used to compute the probability density functions for each class using the equation above. With these, also the posteriors for each class can be computed and finally the <a href="https://minasuntea.medium.com/predicting-the-future-using-machine-learning-part-iv-8747b319be5c">Bayes Classifier</a> could be used again to classify the data points into the most probable class.</p><p>However, if there are too many variables, the number of parameters for the covariance matrix can become too large to properly fit the amount of data. Therefore it is common to make simplifying assumptions about the data to decrease the complexity of the data.</p><h4><strong>Naive bivariate distributions</strong></h4><p>One of the well known variants is the <em>Naive Bayes</em>, where the assumption is that all variables are independent. This means that only the variance for each variable is being used instead of the covariances. This simplifies the covariance matrix in such a way that it only has entries on the diagonal.</p><p>First I will discuss the bivaraite (2 variables) distribution, for this will be easier to plot and thus reason about. I used the petal data (petal width and petal length) as 2 variables as they seemed to result into nice clusters. The assumption of independence of the <em>Naive Bayes</em> model simplifies the equation a whole lot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*lP5v6CVIt_ec61jV0LEHbA.png" /><figcaption>Where p(x₁|Cᵢ) is the univariate distribution using μ₁ and σ₁ from the first variable and p(x₂|Cᵢ) is the same equation using μ₂ and σ₂ from the second variable</figcaption></figure><p>Now the probability density function must be computed, just like I did for the <a href="https://medium.com/analytics-vidhya/predicting-the-future-using-machine-learning-part-iv-8747b319be5c">Bayes Classifier</a>, for which I wrote the <em>PDF_naive </em>function. It is also necessary to retrieve the mean and standard deviation of the petal width data, like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*u331NwCi_QBFXvTYZ-HcAQ.png" /></figure><p>After retrieving all the needed data, it is time to plot the probability density functions. Now that we use 2 variables, it will be a 3d plot. There are several ways to make a 3d plot in <em>matplotlib </em>but I chose the contour plot. First a mesh must be created of X and Y values, using linspace, for each dimension which must be combined with a meshgrid. Then the Z values can be computed for the probability density function for each class and these will be the contour plots:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*rTlfAahJJo47NzB8c0abVA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*qv2Iv-xZ4-DMT5-F9nzgfw.png" /></figure><p>All that is left to do now, is compute the posteriors, the classifier and the validate function as well as making the mean and standard deviation vectors of the petal width data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*f7oWVBkTtMoRISl7OpxRDA.png" /></figure><p>Using the <em>validate_naive</em> function the percentage of correct predictions for each class can be reported as well as the average of correct percentages:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8-Gw3foEJbxJ-rJFlIg3IQ.png" /></figure><p>These result in the values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*_Wzyx4YqbGi9Xu9h1WU8pQ.png" /></figure><p>The posteriors can also be visualized in a graph in the same way as the probability density functions. This way the decisions regions are illustrated with the contour plots:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*AF3pQVB3-mat-77agk3_cw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*lMqcbupNgnPG29FRDHOkVA.png" /></figure><h4>Full bivariate distribution</h4><p>Finally, we will compare this <em>naive bivariate distribution</em> with a <em>full bivariate distribution</em>, using the complete covariance matrix. This can easily be done using the built-in function <em>multivariate normal distribution</em> from the <em>SciPy</em> stats module. These function creates a distribution given a mean vector and a covariance matrix. These can be then computed by using the <em>mean</em> and <em>covariance</em> functions from <em>Numpy</em>.</p><p>With this new function the probability density function can be illustrated again just like we did with the <em>naive bivariate distribution</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*zC2Xitm9e0fbrDuA2kXCqg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*Rk5ZenA0vqUuFNxuWsGjEw.png" /></figure><p>Now, in the same way, with the <em>posterior</em>, <em>classify</em> and <em>validate</em> functions, the results can be computed. For this model I constructed those functions a bit different so the code wouldn’t be too many lines:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*uvImvOLTBL24eCUSeEFQfw.png" /></figure><p>Lastly, the results can be computes and visualized:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*ji5xc4OOBo_ohIfTHelYTQ.png" /></figure><p>These result in the values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*GpSRZBjhBSmHh16nIhg-Fw.png" /></figure><p>From the results shown above it is clear that, the more variables you use, the better the classifications. With these models I have reached the end of this article and also the end of discussing the supervised Machine Learning algorithms. In my next article I will be showing an example of an unsupervised Machine Learning algorithm.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8e9c54ef415" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/predicting-the-future-using-machine-learning-part-v-d8e9c54ef415">Predicting the future using Machine Learning part V</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting the future using Machine Learning part IV]]></title>
            <link>https://medium.com/analytics-vidhya/predicting-the-future-using-machine-learning-part-iv-8747b319be5c?source=rss-5edc935bf437------2</link>
            <guid isPermaLink="false">https://medium.com/p/8747b319be5c</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[classification]]></category>
            <dc:creator><![CDATA[Mina Suntea]]></dc:creator>
            <pubDate>Mon, 11 Jan 2021 00:51:06 GMT</pubDate>
            <atom:updated>2021-01-11T17:01:55.578Z</atom:updated>
            <content:encoded><![CDATA[<h4>Bayes Classifier using Normal Gaussian distribution + implementation in Python</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Jh9EmVPryfRNgLEc" /><figcaption>Photo by <a href="https://unsplash.com/@blakeconnally?utm_source=medium&amp;utm_medium=referral">Blake Connally</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article I will be covering another main type of supervised learning algorithm, namely classification. Specifically, I will be showing how I build a Bayes Classifier using Normal Gaussian distribution to estimate the likelihood of continuous variables.</p><p>The dataset used for this is the classic <em>Fisher’s Iris dataset</em>, which contains the measurements of the lengths and widths of the sepals and the petals of 150 flowers. The <em>Fisher’s Iris dataset</em> is such a classic example that it is included in Machine Learning libraries, so everyone can retrieve it by importing the dataset from the <em>scikit-learn</em> library.</p><h4>Separating and plotting the data</h4><p>The first step is retrieving the dataset, which is an easy import, and naming it <em>iris</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*425Nmm76N-fi8tCZ_FKq9w.png" /></figure><p>The <em>iris</em> variable now contains all sorts of information, but the most important attributes are <em>target</em> and <em>data</em>, which contain the labels and datapoints for the 150 flowers. So I extracted these attributes and created a matrix X with the <em>data</em> and a vector R with the <em>targets. </em>By using the vector R, it is now possible to divide the matrix X in different classes, like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*owWnGXaBLxH4mV4p5AS_WQ.png" /><figcaption>Indexing can make your life easier…</figcaption></figure><p>To get an idea about the correlations and the separability of the dataset, we should plot this data. Using the <em>seaborn</em> library, the distributions for every single feature can be visualized as well as scatter plots using 2 features as the <em>x</em> and <em>y </em>axis:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*j1QlcKnDtvDwBXWZgyYwNA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*2mVJW1unGcGgd0vAiR9_nw.png" /><figcaption>Diagonal plots are distribution of all features and the scatter plots are all different configurations of 2 features</figcaption></figure><p>Looking at these plots, it can be derived that the <em>setosa</em> species is more easily seperated than the other species. That does show that a lot of the features of the other species, <em>versicolor</em> and <em>virginica</em>, are correlated with each other.</p><h4>Covariance</h4><p>One of the measures of the correlation between variables is the covariance. The covariance between 2 jointly distributed real-valued random variables <strong>X</strong> and <strong>Y</strong> is defined as the expected product of their deviations from their individual expected values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*IlKw0bbMuYnZrYT-DuUrVg.png" /><figcaption>E[…] is the expected value</figcaption></figure><p>When covariance is positive, then the variables are positively correlated: when one variable increases in value, the other value will probably also increase. But when the covariance is negative, the variables will be negatively correlated: when one variable increases, the other value will probably decrease. Finally, when the covariance is near zero, there is not correlation between the variables.</p><h4>Bayes Classifier</h4><p>After getting familiar with the data, it is now possible to build a model that will predict what class (in this case <em>iris species</em>) a given datapoint belongs to based on the other variables. To determine how well the model fits to the data, we will use the <a href="https://medium.com/analytics-vidhya/predicting-the-future-using-machine-learning-part-iii-410e1a1742c7">Cross Validation</a> method. I used the <em>validation_split</em> function from part III as inspiration, but this <em>validation_split</em> is slightly different:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*D-BEkXnrc39LNeB7lHZmIw.png" /><figcaption>Outputs splitted datasets given a ratio</figcaption></figure><p>Using this function on each of the 3 classes, with a ratio of 0.7 for each, you get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*ESr-bfyx6itPWTqAjl4E_A.png" /><figcaption>Training and validation sets for each class</figcaption></figure><p>From the scatter plots illustrated above can be derived that separating the different classes would be a lot easier based on the petal data (petal width and petal length) than on the sepal data, as it is easier to distinguish the different clusters in that plot. I decided to narrow it down even further and focus on only 1 variable at first, namely the petal length. This variable is very useful on its own and already simplifies the model a lot.</p><p>Using the training sets of all 3 classes I started to compute the mean and standard deviation for the petal length attribute for each class. For these computations the built-in Numpy functions for mean and standard deviation will deem useful:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*CvktmzPmI1AgiL1XslX_lw.png" /></figure><p>Now that we made estimates for the mean and the standard deviations for the petal length for each of the 3 classes, we can compute the <em>probability density function (PDF)</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*nY7zdaO-jCMWkFV4E3zQ2g.png" /><figcaption>Where X is Gaussian normal distributed with mean μ and variance σ²</figcaption></figure><p>Implementation in Python looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*A_aU7i7DdFzDXpgj0RgRpg.png" /></figure><p>Next, the probability density functions of all 3 classes can be computed and visualized using linspace, just like in <a href="https://medium.com/analytics-vidhya/predicting-the-future-using-machine-learning-part-ii-fb45806e5b71">part II</a>, for a range of x-values and compute the corresponding y-values by applying the <em>PDF function</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*--Z_nuFWFrM1Ogh8gGDbow.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*rnvmarl2QlARO67ujyWKmQ.png" /></figure><p>The plot above shows the probability desities for a value x, provided that you know the estimates of the mean and the standard deviation for a specific class. However, what we actually need for classification, is the posterior probabilities of the classes given the data. To retrieve this, <em>Bayes’ rule</em> can be used:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*fdoyrAqlyK1l6VTqWLI9aw.png" /></figure><p>This equation can further be simplified by factoring out the common prior:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*jj5NLEWYZaQ-PEpow5N4rg.png" /></figure><p>Now the posteriors can be computed with the <em>posteriors function</em>. To simplify the code, I made the vectors M and S, with all means and all standard deviations of each class. With these vectors, a parameter will be sufficient to specify the class, from which the posterior has to be computed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*o-3v1SCkbHxYYZ_qot6_OA.png" /></figure><p>Visualizing the posteriors results in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*KxCH3zqNA2QP6xqoTSiT7w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*GpfsA1UUgoiOSeMDEIa5jQ.png" /></figure><p>All tools necessary to contruct a classifier are now available! The Bayes classifier is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*7Jqj4herM5CvJU4i6EEXYQ.png" /></figure><p>Implementing this in Python, calls for 2 functions, namely <em>classify</em> and <em>validate</em>. The <em>classify</em> <em>function</em> classifies a single data point x as one of the 3 classes by returning a 0, 1 or a 2 depending on which class it belongs to. The <em>validate function</em> taks a validation set with all predicted classes for each data point and returns how many were predicted correctly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*7KBji-fBbkRs_V04OL_q1g.png" /></figure><p>Finally I used these functions to report the percentage of correct predictions for each class and the average of correct percentages, like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*sGDgXX2XZgVR6dy3_dKgtA.png" /></figure><p>Which resulted in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*rADgVQbq1_zjNaPffRtGRA.png" /></figure><p>And there you have it! Mind you, this classifier is constructed using an univariate model, for we only used the petal length. But we can do better, by using more variables and therefore using a multivariate model. In my next article I will be discussing these models.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8747b319be5c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/predicting-the-future-using-machine-learning-part-iv-8747b319be5c">Predicting the future using Machine Learning part IV</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting the future using Machine Learning part III]]></title>
            <link>https://medium.com/analytics-vidhya/predicting-the-future-using-machine-learning-part-iii-410e1a1742c7?source=rss-5edc935bf437------2</link>
            <guid isPermaLink="false">https://medium.com/p/410e1a1742c7</guid>
            <category><![CDATA[predictions]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Mina Suntea]]></dc:creator>
            <pubDate>Fri, 08 Jan 2021 15:51:56 GMT</pubDate>
            <atom:updated>2021-01-08T17:19:10.455Z</atom:updated>
            <content:encoded><![CDATA[<h4>Cross validation + implementation in Pyhton</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UPm8jXrssckMwcfm" /><figcaption>Photo by <a href="https://unsplash.com/@jstrippa?utm_source=medium&amp;utm_medium=referral">James Harrison</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As promised in the previous part of this series I will be discussing a method that can be applied so that a generic model is chosen which is less prone to overfit than the <a href="https://minasuntea.medium.com/predicting-the-future-using-machine-learning-part-ii-fb45806e5b71">polynomial model with order 2</a>. This method is called Cross Validation.</p><h4>Cross Validation</h4><p>The Cross Validation method is a method wherein the data is splitted in a training set and a validation set, given a ratio. So, for example, with a ratio of 0.6, 60% of the data is being used as a training set to train the model and 40% is being used as a validation set to which the model can be fitted. Implementing the Cross Validation method in Python gives:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*t-_O6krz9nOorIT3tS_l3A.png" /><figcaption>Training and validation set for both the X and R parts of the data</figcaption></figure><p>The <em>validation_split</em> function returns the training and validation set for both the X and R part of the dataset. Mind you, we are still going to use the dataset I used in <a href="https://minasuntea.medium.com/predicting-the-future-using-machine-learning-part-i-48da5d48a40f">part I</a> and <a href="https://minasuntea.medium.com/predicting-the-future-using-machine-learning-part-ii-fb45806e5b71">part II</a> of this series, which results in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*nTJZOf12U_L2VhuTy25M3A.png" /><figcaption>Chosen ratio of 0.6, which results in 60% training and 40% validation.</figcaption></figure><p>With this new method to split the data, different order polynomials can now just repeatedly be fitted on the training set while looking at which produces the lowest cost on the validation set. The set of weights that produce the lowest costs on the validation set generalizes the best fit to new data and is therefore the best overal fit on the dataset.</p><p>To find the best fit I wrote a function called <em>best_poly_fit </em>in which I iterate over a large range, like 1 to 50, of polynomial orders. Everytime a D_matrix is computed from the training samples and fitted with the <em>poly_fit</em> function to the corresponding training values, after which the cost of this fit is computed with the function <em>poly_cost</em>. Every loop the cost is compared to the minimal cost and gets replaced and returned along with the corresponding weights, depending on the value of the cost. So my <em>best_poly_fit</em> function looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*FCVrVCX8mqe3T9PDnoVfGg.png" /></figure><p>The only thing left to do now is visualize the best found fit along with the best weights and the minimal cost:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*BqBju6txtxd61p-q6mx8Xw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*q2Z0AluAz1MngxT4FkdLcQ.png" /></figure><p>Compared to the linear fit and the polynomial fit with order 2, this fit is by far the best. The advantage of the Cross Validation method is that the model found after training it with a part of the dataset is less prone to overfit or underfit. With this article I have come to the end of the first main type of supervised learning algorithm, namely regression. In my following article I will cover another main type of supervised learning algorithm, also known as the classification algorithm.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=410e1a1742c7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/predicting-the-future-using-machine-learning-part-iii-410e1a1742c7">Predicting the future using Machine Learning part III</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>