<?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 Ayşe Bat on Medium]]></title>
        <description><![CDATA[Stories by Ayşe Bat on Medium]]></description>
        <link>https://medium.com/@aaysbt?source=rss-c4b9afb95bfa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*B28mr1KdixroADjRO3GqrQ.png</url>
            <title>Stories by Ayşe Bat on Medium</title>
            <link>https://medium.com/@aaysbt?source=rss-c4b9afb95bfa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 14:59:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aaysbt/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[Add Custom Shape and Manage Your Dashboard with Parameter in Tableau 2020]]></title>
            <link>https://medium.com/@aaysbt/add-custom-shape-and-manage-your-dashboard-with-parameter-in-tableau-2020-a4d27eab479?source=rss-c4b9afb95bfa------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4d27eab479</guid>
            <category><![CDATA[tableau]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[makeovermonday2020]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Ayşe Bat]]></dc:creator>
            <pubDate>Fri, 11 Sep 2020 15:15:02 GMT</pubDate>
            <atom:updated>2020-09-11T15:15:02.622Z</atom:updated>
            <content:encoded><![CDATA[<p>In this project, we are going to visualize the <a href="https://data.world/makeovermonday/2020w35-indian-batsmen-v-left-arm-pace">Tableau Makeover Monday Week 35 challenge</a>. In this challenge, we have 5 Indian batsman and their batting averages along with their dismissals since WC 2015. The data looks like the below table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*3gbmVhJ5DcpBBJCJum5xCg.png" /><figcaption>Indian batsman datasets</figcaption></figure><p>What we are going to accomplish is showing at the below gift.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*v8vaYbfzXBo5a7kpFzfE6A.gif" /></figure><ul><li>How the dashboard is going to look and how it is going to function is shown above gift . Firstly, we are going plot dismissals vs averages for each player (batsman). This plot will use as the foundation of the dashboard. We can see where each player stands on the dismissals vs average plot. Let’s call this plot batsman plot.</li><li>In the batsman plot, we are going to replace the shape with corresponding images of players.</li><li>Next, we create two bar plots for both dismissal and averaged plots for each player. We place them on the axes. Our goal here creates an interactive dashboard for this purpose we are going the use batsman as a filter. As you can see, once we select the player (batsman)on the batsman plot, the bar char is changing the corresponding value of its player.</li><li>Last, we are going to create a board stand on the top-right corner and showing the chosen batsman and their corresponding values.</li></ul><h4>1- Batsman Plot</h4><p>Let’s create a dismissal vs average plot for each batsman.</p><ul><li>Add Averages to the Rows</li><li>Add Dismissals to the Columns</li><li>Add Batsman to the Label and then to the Shape</li><li>The shape list will appear on the right side of the screen. Click the arrow shape on the right top corner and then click the edit shape.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CB-HFOyMJO5XL9i3B7ogUg.gif" /><figcaption>Batsman plot</figcaption></figure><ul><li>Before changing the picture you need to add your custom picture in the tableau repository. For this, you need to find My Tableau Repository -&gt; Shape -&gt; MyShape. In this folder, you should add your own custom picture. Note that in this project, we are going to use the player&#39;s picture. please make sure your image file has a transparent background.</li><li>In edit shape, select the MyShape then your picture will be shown then you can select the corresponding picture for your project.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p8In-GpZ9Bosj4RE_FynSg.gif" /><figcaption>Edit custom shape</figcaption></figure><ul><li>We need makeup for our plot for the dashboard. For this, we need to get rid of the axis.</li><li>We also need to the fixed size of the axis. We don’t want to change the size of the axis once we select the players. So we need to set the size of the axis for its maximum value.</li><li>In the edit axis menu, find the in the range and then select the Fixed. For the dismissal select values from 0 to 13 and for the Averages select values 0 to 100 and then remove each axis from the plot.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*stEyWj5UJP9unBT_LkQQyA.gif" /></figure><ul><li>Right Click on the plot and then select the format for changing the view of the plot. Remove the row and columns divider. Change the background color to None for transparent background.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y7rjZEBv8_yR2Stx4qa7HQ.gif" /></figure><p>Let’s create a second plot as a bar plot of Dismissals. Add dismissals to the Columns then add Batsman to the Rows and applied Batsman as a filter to get one bar chart for the player.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WLqB-LfNIuaIk0tO61M82g.gif" /></figure><ul><li>We need to fix the axis, for this go to the Edit axis and select fixed and change values from 0 to 13.</li><li>Then, go to the tick marks in Major Ticks Mark select None.</li><li>In general, don’t forget to delete the name of the axis.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iqKcEjdkx0cmsChYeVNNOw.gif" /></figure><p>Apply the same process for Averages, but this time add Averages to the Rows to get a horizontal bar chart.</p><p>For the board view, we want to get the average value and dismissal value and also the name of the player once we click each player on the dashboard. For this, we need to create a parameter for each of them(Batsman, Averages, Dismissals). Once we created them we are going to define an action for all parameters when we are creating the dashboard.</p><ul><li>Go to the Create Parameter</li><li>Write a name for your parameter (Name: Batsman), Select a parameter type (string in this case) then select a list for making the selection from data columns (select batsman.)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jn9JAItadKX79hiio4UjyA.gif" /></figure><p>Apply the same process for Dismissals and Averages but this time makes sure your data type is correct otherwise, you will not be able to select values from the list.</p><p>Let’s start to create our dashboard.</p><ol><li>Add the text area to the dashboard for the title.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lARAemPyIFAhsNqwxq14yA.gif" /></figure><p>2. I want to add images to the title section. For adding an image to your dashboard grab the image and then drop at the dashboard. Then, you can select your image and resize it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nPisCD2zkZZq1KKmlzMQew.gif" /></figure><p>3. Background image for the dashboard. If you are using background image or color for your background please make sure you are using transparent background for all plot and the images that you adding in your dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WufW27yeJgTleMVdOOoovA.gif" /></figure><p>4. Add the Batsman plot and rearrange the size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DbsiRjrVq6c1mJJggXwuMw.gif" /><figcaption>Batsman plot</figcaption></figure><p>5. Add the Averages bar plot and rearrange the size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jRisoBHJARV-Fd9l6ZCcAw.gif" /></figure><p>6. Add the Dismissals bar plot and rearrange the size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xRtQqs3IuX0yf90FbMaCgA.gif" /></figure><p>7. Add the text area into the dashboard. Then go to the insert and select all parameters one by one and then rearrange the size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JO11SSSXeJa-fyU5K8uPZg.gif" /></figure><p>8. For changing the parameter value once we select the batsman we need to define an action. For creating an action go tot the Dashboard-&gt; Action Click add action and then select change parameter. Add Parameter action windows will open.</p><ul><li>Define a name for your action</li><li>Select an area will action run on it selected area (name of your sheet)</li><li>Choose the target parameter (Parameter that you want to change)</li><li>Choose Filed: choose the corresponding field that your parameter will run on it.</li><li>Complete all this action for three parameters (Batsman, Averages, Dismissals) that we created for our dashboard.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZOeyFdLUkH4v9diQ3KILYg.gif" /><figcaption>Action for BatsmanParameter</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZOeyFdLUkH4v9diQ3KILYg.gif" /><figcaption>Action for Dismissals Parameter</figcaption></figure><p>Find the batsman plot and on the right top corner find the arrow and click on it. Find the Use as Filter and then choose that option. That way we are going to change the bar plot and parameter for a chosen selected batsman.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jDPJ7VOAPQkAnf-R0-oYhw.gif" /></figure><p>You can see the final result as below gift and also in my <a href="https://public.tableau.com/profile/ayse.bat#!/vizhome/INDIANBATSMEN/Dashboard1">Tableau public profile.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*v8vaYbfzXBo5a7kpFzfE6A.gif" /></figure><h4>Conclusion</h4><p>As a final result, we created our dashboard for the Indian Batsman player. As you can see the actual data it, not complicated because the Tableau Makeover Monday challenge is aiming to show you what you can do with Tableau. You could also join these challenges and share your public dashboard or see other. Happy Learning Together…</p><p>Please share any comments and improving on this article. I am a learner of Tableau so I am totally open to any critics.</p><p>You may also follow me on<a href="https://twitter.com/aaysbt"> Twitter</a>, <a href="https://www.linkedin.com/in/aysebat/">Linkedin</a>, and <a href="https://medium.com/@aaysbt">Medium.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4d27eab479" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create Portfolio Website and Host at Github.io]]></title>
            <link>https://medium.com/@aaysbt/create-portfolio-website-and-host-at-github-io-279f46f51f32?source=rss-c4b9afb95bfa------2</link>
            <guid isPermaLink="false">https://medium.com/p/279f46f51f32</guid>
            <category><![CDATA[html]]></category>
            <category><![CDATA[website]]></category>
            <category><![CDATA[portfolio]]></category>
            <category><![CDATA[github-pages]]></category>
            <dc:creator><![CDATA[Ayşe Bat]]></dc:creator>
            <pubDate>Sun, 30 Aug 2020 15:33:19 GMT</pubDate>
            <atom:updated>2020-08-30T15:34:23.168Z</atom:updated>
            <content:encoded><![CDATA[<p>Well, are you ready to create your portfolio website using a free HTML+CSS template and then deploy it at github.io as free?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rg2qMDwVEFUNglwejZOglg.gif" /><figcaption>My portfolio website</figcaption></figure><p>Follow the step that I did to create my<a href="https://aysbt.github.io/aysebat/"> Portfolio Website</a> and then learn how to publish at gihhub.io.</p><ul><li>Download the <a href="http://www.mashup-template.com/">free Html+ Css Template</a></li><li>Organize the Html template</li><li>Deploy in Github</li></ul><p>We are going to use a free template, so you just need to organize the Html, and if you want you may also change CSS style. The basic Html will be enough to make your own portfolio.</p><h4>Download the Template</h4><ul><li>Download the template you desire to use for your portfolio. I choose to use the <a href="http://www.mashup-template.com/preview.html?template=univers">universe</a> as my template.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B3b2Mg0_YVHG2e9yHL-w7Q.png" /><figcaption>Univers template tree view</figcaption></figure><h4>Modify the Template</h4><p>Tips for modifying the template.</p><ul><li>Remove the following object in each Html component.</li></ul><pre><em> &lt;li&gt;&lt;a href=”./components.html” title=””&gt;05 : Components&lt;/a&gt;&lt;/li&gt;</em></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*wA6eBehOK4tiDFBB33s2xw.png" /><figcaption>Remove the components.html</figcaption></figure><ul><li>In<strong> index.html</strong>, modify the span object with your name and job title in the body content.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*PrF3wI9DatjfMbTilG91iQ.png" /></figure><ul><li>In the <strong>index.html</strong> file, you may also change the background images. Find out the following object and replace it with your own image.</li></ul><pre><em> &lt;div class=”hero-full-container background-image-container white-text-container” style=”background-image: url(https://medium.com/%E2%80%98./assets/images/%3C/em%3E%3Cstrong%3E%3Cem%3Espace.jpg%3C/em%3E%3C/strong%3E%3Cem%3E%E2%80%99)”&gt;</em></pre><ul><li>In the <strong>about.html</strong> file, change the content and also don’t forget to change your images file.</li><li>The <strong>works.html</strong> file is a container for all projects that you want to present. In this file, the project could be displayed with heather and summary of the project and you also give a link to your project either you created as Html file in your website or you could direct to a link that goes to the project itself(Github, Medium, Kaggle, etc.).</li><li>In the works.html file modify the content and explain what kind of project you have.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*m8OmwdvR5RKUa88TCykkoQ.png" /><figcaption>works.html file modification</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qBqQBqwKIWMrANWKm9Mw1Q.png" /><figcaption>works.html file</figcaption></figure><p>The order is shown at the above picture, add your own project and modify images and text as you want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9O__QwqSuqwSyCqJeLHKLA.gif" /><figcaption>How the works.html file looks like</figcaption></figure><p>Your project will be represented as the above gift. In my portfolio, I want to display my project on one page as 3 containers in each row and I don’t want to transition as you see in this template. For this, you need to just copy the first-row container and created the second row. Make sure you close the all div element and also remove the following elements at the end of the body element.</p><pre><em> &lt;a class=”left carousel-control” href=”#myCarousel” data-slide=”prev”&gt;‹&lt;/a&gt;</em></pre><pre><em>&lt;a class=”right carousel-control” href=”#myCarousel” data-slide=”next”&gt;›&lt;/a&gt;</em></pre><p>You may found my portfolio page layout in the <a href="https://github.com/aysbt/aysebat/blob/master/works.html"><em>link.</em></a></p><h4>Deploying the project to the GitHub.io</h4><ul><li>Create a repository in your<a href="https://github.com/"> Github account</a>. Your portfolio website is going to use that repository. When you finish your website link is going to display as follows. :</li></ul><pre><a href="https://aysbt.github.io/aysebat/"> https://yourgithubname.github.io/yourrepositoryname/</a></pre><ul><li>In your GitHub, go to the repository and then click to the New button to create a new repository.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*xFUsp25B9G-aCiNXBMGfnQ.png" /><figcaption>Create a New Repository</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*TyjpUUGzrwwTWl1b80nOfQ.png" /><figcaption>Create a New Repository</figcaption></figure><p>How is your repository look like when you finish creating it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*VhDQU6OxymUQHnx6Xy-WiA.png" /></figure><ul><li>Use git clone to clone your repository to your computer:</li></ul><pre><em>git clone </em><a href="https://github.com/aysbt/MyWebsite.git"><em>https://github.com/aysbt/MyWebsite.git</em></a></pre><ul><li>Copy all Html and CSS files inside that repository. Add all files to the GitHub and then commit it.</li></ul><pre><em>--&gt; cd univers</em></pre><pre><em>--&gt; cp -rf about.html assets components.html contact.html index.html main.3f6952e4.css main.3f6952e4.css.gz main.70a66962.js main.70a66962.js.gz main.70a66962.map sample work.html works.html ../MyWebsite<br></em>--&gt; cd ../MyWebsite<br>--&gt; git add .     # <em>adding everthing in your file<br>--&gt; </em>git commit -m &quot;Porfolio files&quot;<br>--&gt; git push origin master</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*ZhYoqwV56cjl0QG-0TiNKQ.png" /><figcaption>How is your repository looks like after commit….</figcaption></figure><p>Our project inside a GitHub right now. But we should change the setting our repository actually put our website on the web. Let’s do that. Click the Settings and then find the <strong>GitHub Pages</strong> section. Click the “Select branch” and then choose the master and save changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*6Ujnnc4g5ZdtcWoah-HcVg.png" /></figure><p>You will get the following images in your GitHub and you should get the following message: Your site is ready to be published at <a href="https://aysbt.github.io/MyWebsite/">https://aysbt.github.io/MyWebsite/</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*ioWMBgaTVzn5tt_zJ696zw.png" /></figure><p>Congratulations you have a portfolio website right now. Please thumps up if you like to read it or learned anything useful. Follow me on<a href="https://twitter.com/aaysbt"> Twitter</a>, <a href="https://www.linkedin.com/in/aysebat/">Linkedin</a>, and <a href="https://medium.com/@aaysbt">Medium.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=279f46f51f32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sankey Diagram in Tableau2020.2]]></title>
            <link>https://medium.com/@aaysbt/sankey-diagram-in-tableau2020-2-c4be53ae4d5?source=rss-c4b9afb95bfa------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4be53ae4d5</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[tableau]]></category>
            <category><![CDATA[sankey-diagram]]></category>
            <category><![CDATA[interactive]]></category>
            <dc:creator><![CDATA[Ayşe Bat]]></dc:creator>
            <pubDate>Sun, 23 Aug 2020 06:55:53 GMT</pubDate>
            <atom:updated>2020-08-23T07:02:11.254Z</atom:updated>
            <content:encoded><![CDATA[<p>Tableau Makeover Monday gives a weekly challenge to improve our Tableau data Visualizing and Analyzing. In the week 33 challenge, I have learned how to make a Sankey diagram and add a parameter to my vision to create a more interactive dashboard. <a href="https://public.tableau.com/profile/ayse.bat#!/vizhome/Scotlandweeklychallenge/Dashboard1?publish=yes">Project link.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KbDTRZDA0AICz4Sj_HBbEA.gif" /><figcaption>Final of Dashboard</figcaption></figure><p>The above gift shows how our dashboard looks like. In the Sankey diagram, we show the distribution of companies over the region, and the size indicates how many companies did they have. When the region selected on the map Region name, the number of companies and percent of the total is chances with corresponding region name.</p><p>The <a href="https://data.world/makeovermonday/2020w33-scotland-the-state-of-the-digital">original dataset</a> for this data visualization looks like below and found in <a href="https://data.world/makeovermonday/2020w33-scotland-the-state-of-the-digital">data.world</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*7ke-Ir8oEla0m5RGZwG1gw.png" /><figcaption>The picture of Dataset</figcaption></figure><p>As you can see, we don’t have so much information. But the goal is here to learn a new thing in Tableau without making things complicated. Actually, when I see this data I want to create a Sankey diagram but Tableau doesn&#39;t have such a diagram as default. So, I search the internet and then found a <a href="http://vizdiff.blogspot.com/2018/12/creating-sankey-chart-as-easy-as-1-2-3.html">useful resource. </a>However, this article is published in 2019 so loading data and make a union is easier at Tableau 2020 version but the calculation is the same as in t<a href="https://www.youtube.com/watch?v=1HwCzlA9hI4">his article</a>. We are going to follow step by step and then create our Sankey diagram.</p><p>In the Sankey diagram, we need a place that holds the source data and another corresponding place for our target data. For this, we need to duplicate our data set then we could use one piece as the source and another as the target. Actually, before that in our data set, we don’t have any columns that show the source data. First of all, we need to create a column that indicated all-region.</p><ul><li>Right-click one of the columns in the data source and then got to the Create Calculated Field.</li><li>In the calculated field, crate a string called “All-Region” and give a proper name of the column.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*nv1aIcrpD0K5gVnt4edk4Q.gif" /></figure><ul><li>The next step is to union your data table with itself.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*nKl0rW8aRDk6Qg9Fr06vRg.gif" /></figure><p>We need to create two horizontal boundaries to show where our Sankey diagram starts and where it ends. For this, we are going to create the “ToPad” area using Calculated Field with the formula: <strong><em>IF [Table Name] = “Sheet1” THEN 1 ELSE 49 END. </em></strong>The name of “Sheet1” comes when we union our data. Using this parameter we are both separating the source from the target and we place them in different places on the Sheet. The number 49 was chosen for the curve has enough marks to be drawn smoothly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z4UoN18uSURSW41v40HDUA.gif" /><figcaption>Creating ToPad Fields</figcaption></figure><p>Right now we only have a value of 1 and a value of 49. Instead of having two values, we are going to create a bin from ToPad to have all values between 1 to 49.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bRyz_52E_mtocDl84revZg.gif" /><figcaption>Create Padding from ToPAd Filed</figcaption></figure><p>Next, we are going to create calculated fields “t”. We are going to use the t in our sigmoid function calculation. Yeap, that is true we are going to create a sigmoid function to create the curve that we desire. t is equal to <em>(INDEX()-25)/4 </em>which is create evenly space for our marks across the view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DDXUxJYXhT-tE5bftmZ97Q.gif" /></figure><blockquote>So, we are going to create a sigmoid function. A <strong>sigmoid function</strong> is a mathematical function having a characteristic “S”-shaped curve or <strong>sigmoid curve. — </strong><a href="https://en.wikipedia.org/wiki/Sigmoid_function"><strong>Wikipedia</strong></a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/165/1*zDUs6VMAopVTP_WN0XS8oQ.gif" /><figcaption>Sigmoid Function Formula</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OFIbFkuW-TcDavUiwQpfZg.gif" /><figcaption>Sigmoid function</figcaption></figure><p>We need one more calculation to build out full curve. So we have Rank1 which is our starting point on the left side for the source. Then we have Rank2 minus Rank1 that jumps it on the target side and then multiplying with the sigmoid function gives us curve that we want in our Sankey diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fkvDkjRVidY_JuI5tRfwsg.gif" /><figcaption>The Curve Field</figcaption></figure><p>So that is a lot of calculation but we can build out our Sankey diagram using these calculations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KQsskGYHhBI030sXae8T-A.gif" /><figcaption>Making the Sankey Diagram</figcaption></figure><p>End of this, we have two values one is on the left side (source)and the other is the right side(target), and the curve doesn&#39;t understand the calculation yet. For this, we are going to use a nested table calculation. At this point, we need to reach our source(<em>in our case: All Region</em>) and target(<em>in our case: Region</em>). Add these two in the Detail fields so we can use them in nested calculations.</p><p>For Rank1, we need to add source, target, and padded so we can tell them to go from source to target using padded. We will do the same thing for Rank2 and then for t which we are going to make sure that t is using the padded. You should follow the below gif for these calculations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*phO_kzLYrDXnQRO2F0odFw.gif" /></figure><p>So, we need a little cosmetics in our diagram. Do the following step for this.</p><ul><li>Get rid fo the row and column grid and zero lines in Format section (Right Click -&gt;Format)</li><li>Edit x-axis: fixed the axis start from -5 to 5.</li><li>Get rid of the axis labels on the diagram.</li></ul><p>You will get the following images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*xbNo1NsFoaMPhTNNP_I3Pw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PzZaPD334qUsXQvNrqszmA.gif" /></figure><p>So we need a size for our lines. We are going to size them with the number of companies. We need to create another calculated field to obtain the size of the company. The Formula: <em>WINDOWS_AVG(SUM(Companies)). </em>Create the calculated field and then add in the size make sure you also set the calculation using padded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XIGK8NFouio22GYxFeVVuA.gif" /><figcaption>Color the Sankey Diagram</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w2f_nMmQNjiDLPm5byQKag.gif" /><figcaption>Create the bar char for regions</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5DBnej6e_EzRy-mKXMDCnA.gif" /><figcaption>Set the map coloring</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Z8dyjVDpNr54XY9gqV13gQ.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KbDTRZDA0AICz4Sj_HBbEA.gif" /><figcaption>Final of Dashboard</figcaption></figure><h3>Conclusion</h3><p>We have completed our Sankey diagram, bar chart indicates the number of companies for each region, and the map shows the geographic location of the region. When we select a region on the map it is going to highlight selected region on bar chart and Sankey diagram.</p><p>For the record, I am the learner of Tableau so I open to any comment. Let me know if you have any suggestions. Follow me on<a href="https://twitter.com/aaysbt"> Twitter</a>, <a href="https://www.linkedin.com/in/aysebat/">Linkedin</a>, and in <a href="https://medium.com/@aaysbt">Medium.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4be53ae4d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Marketing Customer Segmentation using KMeans Algorithm and Dimensionality Reduction using…]]></title>
            <link>https://medium.com/@aaysbt/marketing-customer-segmentation-using-kmeans-algorithm-and-dimensionality-reduction-using-7d88b591edcd?source=rss-c4b9afb95bfa------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d88b591edcd</guid>
            <category><![CDATA[segmentation]]></category>
            <category><![CDATA[autoencoder]]></category>
            <category><![CDATA[k-means-clustering]]></category>
            <category><![CDATA[datasciencecourse]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Ayşe Bat]]></dc:creator>
            <pubDate>Fri, 24 Jul 2020 13:17:31 GMT</pubDate>
            <atom:updated>2020-07-24T13:17:31.245Z</atom:updated>
            <content:encoded><![CDATA[<h3>Marketing Customer Segmentation using KMeans Algorithm and Dimensionality Reduction using Autoencoders</h3><p>Marketing is vital for the growth and sustainability of any business. The company’s brand is engaged customers grow revenue and increase sales which Marketers can help with that purpose if they have the necessary information. Marketers should know their customers and identify their needs. By understanding the customer marketers can launch a targeted ad marketing campaign. For this marking purpose, we could segment the market into groups of customers that they have common features.</p><p>We want to perform customer market segmentation analysis using the KMeans algorithm. In our dataset, we know the spending habits of customers which is going to help us segment the customers. Basically, we use customer data to organize for marketers to launch a targeted marketing campaign.</p><p>What we go thought with this project.</p><ul><li>Exploratory data analysis and visualize customers&#39; data set.</li><li>Learn how to fill out missing data points or null elements.</li><li>Understand the theory and intuition behind KMeans clustering algorithms.</li><li>Learn how to find the optimal number of clusters using the Elbow Method.</li><li>Apply K-means algorithms and cycle learn to perform market segmentation to understand the theory and the intuition behind autoencoders.</li><li>Learn how autoencoders could perform dimensionality reduction build and train autoencoder models.</li><li>Understand the intuition behind principle component analysis (PCA) and perform dimensionality reduction using a real-world data set.</li></ul><h4>Loading the <a href="https://github.com/aysbt/DataScienceProject">Data</a> and Exploratory Data Analysis (EDA)</h4><p>You found data in the <a href="https://github.com/aysbt/DataScienceProject">link.</a> Customer data contain the Customer’s spending habits. We are going the investigate and explore the for analysis purpose.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ad7958b2363a7856efdb439fc1c56ad/href">https://medium.com/media/3ad7958b2363a7856efdb439fc1c56ad/href</a></iframe><pre>class &#39;pandas.core.frame.DataFrame&#39;&gt; <br>RangeIndex: 8950 entries, 0 to 8949 <br>Data columns (total 18 columns):  <br>#   Column                            Non-Null Count  Dtype   <br>---  ------                            --------------  -----    <br>0   CUST_ID                           8950 non-null   object   <br>1   BALANCE                           8950 non-null   float64  <br>2   BALANCE_FREQUENCY                 8950 non-null   float64  <br>3   PURCHASES                         8950 non-null   float64  <br>4   ONEOFF_PURCHASES                  8950 non-null   float64  <br>5   INSTALLMENTS_PURCHASES            8950 non-null   float64  <br>6   CASH_ADVANCE                      8950 non-null   float64  <br>7   PURCHASES_FREQUENCY               8950 non-null   float64  <br>8   ONEOFF_PURCHASES_FREQUENCY        8950 non-null   float64  <br>9   PURCHASES_INSTALLMENTS_FREQUENCY  8950 non-null   float64  <br>10  CASH_ADVANCE_FREQUENCY            8950 non-null   float64  <br>11  CASH_ADVANCE_TRX                  8950 non-null   int64    <br>12  PURCHASES_TRX                     8950 non-null   int64    <br>13  CREDIT_LIMIT                      8949 non-null   float64  <br>14  PAYMENTS                          8950 non-null   float64  <br>15  MINIMUM_PAYMENTS                  8637 non-null   float64  <br>16  PRC_FULL_PAYMENT                  8950 non-null   float64  <br>17  TENURE                            8950 non-null   int64   dtypes: float64(14), int64(3), object(1) memory usage: 1.2+ MB</pre><p>In this marketing customer data, we have 18 features that each of them explained in the below. We have a total of 8950 rows but 2 features have missing information, we are going to investigate this later.</p><ul><li><strong>CUSTID:</strong> Identification of credit cardholder</li><li><strong>BALANCE:</strong> Balance amount left in customer’s account to make purchases</li><li><strong>BALANCE_FREQUENCY:</strong> How frequently the Balance is updated, score between 0 and 1 (1 = frequently updated, 0 = not frequently updated)</li><li><strong>PURCHASES:</strong> Amount of purchases made from the account</li><li><strong>ONEOFFPURCHASES:</strong> Maximum purchase amount did in one-go</li><li><strong>INSTALLMENTS_PURCHASES:</strong> Amount of purchase done in installment</li><li><strong>CASH_ADVANCE:</strong> Cash in advance given by the user</li><li><strong>PURCHASES_FREQUENCY:</strong> How frequently the Purchases are being made score between 0 and 1 (1 = frequently purchased, 0 = not frequently purchased)</li><li><strong>ONEOFF_PURCHASES_FREQUENCY:</strong> How frequently Purchases are happening in one-go (1 = frequently purchased, 0 = not frequently purchased)</li><li><strong>PURCHASES_INSTALLMENTS_FREQUENCY:</strong> How frequently purchases in installments are being done (1 = frequently done, 0 = not frequently done)</li><li><strong>CASH_ADVANCE_FREQUENCY:</strong> How frequently the cash in advance being paid</li><li><strong>CASH_ADVANCE_TRX:</strong> Number of Transactions made with “Cash in Advance”</li><li><strong>PURCHASES_TRX:</strong> Number of purchase transactions made</li><li><strong>CREDIT_LIMIT:</strong> Limit of Credit Card for user</li><li><strong>PAYMENTS:</strong> Amount of payment done by the user</li><li><strong>MINIMUM_PAYMENTS:</strong> Minimum amount of payments made by the user</li><li><strong>PRC_FULL_PAYMENT: </strong>Percent of full payment paid by the user</li><li><strong>TENURE: </strong>Tenure of credit card service for user</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*k5c64UyBkjkGYR0aHOcShw.png" /><figcaption>Missing data for each feature</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*M9pdu4znHa2eWeBKJZvfBQ.png" /><figcaption>Total Missing Data for each column</figcaption></figure><p>We have 313 missing value for<em> MINIMUM_PAYMNETS </em>and 1 missing value for <em>CREDIT_LIMIT</em>. We are going to fill out the missing values with means of each feature.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/51cc54c4a29e02b60f0faafde199f1f7/href">https://medium.com/media/51cc54c4a29e02b60f0faafde199f1f7/href</a></iframe><ul><li>We plot the seaborn distplot which combines the matplotlib.hist function with seaborn kdeplot().</li><li>Kernel Density Estimate (KDE) is used for visualizing the Probability Density at different values of a continuous variable.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*AZbFCOHtTyd8B8vEE-yOyA.png" /></figure><p><strong><em>INTERPRETATION OF DISTPLOT</em></strong></p><ul><li>Mean of <em>balance</em> is $1500</li><li><em>Balance_Frequency</em> for most customers is updated frequently ~1</li><li>For <em>‘PURCHASES_FREQUENCY’</em>, there are two distinct groups of customers</li><li>For ‘<em>ONEOFF_PURCHASES_FREQUENCY</em>’ and ’PURCHASES_INSTALLMENT_FREQUENCY’ * most users don’t do one-off purchases or installment purchases frequently</li><li>A very small number of customers pay their balance in full <em>‘PRC_FULL_PAYMENT’</em> 0</li><li>Credit limit average is around $4500</li><li>Most customers are ~11 years tenure</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3efddcf86b340acebbc64f9da6161a43/href">https://medium.com/media/3efddcf86b340acebbc64f9da6161a43/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4eBN84Dk8G0CHxLaTZJZFA.png" /><figcaption>Correlation for each feature of the dataset.</figcaption></figure><p><em>INTERPRETATION OF CORRELATION PLO</em>T</p><ul><li>‘<em>PURCHASES</em>’ have a high correlation between ‘<em>one-off purchases’, ‘installment purchases, ‘purchase transactions’, ‘credit limit’,</em> and <em>‘payments</em>’.</li><li>There is a strong positive correlation between ‘<em>PURCHASES_FREQUENCY</em>’ and ‘<em>PURCHASES_INSTALLMENT_FREQUENCY</em>’</li><li>‘<em>CASH_ADVANCE_TRX</em>’ correlated with ‘<em>CASH_ADVANCE_FREQUENCY</em>’ and ‘<em>CASH_ADVANCE’</em></li></ul><p><strong>K-MEANS CLUSTERING ALGORITHM</strong></p><p>K-means is an unsupervised learning algorithm (clustering) that works by grouping data points together (clustering) in an unsupervised fashion. The algorithm groups observations with similar attribute values together by measuring the Euclidian distance between points.</p><p><em>K-Means algorithm step</em></p><p>1- Choose the number of clusters <em>“K”: We are going to find the optimum number of cluster for this model using the elbow method.</em></p><p>2- Select random <em>“K” </em>points that are going to be the centroids for each cluster.</p><p>3- Assign each data point to the nearest centroid, doing so will enable us to create a <em>“K”</em> number of clusters.</p><p>4- Calculate a new centroid for each cluster.</p><p>5- Reassign each data point to the new closest centroid.</p><p>6- Go to step 4 and repeat.</p><p><strong>HOW TO SELECT THE OPTIMAL NUMBER OF CLUSTERS (K)? “ELBOW METHOD”</strong></p><p>K-Elbow visualizer implements the “elbow” method of selecting the optimal number of clusters for K-means clustering.</p><p>We are going to plot the <em>number of clusters on the x-axis</em> and the <em>sum of the variation from centroid for each cluster on the y-axis</em>. When <em>“K” </em>increases, the centroids are closer to the centroids of the clusters. The improvements will decline, at some point rapidly, creating the elbow shape. When you see the variations here it becomes a little bit straight line or the variations are not changing dramatically. That’s where you select the optimal values of <em>“K” </em>and that will be the optimal value.</p><h4>AUTOENCODERS FOR DIMENSIONALITY REDUCTION</h4><p>Autoencoders are a type of unsupervised neural network algorithm (no class labels or labeled data). We used the autoencoder as a dimensionality reduction that will help to choose the important parts of the data.</p><p>Autoencoder having two-component know as encoder and decoder.<strong> Encoder (E), </strong>accept the input data(x), and squeeze into the latent-space (s) also called Bottleneck. Formulated as <em>s=E(x). </em>The encoder is very similar to the feed-forward network. The network here has an assignment on how data is structured not the predicting values or labels. <strong>Decoder (D)</strong>, accept the latent-space representation as input and then reconstructing the original input as output(o). Formulated as o = D(s). The decoder is similar to the feed-forward network. Instead of reducing data to the lower dimension, It reconstructs the data from its lower dimension representation to the original dimensional.</p><p>The entire training process of the encoder formed as <em>o= D(E(x))</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Im7CxJBpVvDqUNWuUVfr9w.png" /><figcaption>Image representation of autoencoder</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2be7e47dbc78f9025b255cd9f44aa7bf/href">https://medium.com/media/2be7e47dbc78f9025b255cd9f44aa7bf/href</a></iframe><pre>Model: &quot;model_12&quot; _________________________________________________________________ Layer (type)                 Output Shape              Param #    ================================================================= input_11 (InputLayer)        [(None, 17)]              0          _________________________________________________________________ dense_77 (Dense)             (None, 7)                 126        _________________________________________________________________ dense_78 (Dense)             (None, 500)               4000       _________________________________________________________________ dense_79 (Dense)             (None, 500)               250500     _________________________________________________________________ dense_80 (Dense)             (None, 2000)              1002000    _________________________________________________________________ dense_81 (Dense)             (None, 10)                20010      _________________________________________________________________ dense_82 (Dense)             (None, 2000)              22000      _________________________________________________________________ dense_83 (Dense)             (None, 500)               1000500    _________________________________________________________________ dense_84 (Dense)             (None, 17)                8517       ================================================================= Total params: 2,307,653 <br>Trainable params: 2,307,653 <br>Non-trainable params: 0</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a0fd5c93d83d7f3e19baa3bca5e3b30/href">https://medium.com/media/0a0fd5c93d83d7f3e19baa3bca5e3b30/href</a></iframe><p>Let’s start with scaling our data that arranges the data in a <strong>standard</strong> normal distribution. Standardizing a dataset involves rescaling the distribution of values so that the <em>mean of observed values is 0</em> and the <em>standard deviation is 1</em>. This can be thought of as subtracting the mean value or centering the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*Ju7ZMoo0oPZdZlFJXoFLYQ.png" /></figure><p>You can see on the plot that the variations are not changing dramatically starting from when the number of Cluster reaches the<em> 5</em>. That’s where we select the optimal values of <em>“K” </em>and the optimal value is 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LH9c654uF-eezuytAUTewA.png" /><figcaption>The Balance Distribution for each Cluster</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tHLXNkuFUXgypqNEDSgQyg.png" /><figcaption>The Balance Frequency Distribution for each Cluster</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KT0AeubQRajERnrro6N66w.png" /><figcaption>The Purchase distribution for each Cluster</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wsxpio1h6ajTIMj5dZvtYg.png" /><figcaption>the One-Off Payment Distribution for each Cluster</figcaption></figure><p>You found all the features plot for each cluster you may visit the project in my <a href="https://github.com/aysbt/DataScienceProject/blob/master/Marketing_Departman_Customer_Segmentation.ipynb">Github account</a>.</p><h3>Principal Component Analysis (PCA)</h3><ul><li>PCA is an Unsupervised Learning Algorithm</li><li>PCA works find trying to find a new set of features called components which are composites of the uncorrelated given input features.</li><li>PCA performs dimensionality reduction while attempting to keep the original information unchanged.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52be5f2a6189b4dfbb0523a7986b39e9/href">https://medium.com/media/52be5f2a6189b4dfbb0523a7986b39e9/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*UEVcOyPXKqyooBsVw1gh4w.png" /></figure><h4>CONCLUSION</h4><p>We have been completed the investigating Marketing Customer data and segment the data based on customer’s spending habits. First, we start with the Exploratory Data Analysis (EDA) and visualize the customers’ data set an then fill out missing data points or null elements. As a purpose of our project, we discourse the KMeans clustering algorithms and learn how to find the optimal number of clusters using the Elbow Method. We created autoencoders to perform dimensionality reduction build and train autoencoder models. As a Final result, we plot the segment the customer for Marketing purposes.</p><p>You may find this study in my <a href="https://github.com/aysbt/DataScienceProject/blob/master/Marketing_Departman_Customer_Segmentation.ipynb"><em>githup account</em></a> as part of<a href="https://www.udemy.com/course/data-science-for-business-6-real-world-case-studies/"> <em>the Data Science for Business Course at Udemy.</em></a></p><p>I have written this article to improve my data science and machine learning skills so I am still a learner. Please let me know any additional information or comment on this article.</p><p>Follow me on<a href="https://twitter.com/aaysbt"> Twitter</a>, <a href="https://www.linkedin.com/in/aysebat/">Linkedin</a>, or in <a href="https://medium.com/@aaysbt">Medium.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d88b591edcd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Employee Churn Analysis]]></title>
            <link>https://medium.com/@aaysbt/employee-churn-analysis-be94751e4df5?source=rss-c4b9afb95bfa------2</link>
            <guid isPermaLink="false">https://medium.com/p/be94751e4df5</guid>
            <category><![CDATA[churn-prediction]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Ayşe Bat]]></dc:creator>
            <pubDate>Tue, 14 Jul 2020 15:34:09 GMT</pubDate>
            <atom:updated>2020-07-14T15:34:09.492Z</atom:updated>
            <content:encoded><![CDATA[<p>Employee churn analysis aims to predict who will leave the company. In this analysis, we are going to use the fictional data called HR Analytics Employee Attrition &amp; Performance created by IBM data scientists. You Found the original <a href="https://www.kaggle.com/pavansubhasht/ibm-hr-analytics-attrition-dataset">dataset at Kaggle.</a> Employee churn analysis is similar to the customer churn analysis but mainly focuses on the employee rather than the customer. The data contains information about the employee demographic and specific information like distance from home, job role, job satisfaction, monthly rate, working with current manager, working years at the company, the last promotion time, and so on. In this project, we are going to investigate and make exploratory data analyses using the HR dataset, and then we are going to prepare the data for the machine learning algorithm. You found all analyses in my <a href="http://Human Resource Quit Prediction _ Kaggle.html">Kaggle Notebooks</a> and also in my <a href="https://github.com/aysbt/DataScienceCourse/blob/master/human-resource-quit-prediction.ipynb">GitHub repositories.</a></p><h4>IMPORTING LIBRARIES AND INVESTIGATING THE DATA</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8MSDhufz4EOZ9Iy0Uo3lNQ.png" /><figcaption>Dataset overview</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*nbVVCUt4UGSU7URdEaQJ7Q.png" /><figcaption>Dataset information for each column</figcaption></figure><p>We have a total of 1470 employees information with 35 features which shows the information corresponding to each employee. The Attrition column indicates the employee status showing that the employee stayed at the company or leave the company. In this column, 0 indicates that the employee still working at the company, and 1 indicates that the employee leaves the company. Based on this data we are going look for the pattern that if the same profile of people leaving the company and finally we are going to predict who will leave the company using the ML algorithm.</p><blockquote><strong>Age:</strong> Age of the Employee<br><strong>Attrition</strong> : Employee who stayed: 0 , Employee who leave: 1<br><strong>BusinessTravel:</strong> ‘Travel_Rarely’ ‘Travel_Frequently’ ‘Non-Travel&#39;<br><strong>DailyRate :</strong> Daily Rate of Employee<br><strong>Department</strong> <strong>: </strong>’Sales’ ‘Research &amp; Development’ ‘Human Resources’<br><strong>DistanceFromHome</strong> : Distance from home from work for each Employee<br><strong>Education:</strong> 1:Below College, 2 :College, 3:Bachelor, 4 ;Master, 5:Doctor<br><strong>EducationField :</strong>Life Sciences’ ‘Other’ ‘Medical’ ‘Marketing’ ‘Technical Degree’<br> ‘Human Resources’ <br><strong>EnvironmentSatisfaction</strong> : 1: Low, 2 :Medium, 3 :High, 4 :Very High<br><strong>Gender</strong> : Female or Male <br><strong>HourlyRate</strong> : Hourly Rate of Employee <br><strong>JobInvolvement: </strong>1: Low, 2 :Medium, 3 :High, 4 :Very High<strong> </strong><br><strong>JobLevel </strong><br><strong>JobRole :</strong> ‘Sales Executive’ ‘Research Scientist’ ‘Laboratory Technician’<br> ‘Manufacturing Director’ ‘Healthcare Representative’ ‘Manager’<br> ‘Sales Representative’ ‘Research Director’ ‘Human Resources’<br><strong>JobSatisfaction : </strong>1: Low, 2 :Medium, 3 :High, 4 :Very High<br><strong>MaritalStatus : </strong>‘Single’ ‘Married’ ‘Divorced’<br><strong>MonthlyIncome</strong> : Montly income of Employe between 2094 and 26999.<br><strong>MonthlyRate</strong> <br><strong>NumCompaniesWorked</strong> : Number of Companies for the employee work before the current one. <br><strong>Over18 :</strong>’Y’<br><strong>OverTime : </strong>v<br><strong>PercentSalaryHik</strong>e : Percentage of Salary increase between %11-%25.<br><strong>PerformanceRating</strong> : 1 :Low, 2 :Good, 3 :Excellent, 4 :Outstanding<br><strong>RelationshipSatisfaction</strong> 1: Low, 2 :Medium, 3 :High, 4 :Very High<br><strong>StandardHours</strong> : standard work hour for each employee: 80 Hours<br><strong>StockOptionLevel</strong> : It categorized from 0 to 3 indicate the stock level of employee<br><strong>TotalWorkingYears : </strong>Employee`s total working years and it varies between 0 to 40 years. <br><strong>TrainingTimesLastYear</strong> : Employee`s training time in the last year.<br><strong>WorkLifeBalance</strong> 1 :Bad, 2 :Good, 3 :Better, 4 :Best<br><strong>YearsAtCompany</strong> : Employess`s total working year at the company adn it varies between 0 to 40 years. <br><strong>YearsInCurrentRole</strong> : Employee`s current position at the company and it varies between 0 to 18 years. <br><strong>YearsSinceLastPromotion:</strong> The time the employee get the last promation and it varies between 0 to 15 years.<br><strong>YearsWithCurrManager: </strong>The time for time employee working with current manager and it varies between 0 to 17 years.</blockquote><ul><li>“<em>Attrition</em>” columns indicate “Yes” if the employee quit the job and “No” employee stayed at the company. We should convert this 1 and 0 for use in the machine learning model.</li><li>“<em>Overtime</em>” also has “Yes” and “No”. So we need to convert this column to 1 and 0.</li><li>“<em>Over18</em>” column has only Y[Yes] meaning every employee over18 so we don’t need this information.</li><li>“<em>StandardHour</em>” has only a unique value 80. So we don’t need this column.</li><li>The same strategy also applies to the ‘<em>EmployeeCount</em>’, ’<em>EmployeeNumber</em>’ column.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*YJZpL0pcuPwp2cvrR2v6YQ.png" /><figcaption>Data cleaning for HR dataset</figcaption></figure><p>Distribution plots help us understand the data better, with this visualization we are able to see how our data is distributed and if there are any outliers in the data sets. For this purpose, we are going to use the histogram for every numerical feature in the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XQUK2LWEg8Jol52tSQCoOA.jpeg" /></figure><p>In this project, we are going to use the seaborn for insulation but as an example of Plotly, I am going to plot the attrition count and pie chart for the percentage of attrition using Plotly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*laraSxcpZuqYHGic_6niig.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B6jiKVSJ_Y3aIgossttDaA.png" /><figcaption>Count and Distribution of Attrition</figcaption></figure><p>We are going to write a function to investigate the categorical and numerical columns separately and plot them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*w_I9OE0VyywHpa2mK001Nw.png" /><figcaption>This function shows three plots in one row for investigation categorical variables and effection of attrition on them.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ct8YsFF_w71MpeJbhnjgOw.png" /><figcaption>This function plots the 2 given categorical columns with distribution fo numerical column.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*Nk8MDmXuMpyRHB-PFH3IwQ.png" /><figcaption>This function shows the two plots for investigation numerical value. One of them shows KDE plots for the distribution of variables and the others show the boxplot for statistical investigation.</figcaption></figure><p>As an example of this function, I am going to show a few of the plots here but If you want to see all of the EDA analysis you may visit my <a href="https://www.kaggle.com/aaysbt/human-resource-quit-prediction">Kaggle</a> or <a href="https://github.com/aysbt/DataScienceCourse/blob/master/human-resource-quit-prediction.ipynb">GitHub</a> for all projects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fh6VWkc9giwgifputPo8Dw.png" /><figcaption>Employee Status by Gender</figcaption></figure><figure><img alt="Employee Status by Educational Filed" src="https://cdn-images-1.medium.com/max/1024/1*jWP1jAbLbbG3_p41DBNqRA.png" /><figcaption>Employee Status by Educational Field.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3p-uirRr5sUbwFO7UJXw5A.png" /><figcaption>Employee Status by Marital Status</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hj0p9739mlvgq78hue11wg.png" /><figcaption>Employee Status by Job Role</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TxQv6cYlVQdI-me40hDWuw.png" /><figcaption>Comparison of Gender and Marital Status by Age</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hYpCFiNDnrADZaupL9aFdA.png" /><figcaption>Age Status for the Company</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zvpbk_x1QuuK8bLkcH_aMw.png" /><figcaption>Distribution of Distance from Home</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ltw5EJQrxt8aW1fp6vN70Q.png" /><figcaption>Distribution of Monly Income</figcaption></figure><p>We also look at the numerical columns correlation with each other for this we are going to use the heat map for after applying core() function.</p><pre>correlations = employee_df.coor()<br>fig, ax = plt.subplots(figsize=(20,20))<br>sns.heatmap(correlations, annot=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*R3vSC0ctMxzi8cmAUpz4yA.png" /></figure><ul><li>The job level is strongly correlated with a total working years</li><li>Monthly income is strongly correlated with Job level</li><li>Monthly income is strongly correlated with total working hours</li><li>Age is strongly correlated with monthly income and Total Working years</li></ul><h4>FEATURE ENGINEERING</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*2Cew_2DGn_XQB_EDi3kXoA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*bHTbpT4PIKVr1FlllmN0vg.jpeg" /></figure><h4>CREATE TESTING AND TRAINING DATASET &amp; PERFORM DATA CLEANING</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*e6bzJ9hLRUutEFQN-Yr9eg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*XY2p9KuUsYqo0mzYkXFEaA.png" /></figure><h4>A LOGISTIC REGRESSION CLASSIFIER</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*4JKOr3v0wQ6_nSNhaLAt0A.png" /><figcaption>Logistics Regression Model and Accuracy of the Model</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*3dBZQzM7_5iN43xA99KWeQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*MoJm0qDEpoS8BArnb4fCXA.png" /><figcaption>The Classification Report of the Logistic Regression Model</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*L2UwnZhUfgTDZsGnw8f_rg.png" /><figcaption>ROC Curve of the Logistic Regression Model</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*tuEH7zD6dgwMRan2dZocEQ.png" /></figure><h4>TRAIN AND EVALUATE A RANDOM FOREST CLASSIFIER</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*P6LoxxriJeowOs5rU_HcOQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*RxgeLeHe_i4ooUg403omkQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*PjgTrFwx5STpsotUf_UoHA.png" /><figcaption>Classification Report for Random Forest Classifer</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*l6oUtvll_Q5fbs5atv0C0g.png" /><figcaption>ROC Curve for both Logistic Regression and Random Forest Classifier</figcaption></figure><h4><strong>K-FOLDS CROSS-VALIDATION FOR </strong>MULTIPLE MACHINE LEARNING MODEL</h4><p>To evaluate the performance of any machine learning model we need to test it on some unseen data. For this, we used the Cross-validation which is the resampling procedure used to evaluate machine learning models. This technique is used to estimate the skill of a machine learning model on unseen data. The entire data randomly split into k folds (n_folds=10), then fit the model using 1 folds as a test and others as a training sample of models. Repeat this process until every K-fold serves as the test set. Then take we take the average of our scores.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cx_QrtSWU12kP5GhF0eGdA.png" /><figcaption>k-Fold Cross-Validation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*j3tjXN7JZnhU_oJGUCM1EQ.png" /></figure><pre>plt.subplots(figsize=(12,16))<br>plt.xticks(rotation=45)<br>sns.boxplot(new_model_data_frame.index, accuracy</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*fsAaW-LbKRSjYMv3KdCQ8Q.png" /><figcaption>Machine Learning Model Accuracy Plot</figcaption></figure><h4>Conclusion</h4><p>Well Done. Congratulations because we just cover the classification problem step by step. I have to give some credit for this article. You may found more fancy study if you go to<a href="https://www.kaggle.com/pavansubhasht/ibm-hr-analytics-attrition-dataset"> Kaggle kernels </a>for this dataset. Also, I have been followed the <a href="https://www.udemy.com/course/data-science-for-business-6-real-world-case-studies/">data science for business project Udemy course</a> for this project. You found<a href="http://aysebat.pythonanywhere.com/index.html"> my personnel portfolio in the link</a>.</p><p>Here my social network.<a href="https://www.linkedin.com/in/aysebat/"> Linkedin</a>, <a href="https://github.com/aysbt/">Github,</a> <a href="http://Ayse Bat, Ph D (@aaysbt) _ Twitter">Twitter</a></p><p>Here my other project at the<a href="http://aysebat.pythonanywhere.com/works.html"> Portfolio website.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be94751e4df5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fashion MNIST data training using PyTorch]]></title>
            <link>https://medium.com/@aaysbt/fashion-mnist-data-training-using-pytorch-7f6ad71e96f4?source=rss-c4b9afb95bfa------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f6ad71e96f4</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[pytorchudacityscholar]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[fashion-mnist]]></category>
            <category><![CDATA[udacity]]></category>
            <dc:creator><![CDATA[Ayşe Bat]]></dc:creator>
            <pubDate>Tue, 18 Feb 2020 08:51:36 GMT</pubDate>
            <atom:updated>2021-08-20T03:49:47.994Z</atom:updated>
            <content:encoded><![CDATA[<h3>Fashion MNIST dataset training using PyTorch</h3><p>This project is a part of<a href="https://www.udacity.com/bertelsmann-tech-scholarships"> the Bertelsmann Tech Scholarship AI Track Nanodegree Program</a> from Udacity. In this project, we are going to use Fashion MNIST data sets, which is contained a set of 28X28 greyscale images of clothes. Our goal is building a neural network using Pytorch and then training the network to predict clothes. This trained network will return a probability for 10 classes of clothes shown in images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*grbn8FBN_xlBfQu-AB79fA.png" /></figure><p>Let’s write down a route map to follow</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*rcMiwJlFakqI7bzaqintrQ.png" /></figure><ul><li>Load and visualize the data</li><li>Pre-Process your data (Transform: Normalization, Converting into tensor)</li><li>Define your model using Pytorch</li><li>Training the model</li><li>Save the Best model: find the best model using the validation dataset</li><li>Test out your model</li></ul><blockquote>LET’S GET START</blockquote><h4>Importing Libraries</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*WiZtp2Rqz4PI-pERckI1Mw.png" /></figure><ul><li><a href="https://pytorch.org/docs/stable/optim.html">torch.optim</a> implement various optimization algorithms like SGD and Adam.</li><li><a href="https://pytorch.org/docs/stable/nn.html#torch-nn-functional">torch.nn.functional</a> for non-linear activation functions like relu, softmin, softmax, logsigmoid, etc.</li><li>The <a href="https://pytorch.org/docs/stable/torchvision/index.html#module-torchvision">torchvision</a> packages consist of popular datasets, model architectures, and common image transformations for computer vision. We are using datasets and transform from torchvision to download a fashion-MNIST dataset and transforms an image using compose transformations.</li><li>Subset RandomSampler used to split the dataset into train and validation subsets for validation of our model.</li></ul><h4>Download datasets and Transform images</h4><ol><li>Extract — Get the<em> Fashion-MNIST</em> image data from the source.</li><li>Transform — Put our data into a tensor form.</li><li>Load — Put our data into an object to make it easily accessible.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fHIabSC6ktaMV59WMsfXfg.png" /></figure><ul><li><a href="https://pytorch.org/docs/stable/torchvision/transforms.html">transforms.Compose</a> creates a series of transformation to prepare the dataset.</li><li><a href="https://pytorch.org/docs/stable/torchvision/transforms.html#torchvision.transforms.ToTensor">transforms.ToTenser</a> convert PIL image<em>(L, LA, P, I, F, RGB, YCbCr, RGBA, CMYK, 1)</em> or numpy.ndarray<em> (H x W x C) i</em>n the range [0, 255] to a torch.FloatTensor of shape<em> (C x H x W)</em> in the range [0.0, 1.0].</li><li>transform.Normalize Normalize a tensor image with mean and standard deviation. Tensor image size should be<em> (C x H x W) </em>to be normalized which we already did use<a href="https://pytorch.org/docs/stable/torchvision/transforms.html#torchvision.transforms.ToTensor">transforms.ToTenser</a>.</li><li>datasets.FashionMNIST to download the Fashion MNIST datasets and transform the data. train=True if we want to get trained dataset otherwise set the parameter False for the test dataset.</li><li>torch.utils.data.Dataloader takes our data train or test data with parameter batch_size and shuffle. batch_size define the how many samples per batch to load, and shuffle parameter set the True to have the data reshuffled at every epoch.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*ObmfniGpwcaCoMyImYj8Fw.png" /></figure><h4>Building the network</h4><p>Our images are 28x28 2D tensors, so we need to convert them into 1D vectors. 784 is 28 times 28, so, this is typically called <em>flattening</em>, we flattened the 2D images into 1D vectors. This is our input layer and here we need to 10 output layers for the classification of the clothes.</p><p>While we are defining the hidden layers, we are able to choose the arbitrary number. But this selection directly affects our neural network performance. We should modify the number to find out an optimized model for our image classification problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2SHOuTUK51_Up3D9JMAplA.png" /><figcaption>Fully Connected Neural Network Model</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*PnykCAoU8iTAWSq-J9Sr7w.png" /></figure><ul><li>Defining our Neural Network (NN)architectures using the python class.</li><li>PyTorch provides a nn.Module that building neural networks.</li><li>super().__init__() this creates a class that tracks the architecture and provides a lot of useful methods and attributes.</li><li>In NN architecture, we defined 3 hidden layers and 1 output layer.</li><li>self.fc1 = nn.Linear(784, 256): This line creates a module for a linear transformation,<strong><em> xw+b</em></strong>, with 784 inputs and 256 outputs for first hidden layer and assigns it to self.fc1. The module automatically creates the weight and bias tensors which we&#39;ll use in the forward method.</li><li>Similarly, the following lines create another linear transformation with 256 inputs and 128 output and so on.</li><li>In Forward Model, we take tensor input x to change its shapes to our batch size using x.shape[0] , the -1 fill out the second dimension.</li><li>Then, we could pass thought operations that we defined in __init__ .The input layer goes through the hidden layer with a together dropout and RELU activation function then reassign it to the x.</li><li>For the output layer, we pass through the Log Softmax function to obtain the log-probabilities in neural-network.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*zcryVkxOqbHiD3N4meNsFg.png" /></figure><p>The training pass process is as follow:</p><ul><li>model = Classifier()This line is actually created our model.</li><li>Defined the criterion with Negative log-likelihood loss and also defined our optimizer (SGD)to optimize our model’s parameter when we loop through the dataset using epochs.</li><li>We are going to track running loss and validation loss for each epoch to see the evaluation of our model.</li><li>For raining the data we set the model in train mode: model.train().Then loop over the “trainloader” to extract images and labels from a train data. The following process shows the train pass.</li></ul><blockquote>zero_grad():Clear the gradients of all optimized variables</blockquote><blockquote>log_ps = model(images): Make a forward pass through the network to getting log probabilities bypassing the images to the model.</blockquote><blockquote>loss = criterion(log_ps, lables):Use the log probabilities (log_ps) and labels to calculate the loss.</blockquote><blockquote>loss.backward():Perform a backward pass through the network to calculate the gradients for model parameters.</blockquote><blockquote>optimizer.step()Take a step with the optimizer to update the model parameters.</blockquote><ul><li>We need to use validation data to know when to stop training the model. So, we have validatiın batch that loop over the validation data and labels.</li><li>In validation batch, we apply the model and calculate the loss for the validation data set. We are also going to trach the validation loss. We need to stop training whenever train loss decrease but validation loss does not.</li><li>Print out the average training loss and validation loss, and then the model is going to save whenever the calculated validation loss is smaller than the saved validation loss.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*M9Sn7KsuuHAYn2ZE2TUjfA.png" /></figure><p>We keep tracking the validation loss and train loss to investigate the averages values over time. The following plot shows averages values for train loss and validation loss which calculated for each epoch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*MWDbr_vgqbbNdO77ZiENcw.png" /><figcaption>Tarin loss and validation loss for each epoch</figcaption></figure><h4>Test the Trained Network</h4><p>Finally, we test our best model on previously unseen <strong>test data</strong>. Testing on unseen data is a good way to check that our model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*fgJ4Fiax8Jk4mG_8kX9HhA.png" /><figcaption>Testing our model using unseen test data.</figcaption></figure><p>So, we come to the end. We would like the see how our model performs. For this, we are going the print out the accuracy of our model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*8GdRlJDfb7ljjnTZNwDZVQ.png" /></figure><p>Then visualize the data to displays test images and their labels in the following format: predicted (ground-truth). The text will be green for accurately classified examples and red for incorrect predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*146yMJVXr959DETGFNF9eQ.png" /></figure><p>Finally, completed the train and test our neural network. This project shows the road map for the basic neural network using Pytorch. Thank you so much Udacity and Bertelsmann to reach out to these courses. For the Note, I am still a learner so, please let me know any additional information or comment on this article. You may found the Colab notebook<a href="https://colab.research.google.com/drive/1nkAZaX5QQhnO3XN3FE27jW3JKk0tcPd_?usp=sharing"> here</a>.</p><p>Follow me on<a href="https://twitter.com/aaysbt"> Twitter</a>, <a href="http://linkedin/">Linkedin</a> or in <a href="https://medium.com/@aaysbt">Medium.</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3oEdva9BUHPIs2SkGk%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3oEdva9BUHPIs2SkGk%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExOXh4a2htcjMzODNoNzJjZGlvZDIxM2hnc2ZsOWhtZ2hzbGRkYW5naiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F3oEdva9BUHPIs2SkGk%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7de1ed3519b8fa9c59ef3066525671c/href">https://medium.com/media/e7de1ed3519b8fa9c59ef3066525671c/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f6ad71e96f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predictive Analysis in Python]]></title>
            <link>https://medium.com/my-data-camp-journey/predictive-analysis-in-python-97ca5b64e97f?source=rss-c4b9afb95bfa------2</link>
            <guid isPermaLink="false">https://medium.com/p/97ca5b64e97f</guid>
            <category><![CDATA[predictive-analytics]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Ayşe Bat]]></dc:creator>
            <pubDate>Fri, 22 Mar 2019 19:49:36 GMT</pubDate>
            <atom:updated>2022-08-09T07:06:24.153Z</atom:updated>
            <content:encoded><![CDATA[<p>I am a newbie to machine learning, and I will be attempting to work through predictive analysis in Python to practice how to build a logistic regression model with meaningful variables.</p><h4>What is predictive analysis?</h4><p>The predictive analysis makes predictions on what might happen in the future using historical data. The data is gathered in basetable which is consist of three important components: population, the candidate predictors, and target. <strong>The population </strong>is the group of people or objects you wish to make predictions for. The candidate<strong> predictor</strong> describes the people or objects in the population, which given information could use the predict the event. Finally, <strong>the target </strong>has information about the events to predict. it is one of the events that occur and zero otherwise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hycx0kyvdC3OBRL0Ogv_zQ.png" /><figcaption>Structure of the base table</figcaption></figure><p>In this predictive analysis, we are going to consider the non-profit organization which has a donor database with people who donated in the past. This organization considering sending a letter to its donors to ask them to donate to a specific project.</p><ul><li>One option here is to send the letter to all the candidate donors. But, this could be very expensive.</li><li>The predictive analysis here allows us to determine the donors that are most likely to donate.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*9KjYelWbTykgcpiYmxKwsg.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7903b7f68a4a7a31be3583325368db56/href">https://medium.com/media/7903b7f68a4a7a31be3583325368db56/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*YXp7ZZPuw6aMG5WFn8IcHQ.png" /></figure><h4>Logistic Regression</h4><p><strong>Logistic regression</strong> is a predictive analysis that makes predictions about whether something is True(1) or not(0). It is widely used for classifying the data and explaining the relationship between the binary variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yjTiGpaaeepaO4mKMhmZFg.png" /><figcaption>Logistic Regression</figcaption></figure><p>If we plot the target as a function of age for all donors and then we fit a regression line through points, it is of the form a*x+b, with a positive number. <em>a </em>is called the<em> </em><strong><em>coefficient</em></strong> of age, and<em> b</em> is called the <strong><em>intercept</em></strong>. If we plot the target as a function of the time since the last donation for each donor, it can be seen that those who recently donated, are more likely to donate. in this case, the coefficient of recency is negative.</p><p>We could make a prediction using one variable or a more complicated model adding other variables. We can build a logistic regression model using the module<em> linear_model</em> from scikit-learn.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee3e4d1a891c00a57a8c6f1cb8f18fc2/href">https://medium.com/media/ee3e4d1a891c00a57a8c6f1cb8f18fc2/href</a></iframe><pre>#result of printing<br>0.007178355658921441 age<br>0.11430414536794431 gender_F<br>-0.0013087501133203447 time_since_last_gift<br>[-2.54149728]</pre><p>So, our logistic regression model looks as follows:</p><pre>-2.5 + 0.0072* age + 0.1143 *gender_F - 0.0011* time_since_last_gift</pre><p>For example, we have 70 years old female person who made the last donation 120 days ago.</p><pre>= -2.5 + 0.0072* 70 + 0.1143 *1 - 0.0011* 120<br>= -2.137</pre><pre>#Then we calculate the logit function:<br>1/(1+e^-(-2.0123)) = 0.117 </pre><p>The logit function is used for the probabilities for the values between 0 and 1. As you can see from the above example for the given data which is 70 years old female person who made the last donation 120 days ago. We calculated the probability of making a donation is 11%.</p><p>The good news is we don’t have to calculate the predicted probabilities manually in python. We are going to use the <em>predict_proba</em> function on the <em>logreg</em> object to calculate the probabilities. The <em>predict_proba</em> has two-dimensional arrays. The first number is the probability that the donor will not donate (target 0), and the second number is the probability of the donor will donate (target 1).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54c7627594616f6eaa10d30ab09b0550/href">https://medium.com/media/54c7627594616f6eaa10d30ab09b0550/href</a></iframe><pre>[[0.93427169 0.06572831]<br> [0.9454883  0.0545117 ]<br> [0.9185279  0.0814721 ]<br> [0.95269877 0.04730123]<br> [0.94745512 0.05254488]]</pre><h4>Calculating AUC</h4><p>The AUC value assesses how well a model can order observations from a low probability to be the target to a high probability to be the target. In Python, the <em>roc_auc_score</em> function can be used to calculate the AUC of the model. It takes the true values of the target and the predictions as arguments.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/567fa33784de2ff104ffcdc237be2937/href">https://medium.com/media/567fa33784de2ff104ffcdc237be2937/href</a></iframe><pre>#result of the auc calculation using the variable of age, gender_F, time_since_last_gift<br>0.63</pre><h4>Variable Selection</h4><p>We have more variables that we could include in our model but we have to make wisely set of variable selections for our model.</p><p>Let’s define a function that calculates AUC for a given set of a variable of the model that uses this variable set as predictors named as auc_score.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ba6a9716548680d29493f73275dad93/href">https://medium.com/media/6ba6a9716548680d29493f73275dad93/href</a></iframe><pre>#result of auc score using the max_gift, min_gift, and mean_gift<br>0.7125</pre><ul><li>We are going to define thenext_best_variable function which finds the variable that should be added in the next step to the variable list.</li><li>We write a for loop iterate over all column variables to find the best variable for our model.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e7099aece1ab3a9db1036aad2aa2453/href">https://medium.com/media/7e7099aece1ab3a9db1036aad2aa2453/href</a></iframe><pre>Variable added in step 1 is max_gift<br>Variable added in step 2 is number_gift<br>Variable added in step 3 is time_since_last_gift<br>Variable added in step 4 is mean_gift<br>Variable added in step 5 is age<br>[&#39;max_gift&#39;, &#39;number_gift&#39;, &#39;time_since_last_gift&#39;, &#39;mean_gift&#39;, &#39;age&#39;]</pre><pre>Let’s find out the AUC Score for our current variable<br>current_list_auc = auc_score(current_variable, ‘target’, basetable)<br>print(current_list_auc)</pre><pre>0.768756710130262</pre><p>The credit goes to <a href="https://www.datacamp.com/courses/foundations-of-predictive-analytics-in-python-part-1">Foundations of Predictive Analytics in Python at the DataCamp </a>course. In this course, you will learn how to build a logistic regression model with meaningful variables (covered here). You will also learn how to use this model to make predictions and how to present it and its performance to business stakeholders. I totally recommended the course.</p><h4>Final Thought</h4><p>You may find this study in my <a href="https://github.com/aysbt/DataCamp/blob/master/Foundations_of_Predictive_Analytics_in_Python%20.ipynb">GitHub</a> account as part of the Datacamp repository.</p><p>I have written this article to improve my data analytic skills and machine learning skills so I am still a learner. Please let me know any additional information or comment on this article.</p><p>Follow me on<a href="https://twitter.com/aaysbt"> Twitter</a>, <a href="http://linkedin/">Linkedin</a>, or <a href="https://medium.com/@aaysbt">Medium.</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FxUA7aN1MTCZx97V1Ic%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Filiza-iliza-shlesinger-xUA7aN1MTCZx97V1Ic&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FxUA7aN1MTCZx97V1Ic%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/577d368f6ba5853de6cfb0af44705e96/href">https://medium.com/media/577d368f6ba5853de6cfb0af44705e96/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97ca5b64e97f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/my-data-camp-journey/predictive-analysis-in-python-97ca5b64e97f">Predictive Analysis in Python</a> was originally published in <a href="https://medium.com/my-data-camp-journey">My Data Science Journey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Import Your data from Different sources using Python]]></title>
            <link>https://medium.com/my-data-camp-journey/import-your-data-from-different-sources-using-python-fd253330aa2a?source=rss-c4b9afb95bfa------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd253330aa2a</guid>
            <category><![CDATA[hdf5]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[excel]]></category>
            <category><![CDATA[import-data]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Ayşe Bat]]></dc:creator>
            <pubDate>Fri, 15 Mar 2019 20:14:16 GMT</pubDate>
            <atom:updated>2019-03-15T20:14:16.017Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*0nZNUPTquNxWwFYOb4foiQ.png" /></figure><p>The data could have come from different sources, we need to ability to import and manage this file, successfully. So, in this source, we will look at how to import data from different file type. We will learn to import the files from a flat file(.txt, .csv), other types of software (Excel, Stata, SAS, Matlab), and.</p><h4>Import data from Flat File</h4><p>To check out any plain text file, you can use the Python’s open() function to open a connection to the file.</p><pre>#assign the file name to the variable string<br>file_name = &#39;file_name.txt&#39;</pre><pre>#pass the file name to the open function using &#39;r&#39; mode <br>file = open(file_name, mode=&#39;r&#39;)# only for reading</pre><pre>#to connection to the file apply the read() function<br>text =file.read()<br>#close the connection<br>file.close()</pre><p>By using a context manager construct that allows us to create a context in which you can execute commands with the file open. We can avoid having to close to connection to the file using the ‘with’ statement. For the large files, we may want to print a few lines. You can use ‘file.readline()’ function to execute the first line of a text file. If you execute the same comment again, the second line will be printing and so on.</p><pre>#By using the with open we don&#39;t need to close the connection.<br>with open(file_name, &#39;r&#39;) as file:<br>     print(file.read())</pre><pre>#print out the file line by line executing with file.readline()<br>with open(file_name, &#39;r&#39;) as file:<br>     print(file.readline())<br>     print(file.readline())<br>     print(file.readline())</pre><h4>Importing Flat File using Numpy</h4><p>Flat files are a basic text file containing records, that is table data, without structured relationships.</p><p>We could use the numpy function loadtxt()</p><ul><li>The first argument will be the filename.</li><li>The second will be the delimiter which can take &#39;,&#39; for comma separated file and &#39;\t&#39; for tab-delimited file</li><li>skiprows allows you to specify how many rows you wish to skip.</li><li>usecols takes a list of the indices of the columns you wish to keep.</li><li>dtype=’str’ will ensure that all entries are imported as a string.</li></ul><pre>import numpy as np<br>file_name = ‘data/mnist_kaggle_some_rows.csv’</pre><pre>#Default delimiter is white space so, we need the specify delimiter parameter explicitly.<br>data = np.loadtxt(file_name, delimiter=’,’)</pre><pre>#we are reading a file as a numpy array<br>print(type(data))<br>print(data)</pre><pre>&lt;class &#39;numpy.ndarray&#39;&gt;<br>[[1. 0. 0. ... 0. 0. 0.]<br> [0. 0. 0. ... 0. 0. 0.]<br> [1. 0. 0. ... 0. 0. 0.]<br> ...<br> [2. 0. 0. ... 0. 0. 0.]<br> [0. 0. 0. ... 0. 0. 0.]<br> [5. 0. 0. ... 0. 0. 0.]]</pre><h4>Importing different datatypes:</h4><p><em>Let’s import the text file which has</em></p><ul><li>text header, consisting of a string</li><li>tab-delimited</li></ul><p>Due to the file containing string header we need to handle it. If we import the file using loadtxt() function without handling string file we could get the ValueError.</p><ul><li>Alternative 1: We can set the dtype = str to avoid to ValueError,</li><li>Alternative 2: We can skip the first row, using the skiprows argument!</li></ul><pre>#Alternative 1:<br>file_sea_slug = ‘data/seaslug.txt’<br>data_alt_1 = np.loadtxt(file_sea_slug, delimiter=’\t’, dtype=str)<br>print(type(data_alt_1))<br>print(data_alt_1[0:5])</pre><pre>&lt;class &#39;numpy.ndarray&#39;&gt;<br>[[&#39;Time&#39; &#39;Percent&#39;]<br> [&#39;99&#39; &#39;0.067&#39;]<br> [&#39;99&#39; &#39;0.133&#39;]<br> [&#39;99&#39; &#39;0.067&#39;]<br> [&#39;99&#39; &#39;0&#39;]]</pre><pre>#---------------------------------------------------------------#</pre><pre>#Alternative 2:<br>data_alt_2 = np.loadtxt(file_sea_slug, delimiter=&#39;\t&#39;, skiprows=1)<br>print(type(data_alt_2))<br>print(data_alt_2[0:9])</pre><pre>&lt;class &#39;numpy.ndarray&#39;&gt;<br>[[9.90e+01 6.70e-02]<br> [9.90e+01 1.33e-01]<br> [9.90e+01 6.70e-02]<br> [9.90e+01 0.00e+00]<br> [9.90e+01 0.00e+00]<br> [0.00e+00 5.00e-01]<br> [0.00e+00 4.67e-01]<br> [0.00e+00 8.57e-01]<br> [0.00e+00 5.00e-01]]</pre><p>To import datasets which have different datatypes in different columns; for example, one column may contain strings and another float. The function np.loadtxt() will freak at this. There is another function, np.genfromtxt(), which can handle such structures. If we pass dtype=None to it, it will figure out what types each column should be.</p><pre>data <strong>=</strong> np.genfromtxt(file_name, delimiter<strong>=</strong>&#39;,&#39;, names<strong>=True</strong>, dtype<strong>=None</strong>)</pre><ul><li>The first argument is the filename</li><li>The second specifies the delimiter</li><li>The third argument names tell us there is a header (names=True)</li><li>dtype=None is representing the different data type</li></ul><p><em>There is also another function </em><em>np.recfromcsv()that behaves similarly to np.genfromtxt(), except that its default dtype is None!</em></p><pre># Let’s look at titanic.csv <br># ‘,’, comma separated<br># there is a header<br># There is string and number data type in it.<br>titanic = np.genfromtxt(‘data/titanic_sub.csv’, delimiter=’,’, names=True, dtype=None)<br>print(titanic[0:2])</pre><pre>[(1, 0, 3, b&#39;male&#39;, 22., 1, 0, b&#39;A/5 21171&#39;,  7.25  , b&#39;&#39;, b&#39;S&#39;)<br> (2, 1, 1, b&#39;female&#39;, 38., 1, 0, b&#39;PC 17599&#39;, 71.2833, b&#39;C85&#39;, b&#39;C&#39;)<br>]</pre><pre># using np.recfromcsv()<br>titanic_2 = np.recfromcsv(&#39;data/titanic_sub.csv&#39;)<br>print(titanic_2[0:2])</pre><pre>[(1, 0, 3, b&#39;male&#39;, 22., 1, 0, b&#39;A/5 21171&#39;,  7.25  , b&#39;&#39;, b&#39;S&#39;)<br> (2, 1, 1, b&#39;female&#39;, 38., 1, 0, b&#39;PC 17599&#39;, 71.2833, b&#39;C85&#39;, b&#39;C&#39;) ]</pre><h4>Importing Data using Pandas</h4><p>What we learn so far is to import a bunch of different types of flat files into python as Numpy arrays. Although the numpy array is incredibly useful and has numerous of purpose, they can not handle the data as two dimensional labeled data structure.</p><p>Pandas offer us to the DataFrame, which has observations (rows), and variables(columns).</p><pre>#import pandas <br>import pandas as pd</pre><pre>#import titanic as dataframe<br>df_titanic = pd.read_csv(&#39;data/titanic_sub.csv&#39;)</pre><pre>print(type(df_titanic))</pre><pre>#let&#39;s look at first 5 row<br>df_titanic.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*gQ4GHKt97PpwMlrRHd23ew.png" /></figure><p>Handling read_csv() function under different circumstances</p><ul><li>sep: Stands for a separator, a default is ‘,‘ as in .csv(comma separated values): We could specify if needed.</li><li>header= None: Load a CSV with no headers</li><li>names=[&#39;column_name1&#39;,&#39;column_name2&#39;]: Load a .csv while specifying column names</li><li>index_col=&#39;date&#39;: Load a .csv with setting the index column to column name like we would like set index as a date.</li><li>na_values=[&#39;NA&#39;]: Load a .csv while specifying “NA” as missing values.</li><li>skiprows=3: Load a .csv while skipping the top 3 rows</li></ul><h4>Importing Other File Types into Python</h4><ul><li>Excel spreadsheets</li><li>Matlab files</li><li>SAS files</li><li>STATA files</li><li>HDF5 files</li></ul><p><strong>Pickle files: </strong>Pickling means converting the object into a sequence of bytes, or byte-stream. <br><strong>Warning </strong><em>Loading pickled data received from untrusted sources can be unsafe. Firstly, we are going to create our pickle file from Titanic DataFrame.</em></p><pre>#import pickle<br>import pickle</pre><pre>#Let’s save the Titanic data frame into a pickle file<br>pd.to_pickle(df_titanic, ‘data/titanic_pickle.pkl’)</pre><pre>#first try with with open<br># &#39;rb&#39; reading and binary<br>with open (&#39;data/titanic_pickle.pkl&#39;,&#39;rb&#39;) as file:<br>    data = pickle.load(file)<br>#reading the data type as DataFrame<br>print(type(data))<br>print(data[0:3])</pre><pre>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>   PassengerId  Survived  Pclass     Sex   Age  SibSp  Parch  \<br>0            1         0       3    male  22.0      1      0   <br>1            2         1       1  female  38.0      1      0   <br>2            3         1       3  female  26.0      0      0   </pre><pre>             Ticket     Fare Cabin Embarked  <br>0         A/5 21171   7.2500   NaN        S  <br>1          PC 17599  71.2833   C85        C  <br>2  STON/O2. 3101282   7.9250   NaN        S</pre><pre>#---------------------------------------------------------------#</pre><pre>#Let&#39;s read with pandas<br>unpickled_df = pd.read_pickle(&#39;data/titanic_pickle.pkl&#39;)<br>#unpickled_df.head()</pre><p><strong>Excel File: </strong>You may need to deal with excel file at some point.<strong> </strong>Here, you’ll learn how to use pandas to import Excel spreadsheets.</p><ul><li>Use the pandas’ ExcelFile() to load the .xlsx file</li><li>Figure out what is the sheets name using .sheet_names</li><li>We could load the particular sheets into a DataFrame for this we need to apply a parse() method with a single parameter, which is either the name of string or the index as a float of the sheets that you wish to load.</li></ul><pre>#load the battledeath.xlsx into the excel_data variable<br>excel_data = pd.ExcelFile(‘data/battledeath.xlsx’)</pre><pre>#print the sheet name <br>print(excel_data.sheet_names)</pre><pre>[&#39;2002&#39;, &#39;2004&#39;]</pre><pre>#Load the sheet into dataframe <br>df1 = excel_data.parse(&#39;2004&#39;)<br>df2 = excel_data.parse(&#39;2002&#39;)<br>print(df1.head())</pre><pre>War(country)      2004<br>0  Afghanistan  9.451028<br>1      Albania  0.130354<br>2      Algeria  3.407277<br>3      Andorra  0.000000<br>4       Angola  2.597931</pre><blockquote>It could be read using <em>pd.read_excel()</em> function.</blockquote><pre># we could specify the sheet_name<br>excel_df = pd.read_excel(‘data/battledeath.xlsx’, index_col=0, sheet_name=’2004&#39;)</pre><p><strong>SAS File: Statistical analysis System</strong></p><ul><li>Business analysis and biostatistics</li><li>Advanced analysis, Multivariable analysis</li><li>Data management</li><li>Predictive analytics</li><li><em>sas7bdat</em>: dataset files &amp;<em> sas7cdat:</em> catalog file</li></ul><pre>#if the sas7bdat dosen&#39;t install your conda you could install first using followinf line.<br>pip install sas7bdat</pre><pre># import the sas7bdat <br>from sas7bdat import SAS7BDAT<br>with SAS7BDAT (&#39;data/sales.sas7bdat&#39;) as file:<br>    df_sas = file.to_data_frame()<br>print(df_sas.head())</pre><pre>YEAR     P           S<br>0  1950.0  12.9  181.899994<br>1  1951.0  11.9  245.000000<br>2  1952.0  10.7  250.199997<br>3  1953.0  11.3  265.899994<br>4  1954.0  11.2  248.500000</pre><p><strong>Stata File: “Statistics” + “data”</strong></p><ul><li>Importing Stata files as DataFrames using the pd.read_stata()from pandas.</li><li>Academic &amp; social sciences research</li></ul><pre>df_stata = pd.read_stata(&#39;data/disarea.dta&#39;)</pre><p><strong>HDF5: Hierarchical Data Format version 5</strong></p><ul><li>Storing for a large quantity of numerical data</li><li>Datasets can be hundreds of gigabytes, or terabytes</li></ul><pre>#h5py library<br>import h5py<br>df_h5py = h5py.File(‘data/L-L1_LOSC_4_V1–1126259446–32.hdf5’, ‘r’)<br>print(type(df_h5py))<br>print(df_h5py)</pre><pre>&lt;class &#39;h5py._hl.files.File&#39;&gt;</pre><pre>#we could explore the hierarhical structure</pre><pre>for key in df_h5py.keys():<br>    print(key)</pre><pre>#Each of these HDF group which we could think thse group as directories.</pre><pre>meta<br>quality<br>strain</pre><pre>print(type(df_h5py[&#39;meta&#39;]))<br>&lt;class &#39;h5py._hl.group.Group&#39;&gt;</pre><pre>for key in df_h5py[&#39;meta&#39;].keys():<br>    print(key)</pre><pre>Description<br>DescriptionURL<br>Detector<br>Duration<br>GPSstart<br>Observatory<br>Type<br>UTCstart</pre><h4>Final Thought</h4><p>You may find this study in my <a href="https://github.com/aysbt/DataCamp/blob/master/Importing_Data_in_Python_part1.ipynb">githup</a> account as part of Datacamp repository.</p><p>I have written this article to improve my data analytic skills so I am still a learner. Please let me know any additional information or comment on this article.</p><p>Follow me on<a href="https://twitter.com/aaysbt"> Twitter</a>, <a href="http://linkedin/">Linkedin</a> or in <a href="https://medium.com/@aaysbt">Medium.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd253330aa2a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/my-data-camp-journey/import-your-data-from-different-sources-using-python-fd253330aa2a">Import Your data from Different sources using Python</a> was originally published in <a href="https://medium.com/my-data-camp-journey">My Data Science Journey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Brief Introduction to Statistical Analysis using Python]]></title>
            <link>https://medium.com/my-data-camp-journey/brief-introduction-to-statistical-analysis-using-python-94545216198c?source=rss-c4b9afb95bfa------2</link>
            <guid isPermaLink="false">https://medium.com/p/94545216198c</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[statistical-analysis]]></category>
            <category><![CDATA[statistical-learning]]></category>
            <dc:creator><![CDATA[Ayşe Bat]]></dc:creator>
            <pubDate>Fri, 08 Mar 2019 14:11:42 GMT</pubDate>
            <atom:updated>2019-03-08T14:11:42.755Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*_Whjy0D-uBXpgIPcW5QTPA.jpeg" /></figure><p>Statistical thinking is really important for data analysis, in this article I will emphasize the core of the statistical analysis.</p><blockquote>Graphical Exploratory Data Analysis</blockquote><ul><li>Exploratory Data Analysis (EDA)</li><li>Empirical cumulative distribution functions (ECDF)</li></ul><blockquote>Quantitative Exploratory Data Analysis</blockquote><ul><li>Mean</li><li>Median</li><li>Variance and standard deviation</li><li>Covariance, and Pearson Correlation Coefficient</li></ul><h3>Graphical Exploratory Data Analysis</h3><p>Exploring your data (EDA) is a crucial step in your analysis.</p><ul><li>Organizing</li><li>Plotting</li><li>Computing a few numerical summaries</li></ul><p>For EDA, we are going to explore the 2008 US swing state election result which is at country level in each of the three major swing states of Pennsylvania, Ohio, and Florida.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*qHZRGbLqOqq9wMMns7Zh6w.png" /></figure><p>We take the Democratic share (dem_share) of the vote in the counties of all the three swing state and plot them as a histogram. We are interested in the fraction of the vote to Brack Obama in the county.</p><pre>#We can specified where the edge of the bars of histigrams are using the bins keyword<br># 20 evenly spaced bins will create<br>_ = plt.hist(swing_state[&#39;dem_share&#39;], bins =20)</pre><pre>#labeling the plot<br>_ = plt.xlabel(&#39;Percent of vote for Obama&#39;)<br>_ = plt.ylabel(&#39;Number of counties&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*CowZttyeWxnnUqms22RvKA.png" /></figure><p>With the bee swarm plot, we could plot the vote totals in three swing states. Each point in the plot represents the share of the vote Obama got into a single count. The y-axis gives us quantitative information.</p><pre>sns.swarmplot(x=’state’, y=’dem_share’, data=swing_state)<br>plt.xlabel(‘state’)<br>plt.ylabel(‘percent of vote for Obama’)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*v1MNm6Iq15EZjluhIZ_T7w.png" /></figure><ul><li>We can clearly see that Obama got less than 50% of the vote in the majority of counties in each of the three swing states.</li></ul><p><strong>Empirical cumulative distribution functions (ECDF): </strong>We are going to plot ECDF for the percentage of the vote for the Obama. The x-axis is a percent of the vote that vote for Obama. The y-axis is the fraction of data point that has a value smaller than the corresponding x-value.</p><pre>#We can use np.sort() to generate our x-data<br>x = np.sort(swing_state[&#39;dem_share&#39;])</pre><pre>#y-axis is evenly speaced data point with a max 1.<br>y = np.arange(1, len(x) +1)/len(x)</pre><pre>_ = plt.plot(x,y, marker =&#39;.&#39;, linestyle=&#39;none&#39;)<br>plt.xlabel(&#39;Percent of Vote for Obama&#39;)<br>plt.ylabel(&#39;ECDF&#39;)</pre><pre>#Keep the data off from plot edge<br>plt.margins(0.02) <br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*GIn1e8UUkfYpqjetj30lXg.png" /></figure><p><em>75% of counties in swing states had 50% or less of its people vote for Obama</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F8gNQZ9IpkcdiAjfOgN%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F8gNQZ9IpkcdiAjfOgN%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F8gNQZ9IpkcdiAjfOgN%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e362b0e98b434024c10e767dba9f9f1/href">https://medium.com/media/0e362b0e98b434024c10e767dba9f9f1/href</a></iframe><h3>Quantitative Exploratory Data Analysis</h3><p><strong>Mean</strong>: If you have a sample of <em>n</em> values, <em>xi</em>, the mean, <em>μ</em>, is the sum of the values divided by the number of values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/93/1*9pGCnmcwjt-AoDdttSf7iw.png" /></figure><p><strong>Outliers:</strong> Data point whose value is far greater or less than most of the rest of the data.</p><ul><li><em>The mean was highly affected by outliers.</em></li></ul><p><strong>The median:</strong> is the middle value of the dataset and is immune to data that have extreme values. The median is the special name for the 50th percentile. Similarly, the 25th percentile is the value of the data point that is greater than 25% of the sorted data.</p><pre>print(&#39;Mean: &#39;, np.mean(swing_state[&#39;dem_share&#39;]))<br>print(&#39;Median: &#39;,np.median(swing_state[&#39;dem_share&#39;]))</pre><pre>Mean:  43.76441441441444<br>Median:  43.185</pre><pre>np.percentile(swing_state[&#39;dem_share&#39;], [25,50,75])<br>array([37.3025, 43.185 , 49.925 ])</pre><p>The Box plot was invented by John Tukey to display some of the statistical features of the data set based on percentiles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*4oeMkB1TvYn1UoT0SmtvHQ.png" /></figure><p>Here we look at the box plot for percent of the vote for Obama for different states.</p><ul><li>The center of boxes are shown the <strong>median</strong>: 50th</li><li>The edges of the boxes are shown the<strong> 25th and 75th </strong>percentile</li><li>The total height of the box contains 50% of the data and it is called interquartile range or <strong>IQR</strong></li><li>The whiskers extend the distance of 1.5 times IQR to the extent a distance of the data.</li><li>All points outside of the whiskers are called outliers.</li></ul><p><em>Let’s plot ECDF with the percentile points on it.</em></p><pre>x = np.sort(swing_state[&#39;dem_share&#39;])<br>y = np.arange(1, len(x) +1) /len(x)<br>percentiles = np.array([2.5, 25, 50, 75, 97.5])</pre><pre>_ = plt.plot(x,y, marker =&#39;.&#39;, linestyle=&#39;none&#39;)<br>plt.xlabel(&#39;percent of vote for Obama&#39;)<br>plt.ylabel(&#39;ECDF&#39;)</pre><pre>_ = plt.plot(per_vers_x, percentiles/100, marker=&#39;D&#39;, color=&#39;red&#39;, linestyle =&#39;none&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*xSWOWqNHzGmG57D6S6zC1A.png" /></figure><h4>Variance and standard deviation</h4><p><strong>Variance:</strong> is intended to describe the spread of the data. The variance is calculated as the average of the squared distance from the mean in python with numpy we can calculate the variance n<em>p.var()</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/155/1*3yUbp4D0UuJEjerD9wa23A.png" /></figure><p><em>xi−μ</em> is called deviation from mean so the variance is the mean squared deviation. The square root of the variance, σ, is called the <strong>standard deviation.</strong> Standard deviation (σ)is a reasonable metric for the spread of the data and calculated with <em>np.std()</em></p><pre>print(&#39;Variance: &#39;, np.var(swing_state[&#39;dem_share&#39;]))<br>print(&#39;Standart deviation: &#39;, np.std(swing_state[&#39;dem_share&#39;]))</pre><pre>Variance:  114.24649492735986<br>Standart deviation:  10.68861520157592</pre><p>To see how the standard deviation affects the distribution. Let’s plot the normal distribution also known as Gaussian distribution to see how different standard deviations affect the distributions with same mean value.</p><pre>#Draw 100,000 samples from a Normal distribution <br>#First samplehas a mean of 20 and a standard deviation of 1<br>sample_std1  =  np.random.normal(20, 1,   size=100000)<br>#Second has standard deviations of 3 <br>sample_std3  =  np.random.normal(20, 3,   size=100000)<br>#Third has standard deviations of 10<br>sample_std10 =  np.random.normal(20, 10,  size=100000)</pre><pre>#Plot a histograms of each of the samples; for each, use 100 bins<br>_ = plt.hist(sample_std1,  density=True, histtype=&#39;step&#39;, bins=100)<br>_ = plt.hist(sample_std3,  density=True, histtype=&#39;step&#39;, bins=100)<br>_ = plt.hist(sample_std10, density=True, histtype=&#39;step&#39;, bins=100)</pre><pre>_ = plt.legend((&#39;std = 1&#39;, &#39;std = 3&#39;, &#39;std = 10&#39;))<br>_ = plt.title(&quot;The normal distribution&quot;)<br>plt.ylim(-0.01, 0.42)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*6wqdtnTxyMt3M-Bn6arVAw.png" /></figure><h4>Covariance, and Pearson Correlation Coefficient</h4><p><strong>Covariance</strong> is a measure of the tendency of two variables to vary together. If we have two series,<em> X</em> and<em> Y,</em> their deviations from the mean are</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/132/1*UBS11rf21Ztzkv5yqQ5gXw.png" /></figure><p>where <em>μx</em> is the mean of <em>X</em> and <em>μy</em> is the mean of <em>Y</em>. If <em>X</em> and <em>Y</em> vary together, their deviations tend to have the same sign.</p><p>If we multiply them together, the product is <em>positive</em> when the deviations have the same sign and <em>negative</em> when they have the opposite sign. So adding up the products gives a measure of the tendency to vary together.</p><p><em>Covariance is the mean of these products:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/1*xn_d3c5yZXeS1QyxglEFxA.png" /></figure><p>where <em>n</em> is the length of the two series (they have to be the same length).</p><p><strong><em>We are going to make scatter plot for the percent of votes for Obama versus the total number of votes in each county.</em></strong></p><pre>mean_of_dem_share = np.mean(swing_state[&#39;dem_share&#39;])<br>mean_of_total_vote =np.mean(swing_state[&#39;total_votes&#39;])/1000</pre><pre>_ = plt.plot(swing_state[&#39;total_votes&#39;]/1000, swing_state[&#39;dem_share&#39;], marker=&#39;.&#39;,<br>            linestyle=&#39;none&#39;)<br>#drawing the mean of total votes<br>_ = plt.axvline(x=mean_of_total_vote, ymin=0, ymax= max(swing_state[&#39;total_votes&#39;]),<br>                color=&#39;red&#39;, zorder=1, alpha=0.8 )<br>_ = plt.text(480,45,&#39;Mean of percent for Obama&#39;, color=&#39;r&#39;)<br>#draw tha mean of percent of votes for Obama<br>_ = plt.axhline(y=mean_of_dem_share, xmin=0, xmax= max(swing_state[&#39;dem_share&#39;]),<br>                color=&#39;red&#39;, zorder=1, alpha=0.8)<br>_ = plt.text(100, 10, &#39;Mean of total votes&#39;, color=&#39;r&#39;)</pre><pre>#distance from mean<br>_ = plt.vlines(x=220, ymin=44, ymax=65., color=&#39;g&#39;)<br>_ = plt.hlines(y=65, xmin=85, xmax=220, color=&#39;b&#39;)</pre><pre>_ = plt.text(100, 70, &#39;distance from mean of total votes&#39;, color=&#39;b&#39;)<br>_ = plt.text(205,60,&#39;distance from mean of percent for Obama&#39;, color=&#39;g&#39;)<br>#_ =plt.axline()<br>#data point</pre><pre>_ = plt.xlabel(&#39;Total Votes (thousands)&#39;)<br>_ = plt.ylabel(&#39;Percent of Votes for Obama &#39;)</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*czYGAieSLi00a9FxIKkwhg.png" /></figure><p><em>if you look at the data point that we point out</em>: Covariance is the mean of the product of differences which it calculates using the distance from a mean of percent for Obama and distance from a mean of total votes.</p><p><strong>Positively Correlated:</strong> If <em>x</em> and <em>y</em> both tend to be above, or both below their respective means together then covariance is positive</p><p><strong>Negatively Correlated:</strong> If x is high while y is low then covariance is negative or anti-correlated.</p><p>If we want to have a more generally applicable measure of how two variables depend on each other, we want to be dimensionless. We can divide the covariance by standard deviation (σ) of x and y variables.</p><p><strong>Pearson’s correlation ( </strong><em>ρ</em><strong> ):</strong> Pearson’s correlation is always between <em>−1 </em>and <em>+1</em> (including both). The magnitude indicates the strength of the correlation. If the correlation is equal to the <em>1</em> means that two variables are perfectly correlated. The same is true if the correlation is equal to the <em>−1</em>means that the variables are negatively correlated, but for purposes of prediction, a negative correlation is just as good as a positive one. So if the correlation is equal to the 0, does that mean there is no relationship between the variables? Unfortunately, Pearson’s correlation only measures linear relationships.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/119/1*W6cB9MtcKxnQHaCyEJvE5A.png" /></figure><p>The covariance may be computed using the Numpy function np.cov(). For example, we have two sets of data<em> x</em> and <em>y,</em> np.cov(x, y) returns a 2D array where entries [0,1] and [1,0] are the covariances. Entry [0,0] is the variance of the data in x, and entry [1,1] is the variance of the data in y. This 2D output array is called the covariance matrix since it organizes the self- and covariance.</p><pre>Covariance_matrix = np.cov(swing_state[&#39;dem_share&#39;], swing_state[&#39;total_votes&#39;])<br>print(&#39;Covariance matrix between percent of vote for Obama and total votes is\n&#39;, Covariance_matrix)</pre><pre>Covariance matrix between percent of vote for Obama and total votes is<br> [[1.14763447e+02 8.17309362e+05]<br> [8.17309362e+05 2.02451039e+10]]</pre><pre># let&#39;s compare variance x from var and covariance matrix<br>print(&#39;1: Variance of X from np.var():&#39;, np.var(swing_state[&#39;dem_share&#39;]))<br>print(&#39;2: Variance of X from covariance matrix&#39;, Covariance_matrix[0,0])</pre><pre>1: Variance of y from np.var(): 20153909774.448013<br>2: Variance of y from covariance matrix 20245103936.323345</pre><pre>pearson_coefficient = np.corrcoef(swing_state[&#39;dem_share&#39;], swing_state[&#39;total_votes&#39;])<br>print(pearson_coefficient[0,1])</pre><pre>0.536197364958678</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fk53IkiREZ8FTW%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fk53IkiREZ8FTW%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fk53IkiREZ8FTW%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="266" frameborder="0" scrolling="no"><a href="https://medium.com/media/906f8096b48fc440dfcf1bb83d1412ce/href">https://medium.com/media/906f8096b48fc440dfcf1bb83d1412ce/href</a></iframe><h4>Final Thought</h4><p>The statistical analysis is more detailed and using the solve more complex problem. We just write a basic concept of a statistic. This term we mentioned in this article any data analytic should know. I will continue to write about statistical analysis.</p><p>You may find this study in my<a href="https://github.com/aysbt/DataCamp/blob/master/Statistical_Thinking_in_Python_course_1.ipynb"> githup</a> account as part of Datacamp repository.</p><p>I have written this article to improve my data analytic skills so I am still a learner. Please let me know any additional information or comment on this article.</p><p>Follow me on<a href="https://twitter.com/aaysbt"> Twitter</a>, <a href="http://linkedin/">Linkedin</a> or in <a href="https://medium.com/@aaysbt">Medium.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94545216198c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/my-data-camp-journey/brief-introduction-to-statistical-analysis-using-python-94545216198c">Brief Introduction to Statistical Analysis using Python</a> was originally published in <a href="https://medium.com/my-data-camp-journey">My Data Science Journey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Preprocessing Data for Logistic Regression]]></title>
            <link>https://medium.com/my-data-camp-journey/preprocessing-data-for-logistic-regression-f311c937d765?source=rss-c4b9afb95bfa------2</link>
            <guid isPermaLink="false">https://medium.com/p/f311c937d765</guid>
            <category><![CDATA[data-processing]]></category>
            <category><![CDATA[absenteeism]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Ayşe Bat]]></dc:creator>
            <pubDate>Fri, 01 Mar 2019 09:20:04 GMT</pubDate>
            <atom:updated>2019-03-01T09:20:04.917Z</atom:updated>
            <content:encoded><![CDATA[<p>As far as I understood, preprocessing the data is an important part of data analysis. In this article, I will show how to prepare the data for logistic regression using absenteeism data which is show the absenteeism at the company during work hour.</p><p>We’ll look at predicting absenteeism from work. More precisely we would like to know whether or not an employee can be expected to be missing for a specific number of hours in a given workday. Having such information in advance can improve our decision making.</p><p>We want to know for how many working hours an employee could be away from work based on information such as how far they live from their workplace. How many children and pets they have. Do they have higher education and so on. But firstly, We are going to prepare our data for logistic regression.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FgmeJRdWDgQ3mw%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FgmeJRdWDgQ3mw%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FgmeJRdWDgQ3mw%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="289" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb806fbc824041d9d895ea7b0432e518/href">https://medium.com/media/cb806fbc824041d9d895ea7b0432e518/href</a></iframe><h4>Data Preposeccsing</h4><pre>#import the pandas module<br>import pandas as pd<br>#load the data<br>df = pd.read_csv(‘data/Absenteeism-data.csv’)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*Yt8lO_umThvjqi1nGsXnMg.png" /><figcaption>Absenteeism from work dataset</figcaption></figure><pre>df.info()<br>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 700 entries, 0 to 699<br>Data columns (total 12 columns):<br>ID                           700 non-null int64<br>Reason for Absence           700 non-null int64<br>Date                         700 non-null object<br>Transportation Expense       700 non-null int64<br>Distance to Work             700 non-null int64<br>Age                          700 non-null int64<br>Daily Work Load Average      700 non-null float64<br>Body Mass Index              700 non-null int64<br>Education                    700 non-null int64<br>Children                     700 non-null int64<br>Pets                         700 non-null int64<br>Absenteeism Time in Hours    700 non-null int64<br>dtypes: float64(1), int64(10), object(1)<br>memory usage: 65.7+ KB</pre><ul><li><strong>The ID </strong>is the individual identification for each person and doesn’t have any numeric information. The Id column does not have any value for predicting the absenteeism hour from the work. So, we can drop the ID column from the data frame.</li></ul><pre>df = df.drop([&#39;ID&#39;], axis = 1)</pre><ul><li><strong>The Reason for Absence:</strong></li></ul><pre>#Let’s extract a list containing distinct values from reason for absence<br>df[‘Reason for Absence’].unique()</pre><pre>array([26,  0, 23,  7, 22, 19,  1, 11, 14, 21, 10, 13, 28, 18, 25, 24,  6, 27, 17,  8, 12,  5,  9, 15,  4,  3,  2, 16])</pre><p>How can we extract some meaning from these numeric values? Similarly to the case of the ID column, the values here do not actually have a numeric meaning they represent categories that are equally meaningful. So, we can turn these values into dummy variables which are an explanatory binary variable that equals 1 if a certain categorical effect is present and equals 0 is not.</p><pre>reason_columns =pd.get_dummies(df[&#39;Reason for Absence&#39;])<br>reason_columns.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*zXeMia61UMGzqQ_2pPldYw.png" /></figure><p>If we add all these dummy variables in the df data frame we would end up with a dataset containing nearly 40 columns. So, we could reorganize a certain type of variables into groups</p><ul><li>Group 1: Related to various diseases.</li><li>Group 2: Related to pregnancy and giving birth.</li><li>Group 3: Related to poisoning or signs not elsewhere categorized.</li><li>Group 4: Represents light reasons for absence such as a dental appointment physiotherapy a medical consultation and other.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*td8NbBOeFyJQ91L_vkBA3w.png" /><figcaption>Grouping the reason for an absence</figcaption></figure><pre>#max() function here  substitute an entire row in new single one column<br>reason_type_1 = reason_columns.loc[:, 1:14].max(axis=1)<br>reason_type_2 = reason_columns.loc[:, 15:17].max(axis=1)<br>reason_type_3 = reason_columns.loc[:, 18:21].max(axis=1)<br>reason_type_4 = reason_columns.loc[:, 22:].max(axis=1)   ## from 22 to end of data frame</pre><pre>#Let’s concant all reason’s<br>df_reason = pd.concat([reason_type_1, reason_type_2,reason_type_3,reason_type_4], axis=1)<br>#create the varible with column name<br>reason_column_name = [‘Reason_1’,’Reason_2&#39;,’Reason_3&#39;, ‘Reason_4’]<br>#Rename the column<br>df_reason.columns = reason_column_name<br>df_reason.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*FGDwE0A-uojvddMBib_Nuw.png" /></figure><p>We still have the reason for absence column in df. We need to add all those dummy variables to our current df. But, we could observe duplicate information calling multicore linearity which is something we should be avoided in general. Therefore in our case, we could drop the reason for absence column from the df data frame. Then concatenate the data frames.</p><pre>df  = df.drop([&#39;Reason for Absence&#39;], axis = 1)<br>df = pd.concat([df_reason, df], axis=1)</pre><ul><li><strong>Date</strong> values have been stored as text what we will do now is introduce a data type called timestamp. We will convert the strings from the date column into timestamps with the help of the format parameter.</li></ul><pre>df[&#39;Date&#39;] =pd.to_datetime(df[&#39;Date&#39;], format=&#39;%d/%m/%Y&#39;)</pre><p>We will create the<strong> Month Value</strong> and <strong>Day of the Week</strong> column from the Date column.</p><pre>list_months =[]<br>for i in range(df.shape[0]):   #df.shape[0] takes the row from the df dataframe<br>    list_months.append(df[&#39;Date&#39;][i].month)<br>df[&#39;Month Value&#39;] =list_months</pre><pre>#then we create the function to implement it to all values from the column of interest.<br>def date_to_week(data_value):<br>    return data_value.weekday()<br>df[&#39;Day of the Week&#39;] = df[&#39;Date&#39;].apply(date_to_week)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*a37DrCu7SJx8V5GrN_20sg.png" /></figure><ul><li>Education column contains only the values 1, 2, 3, and 4. <br>1: higher degree <br>2: graduate<br>3: postgraduate<br>4: master or a doctor</li></ul><p>Let’s use panda’s value_counts method to see the values from the education column how may times countered.</p><pre>df[&#39;Education&#39;].value_counts()<br>1    583<br>3     73<br>2     40<br>4      4<br>Name: Education, dtype: int64</pre><p>We can see that nearly 600 people from high school education only while just above one hundred have a better degree than that. Therefore separating between graduate postgraduate and doctor degrees becomes less relevant for this study and it would make sense to combine these in a single category.</p><p>1 -&gt; 0 higher degree <br>2 -&gt; 1 graduate<br>3 -&gt; 1 postgraduate<br>4 - &gt;1 master ora doctor</p><pre>df[&#39;Education&#39;] = df[&#39;Education&#39;].map({1:0, 2:1, 3:1, 4:1})<br>df[&#39;Education&#39;].unique()<br> array([0, 1])</pre><pre>df[&#39;Education&#39;].value_counts()<br> 0    583<br> 1    117<br> Name: Education, dtype: int64</pre><p>The transportation expense, distance to work, age, daily work Load, body mass index columns won’t manipulate in any way. They will be left without a change.</p><p>As the last step, we should save our preprocessed file into .csv for machine learning study.</p><pre>df_preprocessed.to_csv(‘data/absenteeism_preprocessed.csv’, index=False)</pre><h4>Final Thought</h4><p>You may find this study in the<a href="https://www.udemy.com/python-sql-tableau-integrating-python-sql-and-tableau/learn/v4/overview"> Udemy course</a> with more detail and also check my<a href="https://github.com/aysbt/DataScienceCourse"> githup</a> for preprocessing part.</p><p>I have written this article to improve my data analytic skills so I am still a learner. Please let me know any additional information or comment on this article.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F12js4kjVoX8Chq%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F12js4kjVoX8Chq%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F12js4kjVoX8Chq%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea56fbf7c99bc2989ebffffb17366816/href">https://medium.com/media/ea56fbf7c99bc2989ebffffb17366816/href</a></iframe><p>Follow me on<a href="https://twitter.com/aaysbt"> Twitter</a>, <a href="http://linkedin/">Linkedin</a> or in <a href="https://medium.com/@aaysbt">Medium.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f311c937d765" width="1" height="1" alt=""><hr><p><a href="https://medium.com/my-data-camp-journey/preprocessing-data-for-logistic-regression-f311c937d765">Preprocessing Data for Logistic Regression</a> was originally published in <a href="https://medium.com/my-data-camp-journey">My Data Science Journey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>