<?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 Isak Kabir on Medium]]></title>
        <description><![CDATA[Stories by Isak Kabir on Medium]]></description>
        <link>https://medium.com/@kabir-isak?source=rss-d6209d17d3f9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*tb7p9YQroqL7Kzz5JLc_JQ.jpeg</url>
            <title>Stories by Isak Kabir on Medium</title>
            <link>https://medium.com/@kabir-isak?source=rss-d6209d17d3f9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 02:24:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kabir-isak/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[Ways to Make Change Management Easier]]></title>
            <link>https://medium.com/analytics-vidhya/ways-to-make-change-management-easier-fd8b4899089c?source=rss-d6209d17d3f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd8b4899089c</guid>
            <category><![CDATA[change-management]]></category>
            <dc:creator><![CDATA[Isak Kabir]]></dc:creator>
            <pubDate>Sun, 06 Aug 2023 19:46:06 GMT</pubDate>
            <atom:updated>2023-08-21T10:43:37.468Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*qDjvbO4fGQcylcIN" /><figcaption><a href="https://medium.com/u/2053395ac335">Unsplash</a></figcaption></figure><h3>What</h3><p>Change management involves the principles of providing individuals with the necessary tools and offering assistance to ensure their successful embrace of changes, all aimed at enhancing organisational achievements and results. Understanding how change management works will transform the way you coordinate multiple departments and agendas within the organisation.</p><h3><strong>How</strong></h3><p>Prosci has a 3 phase process based on:</p><ol><li><strong>Prepare Approach</strong>: Define Success, Define Impact, Define Approach</li><li><strong>Manage Change</strong>: Plan and Act, Track Performance, Adapt Actions</li><li><strong>Sustain Outcomes</strong>: Review Performance, Activate Sustainment, Transfer Ownership.</li></ol><p><strong>The first phase</strong> in the Prosci Methodology helps teams clearly define success of the project, impacts of the change and the overall approach to the change management strategy. The essence is to define what the future would look like. Without a clear and compelling vision for the change, employees may struggle to understand why the change is necessary and how it aligns with the organisations goals.</p><ul><li>What are we trying to achieve?</li><li>What impact does the change have on the organisation?</li><li>What will it take to achieve the success?</li></ul><p><strong>The second phase</strong> of the Prosci 3-Phase Process involves developing a specific plan to get to the defined future, such as the sponsor plan and communications plan, executing activities, and tracking outcomes and performance</p><ul><li>What will we do to prepare and support people?</li><li>How are we performing?</li><li>What adjustments and actions do we need to make?</li></ul><p><strong>The third phase</strong> focuses on sustain the change over time, including reviewing performance, identifying gaps and opportunities for improvement, preparing key roles, transferring responsibility</p><ul><li>Are we performing according to plan?</li><li>What is needed to ensure the change sticks?</li><li>Who will assume ownership and sustain outcomes?</li></ul><blockquote>Change management is hard, because there is no easy recipe. Here are some few advice on what makes it easier:</blockquote><h3><strong>Establishing a trustful partnership</strong></h3><p>Establishing a strong bond and cultivating trust between the client and the agencyis important. This foundation equips the team to navigate forthcoming challenges more smoothly, as a shared sense of unity emerges between the partners. Furthermore, gaining people’s trust simplifies the process of leading and encourages receptiveness to your guidance, advice, and strategic input.</p><h3>Establishing the expectation of accountability and ownership</h3><p>Running workshops and 1–1s with multiple people to manage their expectations. Formulating plans, devising schedules, defining deadlines, and implementing progress reviews — these organisational techniques hold significance. However, their effectiveness hinges greatly on active participation and timely fulfilment of responsibilities by individuals, emphasising the pivotal role of accountability.</p><p>Hence, the initial allocation of resources and the establishment of accountability play a vital role in the success of the project — setting up what you need, when you need it, and from whom you’re getting it.</p><h3>Establishing a proactive culture and always anticipating</h3><p>On occasion, it becomes necessary to incorporate minor intermediary steps within a process to proactively address potential obstacles and risks. Proactively addressing risks helps prevent obstacles from derailing the change initiative. For instance, conducting a preliminary presentation to an executive to secure their support and ease any concerns before a larger meeting.</p><p>Ultimately, this approach revolves around proactiveness and staying one step ahead. It contributes to a smoother navigation through challenging transitions. We constantly contemplate inquiries such as: “How can we enhance this process? What actions will enhance buy-in?</p><h3>Designate Change Champions</h3><p>Designate change agents and champions within the organisation to drive and support the change effort. These individuals can help influence and guide their peers through the transition. They can identify potential sources of resistance and develop strategies to mitigate them. Listen to concerns and involve employees in finding solutions.</p><h3>In Summary</h3><p>A successful change management strategy includes:</p><ol><li>Defining what great looks like, the vision</li><li>Defining the approach</li><li>Defining how change will impact the organisation</li><li>Defining measures so the team can see progress and create ownership</li><li>Acknowledge achievements, to foster a culture of recognizing progress.</li><li>Conveying the details of the change, both at the individual and team levels</li><li>Engaging individuals who might not be directly involved but are important in the transformation phase</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd8b4899089c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/ways-to-make-change-management-easier-fd8b4899089c">Ways to Make Change Management Easier</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pitfalls within Agile Data Science Project]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://kabir-isak.medium.com/pitfalls-within-agile-data-science-project-90b3d5cb819f?source=rss-d6209d17d3f9------2"><img src="https://cdn-images-1.medium.com/max/1000/0*x1azDcwDfWvhYSzh" width="1000"></a></p><p class="medium-feed-snippet">There are plenty of reasons why a data science project can fail such as: selection bias, target leakage, data drift, overfitting and more&#x2026;</p><p class="medium-feed-link"><a href="https://kabir-isak.medium.com/pitfalls-within-agile-data-science-project-90b3d5cb819f?source=rss-d6209d17d3f9------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://kabir-isak.medium.com/pitfalls-within-agile-data-science-project-90b3d5cb819f?source=rss-d6209d17d3f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/90b3d5cb819f</guid>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Isak Kabir]]></dc:creator>
            <pubDate>Sat, 04 Jun 2022 09:18:04 GMT</pubDate>
            <atom:updated>2022-06-20T11:30:14.071Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Risk-Based Customer Segmentation within Banking]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/ibm-data-ai/risk-based-customer-segmentation-within-banking-6109b1104f20?source=rss-d6209d17d3f9------2"><img src="https://cdn-images-1.medium.com/max/2070/1*XboZUy1dlqOsYmwxRwREuw.png" width="2070"></a></p><p class="medium-feed-snippet">Introduction</p><p class="medium-feed-link"><a href="https://medium.com/ibm-data-ai/risk-based-customer-segmentation-within-banking-6109b1104f20?source=rss-d6209d17d3f9------2">Continue reading on IBM Data Science in Practice »</a></p></div>]]></description>
            <link>https://medium.com/ibm-data-ai/risk-based-customer-segmentation-within-banking-6109b1104f20?source=rss-d6209d17d3f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/6109b1104f20</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[banking]]></category>
            <category><![CDATA[data-science-tutorial]]></category>
            <category><![CDATA[customer-segmentation]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Isak Kabir]]></dc:creator>
            <pubDate>Tue, 14 Dec 2021 20:10:28 GMT</pubDate>
            <atom:updated>2021-12-28T22:23:05.971Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[I Have Built a Recommender System — So What?]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/analytics-vidhya/i-have-built-a-recommender-system-so-what-ef702c009308?source=rss-d6209d17d3f9------2"><img src="https://cdn-images-1.medium.com/max/2600/1*ifsMoNldCdSbyJbJSmvNsA.png" width="2664"></a></p><p class="medium-feed-snippet">Introduction</p><p class="medium-feed-link"><a href="https://medium.com/analytics-vidhya/i-have-built-a-recommender-system-so-what-ef702c009308?source=rss-d6209d17d3f9------2">Continue reading on Analytics Vidhya »</a></p></div>]]></description>
            <link>https://medium.com/analytics-vidhya/i-have-built-a-recommender-system-so-what-ef702c009308?source=rss-d6209d17d3f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef702c009308</guid>
            <category><![CDATA[recommendations]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[business-strategy]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Isak Kabir]]></dc:creator>
            <pubDate>Tue, 29 Dec 2020 22:53:45 GMT</pubDate>
            <atom:updated>2021-01-02T22:18:47.274Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Customer Segmentation with Clustering Algorithms]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://kabir-isak.medium.com/customer-segmentation-with-clustering-algorithms-dde2530227d8?source=rss-d6209d17d3f9------2"><img src="https://cdn-images-1.medium.com/max/1000/0*cvF_S5zjOT7y3KYt" width="1000"></a></p><p class="medium-feed-snippet">Introduction to Clustering</p><p class="medium-feed-link"><a href="https://kabir-isak.medium.com/customer-segmentation-with-clustering-algorithms-dde2530227d8?source=rss-d6209d17d3f9------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://kabir-isak.medium.com/customer-segmentation-with-clustering-algorithms-dde2530227d8?source=rss-d6209d17d3f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/dde2530227d8</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Isak Kabir]]></dc:creator>
            <pubDate>Tue, 01 Dec 2020 09:52:43 GMT</pubDate>
            <atom:updated>2020-12-02T11:57:00.301Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[How to conduct A/B Testing?]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/data-science/how-to-conduct-a-b-testing-3076074a8458?source=rss-d6209d17d3f9------2"><img src="https://cdn-images-1.medium.com/max/1784/1*aPUSwnuyUsxF_ACHuxiDlA.png" width="1784"></a></p><p class="medium-feed-snippet">The idea of A/B testing is to present different content to different variants (user groups), gather their reactions and user behaviour and&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/data-science/how-to-conduct-a-b-testing-3076074a8458?source=rss-d6209d17d3f9------2">Continue reading on TDS Archive »</a></p></div>]]></description>
            <link>https://medium.com/data-science/how-to-conduct-a-b-testing-3076074a8458?source=rss-d6209d17d3f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/3076074a8458</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[ab-test]]></category>
            <dc:creator><![CDATA[Isak Kabir]]></dc:creator>
            <pubDate>Wed, 05 Aug 2020 09:49:43 GMT</pubDate>
            <atom:updated>2020-11-21T21:28:11.913Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Customer Churn Prediction within Music Streaming using PySpark]]></title>
            <link>https://medium.com/data-science/customer-churn-prediction-within-music-streaming-using-pyspark-a96edd4beae8?source=rss-d6209d17d3f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/a96edd4beae8</guid>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Isak Kabir]]></dc:creator>
            <pubDate>Mon, 20 Jul 2020 21:41:39 GMT</pubDate>
            <atom:updated>2020-07-27T19:02:22.481Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fDKTpMwyWBiKMPZ_uO3QVw.jpeg" /><figcaption><a href="https://medium.com/u/2053395ac335">Unsplash</a> Photo by <a href="https://unsplash.com/photos/IJthre6PHHQ">Cezar Sampaio</a></figcaption></figure><p>It is key for a music streaming business <strong>to identify users that are likely to churn, i.e. users who are at risk of downgrading from premium and free subscription to cancelling the service.</strong> If a music streaming business accurately identifies such users in advance, they can offer them discounts or other similar incentives and save millions in revenues. It is a well-known fact that it is more expensive to acquire a new customer than it is to retain an existing one. This is because returning customers will likely spend <a href="http://www2.bain.com/Images/Value_online_customer_loyalty_you_capture.pdf">67% more</a> on your company’s products and services.</p><h3>1.1 Project Overview</h3><p>We want to <strong><em>identify the users that could potentially cancel their account and leave the service</em></strong>. Our goal in this project was to help a fictional business (similar to Spotify and Pandora) by building and training a binary classifier that is able to accurately identify users who cancelled the music streaming service, based on the patterns obtained from their past activity and interaction with the service.</p><ul><li>Define churn variable: <strong>1</strong> — users who cancelled their subscription within the observation period, and <strong>0</strong> — users who kept the service throughout</li></ul><p>Due to the size of the data-set, the project was carried out by leveraging Apache Spark distributed cluster-computing framework capabilities, using Python API for Spark, PySpark.</p><h3>1.2 Load Data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aWslnulJfqOWjoSIDKwLBA.png" /></figure><pre><strong># import libraries</strong></pre><pre>from pyspark import SparkContext, SparkConf<br>from pyspark.sql import SparkSession<br>from pyspark.sql import Window<br>from pyspark.sql.functions import udf, col, concat, count, lit, avg, lag, first, last, when<br>from pyspark.sql.functions import min as Fmin, max as Fmax, sum as Fsum, round as Fround<br>from pyspark.sql.types import IntegerType, DateType, TimestampType</pre><pre>from pyspark.ml import Pipeline<br>from pyspark.ml.feature import VectorAssembler, Normalizer, StandardScaler<br>from pyspark.ml.regression import LinearRegression<br>from pyspark.ml.classification import LogisticRegression, RandomForestClassifier, GBTClassifier<br>from pyspark.ml.clustering import KMeans<br>from pyspark.ml.tuning import CrossValidator, ParamGridBuilder<br>from pyspark.ml.evaluation import BinaryClassificationEvaluator,</pre><pre><strong># create a Spark session</strong><br>spark = SparkSession \<br>.builder \<br>.appName(‘CustomerChurn’) \<br>.getOrCreate()</pre><pre><strong># Check Spark configuration</strong><br>spark.sparkContext.getConf().getAll()</pre><pre>path = &quot;mini_sparkify_event_data.json&quot;<br>df = spark.read.json(path)</pre><h3>2. Data Understanding</h3><p>The data-set contains user activity logs recorded between October 1, 2018 and December 01, 2018. The full data-set consists of approximately 26 million rows/logs, whereas the subset contains 286 500 rows. The full data-set collects logs of 22 277 different users, whereas the subset only covers the activities of 225 users. The subset dataset contains 58 300 Free users and 228 000 Paid users. Both data-sets have 18 columns, as listed below.</p><pre>root<br> |-- artist: string (nullable = true)<br> |-- auth: string (nullable = true)<br> |-- firstName: string (nullable = true)<br> |-- gender: string (nullable = true)<br> |-- itemInSession: long (nullable = true)<br> |-- lastName: string (nullable = true)<br> |-- length: double (nullable = true)<br> |-- level: string (nullable = true)<br> |-- location: string (nullable = true)<br> |-- method: string (nullable = true)<br> |-- page: string (nullable = true)<br> |-- registration: long (nullable = true)<br> |-- sessionId: long (nullable = true)<br> |-- song: string (nullable = true)<br> |-- status: long (nullable = true)<br> |-- ts: long (nullable = true)<br> |-- userAgent: string (nullable = true)<br> |-- userId: string (nullable = true)</pre><p>Every activity log belongs to a specific user. Seven columns in the data-set represent static <strong>user-level information</strong> (fixed for all logs belonging to a specific user):</p><p><strong>artist: </strong>artist that the user was listening to<br><strong>userId</strong>: user identifier;<br><strong>sessionId:<em> </em></strong>a unique ID that identifies a single continuous period of use by a user of the service. Multiple users can have sessions labelled with the same sessionId<br><strong>firstName</strong>: user’s first name<br><strong>lastName</strong>: user’s last name<br><strong>gender</strong>: user’s gender; 2 categories (<em>M</em> and <em>F</em>)<br><strong>location</strong>: user’s location<br><strong>userAgent</strong>: agent used by the user to access the streaming service; 57 different categories<br><strong>registration</strong>: user’s registration timestamp<br><strong>level</strong> (non-static): subscription level; 2 categories (<em>free</em> and <em>paid</em>)<br><strong>page:</strong> what page was the user visiting when this event got generated. The different types of pages are detailed in the section below</p><p>The <strong>page</strong> column contains logs for all the page a user has visited in the app.</p><pre>&gt;&gt;&gt; df.select(&#39;page&#39;).distinct().show(10)<br>+--------------------+<br>|                page|<br>+--------------------+<br>|              Cancel|<br>|    Submit Downgrade|<br>|         Thumbs Down|<br>|                Home|<br>|           Downgrade|<br>|         Roll Advert|<br>|              Logout|<br>|       Save Settings|<br>|Cancellation Conf...|<br>|               About|<br>+--------------------</pre><p>Based on the analysis performed it seems that the maximum time between two consecutive logs that still belong to the same session is one hour.</p><pre># Explore the auth column<br>df.groupby(&#39;auth&#39;).count().show()</pre><pre>+----------+------+<br>|      auth| count|<br>+----------+------+<br>|Logged Out|  8249|<br>| Cancelled|    52|<br>|     Guest|    97|<br>| Logged In|278102|<br>+----------+------+</pre><p>We can also see that users are quite active, one of the top users has listed to about 8000 songs in total. The graphs below indicates that churned users are usually from California and New Jersey, mostly paid subscribers are leaving the Music app and more men than women tend to cancel their subscription. California and New York states tend to be denser in population, and therefore could expect higher numbers of churn and higher in overall engagement. It is easy to see from the plot below that the provided Sparkify data-set is a case of an <strong>imbalanced dataset</strong>, as the share of churned users is only a bit more than 20% (52) compared to 174.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*phRpSXH1Qbbn6w_mF3oVFg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*-Nzou86RwOzrrPjLIu1l7g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nxeJdbys_M3Ue5JMk12yjQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_7yksD5S3QGtXDPy35R9UQ.png" /><figcaption>Categorical features (lastlevel 0-free, 1-paid; gender 0-male, 1-female)</figcaption></figure><h3>3. Feature Engineering</h3><p>First, we had to transform the original data-set (one row per log) to a data-set with user-level information or statistics (<strong>one row per user</strong>). We achieved this by performing several mapping (e.g. obtaining user’s gender, length of observation period, etc.) and aggregation steps.</p><h3>3.1 Transformations</h3><p>For the few users who registered after October 1 the registration times are not consistent with the actual log timestamps and activity types. We thus had to identify late registrations by finding <em>Submit Registration </em>logs in the <em>page</em> column. This step was not trivial as such log events are not mapped to any <em>userId</em> so those had to be extracted from the <em>sessionId</em> information.</p><p>For the few users who registered late the observation start was then set to the timestamp of their first log, whereas for all other users the default October 1 was used.</p><pre># Lag the page column<br>windowsession = Window.partitionBy(&#39;sessionId&#39;).orderBy(&#39;ts&#39;)<br>df = df.withColumn(&quot;lagged_page&quot;, lag(df.page).over(windowsession))</pre><pre>windowuser = Window.partitionBy(&#39;userId&#39;).orderBy(&#39;ts&#39;).rangeBetween(Window.unboundedPreceding, Window.unboundedFollowing)</pre><pre># Identify users that registered after the start of observation, and infer the start date accordingly<br>df = df.withColumn(&quot;beforefirstlog&quot;, first(col(&#39;lagged_page&#39;)).over(windowuser))<br>df = df.withColumn(&quot;firstlogtime&quot;, first(col(&#39;ts&#39;)).over(windowuser))<br>df = df.withColumn(&quot;obsstart&quot;, <br>                   when(df.beforefirstlog == &quot;Submit Registration&quot;, df.firstlogtime).otherwise(obs_start_default))</pre><pre># For each log compute the time from the beginning of observation...<br>df = df.withColumn(&quot;timefromstart&quot;, col(&#39;ts&#39;)-col(&quot;obsstart&quot;))<br># ...and time before the end of observation<br>df = df.withColumn(&quot;timebeforeend&quot;, col(&#39;obsend&#39;)-col(&#39;ts&#39;))</pre><p>Similar to above, there are <em>users who cancelled their service before the end of the default observation period</em>, the so-called churned users. For each such user the end of the respective observation period has been set to the timestamp of his/her last log entry, whereas for all other users the default 1st of December.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zcqmvUau_An0wur7QdCJUQ.png" /></figure><h3>3.2 Feature Engineering — aggregated statistics</h3><p>The newly created <strong>user-level data-set </strong>includes the following columns:</p><p><strong>lastlevel</strong>: user’s last subscription level, transformed into binary format (1 — paid tier, 0 — free tier)<br><strong>gender</strong>:<em> </em>gender, transformed into binary format (1 — female, 0 — male)<br><strong>obsstart, obsend</strong>: start and end of user-specific observation period</p><p><strong>endstate</strong>: user’s last interaction in the observation period<br><strong>nact</strong>: user’s total number of interactions in the observation period<br><strong>nsongs, ntbup, ntbdown, nfriend, nplaylist, ndgrade, nupgrade, nhome, nadvert, nhelp, nsettings, nerror</strong>: number of songs played, thumbs up given, thumbs down given, friends added, songs added to playlist, downgrades, upgrades, home page visits, advertisements played, help page visits, settings visits, errors, <em>respectively</em></p><p><strong>nact_recent, nact_oldest:<em> </em></strong>user’s activity in the last and first <em>k</em> days of the observation window,<em> respectively<br></em><strong>nsongs_recent, nsongs_oldest</strong>: songs played in the last and first <em>k</em> days of the observation window, <em>respectively</em></p><pre># Aggregation by userId<br>df_user = df.groupby(‘userId’)\<br>.agg(<br> # User-level features<br> first(when(col(‘lastlevel’) == ‘paid’, 1).otherwise(0)).<br>alias(‘lastlevel’),<br> first(when(col(‘gender’) == “F”, 1).otherwise(0)).alias(‘gender’),<br> first(col(‘obsstart’)).alias(‘obsstart’),<br> first(col(‘obsend’)).alias(‘obsend’),<br> first(col(‘endstate’)).alias(‘endstate’),<br> <br> # Aggregated activity statistics<br> count(col(‘page’)).alias(‘nact’),<br>Fsum(when(col(‘page’) == “NextSong”, 1).otherwise(0)).alias(“nsongs”),<br> Fsum(when(col(‘page’) == “Thumbs Up”, 1).otherwise(0)).alias(“ntbup”),<br> Fsum(when(col(‘page’) == “Thumbs Down”, 1).otherwise(0)).alias(“ntbdown”),<br> Fsum(when(col(‘page’) == “Add Friend”, 1).otherwise(0)).alias(“nfriend”),<br> Fsum(when(col(‘page’) == “Add to Playlist”, 1).otherwise(0)).alias(“nplaylist”), <br> Fsum(when(col(‘page’) == “Submit Downgrade”, 1).otherwise(0)).alias(“ndgrade”),<br> Fsum(when(col(‘page’) == “Submit Upgrade”, 1).otherwise(0)).alias(“nugrade”),<br> Fsum(when(col(‘page’) == “Home”, 1).otherwise(0)).alias(“nhome”),<br> Fsum(when(col(‘page’) == “Roll Advert”, 1).otherwise(0)).alias(“nadvert”),<br> Fsum(when(col(‘page’) == “Help”, 1).otherwise(0)).alias(“nhelp”),<br> Fsum(when(col(‘page’) == “Settings”, 1).otherwise(0)).alias(“nsettings”),<br> Fsum(when(col(‘page’) == “Error”, 1).otherwise(0)).alias(“nerror”),<br> <br> # Aggregated activity statistics in different periods <br> Fsum(when(col(‘timebeforeend’) &lt; trend_est, 1).otherwise(0)).alias(“nact_recent”),<br> Fsum(when(col(‘timefromstart’) &lt; trend_est, 1).otherwise(0)).alias(“nact_oldest”),<br> Fsum(when((col(‘page’) == “NextSong”) &amp; (col(‘timebeforeend’) &lt; trend_est), 1).otherwise(0)).alias(“nsongs_recent”),<br> Fsum(when((col(‘page’) == “NextSong”) &amp; (col(‘timefromstart’) &lt; trend_est), 1).otherwise(0)).alias(“nsongs_oldest”) )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GOF01-Xp3zfEQ4nbrQlD_g.png" /></figure><h4><strong>Aggregated Activity Statistics</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ixr6z_9chIkfFf1pPH4mJA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RFswC2XDhk8E4Gke8rhHAg.png" /></figure><h3>4. Exploratory Data Analysis</h3><p>After completing the feature engineering step we have analysed the correlations between the built features.</p><pre># For visualization purposes we switch to pandas dataframes<br>df_user_pd = df_user.toPandas()</pre><pre># Calculate correlations between numerical features<br>cormat = df_user_pd[[&#39;nact_perh&#39;,&#39;nsongs_perh&#39;, &#39;nhome_perh&#39;, &#39;ntbup_perh&#39;,&#39;ntbdown_perh&#39;, &#39;nfriend_perh&#39;,&#39;nplaylist_perh&#39;, <br>&#39;nadvert_perh&#39;, &#39;nerror_perh&#39;, &#39;upgradedowngrade&#39;, &#39;songratio&#39;, &#39;positiveratio&#39;,&#39;negativeratio&#39;, <br>&#39;updownratio&#39;, &#39;trend_act&#39;, &#39;trend_songs&#39;, &#39;avgsessionitems&#39;,  &#39;avgsessionlength&#39;,&#39;avgsongs&#39;]].corr()</pre><pre># Plot correlations<br>plt.rcParams[&#39;figure.figsize&#39;] = (10,10)<br>plt.subplots_adjust(left=0.20, right=0.9, top=0.95, bottom=0.15)<br>sns.heatmap(cormat, cmap = &quot;YlGnBu&quot;, square = True, vmin = -1, vmax = 1);<br>plt.title(&#39;Feature correlations&#39;);<br>plt.savefig(&#39;correlations.png&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I0y9heYIzWUptuHGCXTfEg.png" /></figure><p>The heat-map above describes a high correlation between variables <strong>nact_perh</strong> and <strong>nsongs_perh.</strong> This is expected, as listening to songs is obviously by far the most common user activity. For the same reason there is a high correlation between <strong>trend_act</strong> and <strong>trend_songs</strong>. In both cases we decided to simply remove from all further analyses and keep only variables that measure the most important interaction — playing songs.</p><p>In order to further reduce the multi-colinearity in the data, we also decided not to use <strong>nhome_perh</strong> and <strong>nplaylist_perh</strong> in the model. Moreover, <strong>avgsessionlength</strong> is highly correlated with average items in each session, hence it can be ignored too.</p><h3>4.1 Relationship with the churned variable</h3><p>From the visualisations presented below the following observations have been made:</p><ul><li>on average churned users played more songs per hour;</li><li>churned users gave significantly more thumbs down per hour, and had to watch more advertisements on average;</li><li>the ratio of songs and positive interactions relative to total activity was typically lower for churned users</li><li>churned users had on average less interactions per session</li><li>churn rate is higher for users in the free subscription plan</li><li>churn rate is slightly higher for male users</li></ul><p>No features have been removed based on this analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*238C4VPVTDvd5H0A9mfNkQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6FJ5JHr3aI3yYwyN_lH3aQ.png" /></figure><h3>4. Modelling and Evaluation</h3><p>We first performed grid search with cross validation to test the performance of several parameter combinations, all on the user-level data obtained from the smaller Sparkify user activity data-set. Based on the performance results obtained in cross validation (measured by AUC and F1 score), we identified the best-performing model instances and retrained them on the entire training set.</p><h3>4.1 Grid Search Approach</h3><h4>Logistic Regression</h4><ul><li><strong><em>maxIter</em></strong> (maximum number of iterations, default=100) : <strong>[10, 30]</strong></li><li><strong><em>regParam</em></strong> (regularization parameter, default=0.0) : <strong>[0.0, 0.1]</strong></li><li><strong><em>elasticNetParam</em></strong> (mixing parameter — 0 for L2 penalty, 1 for L1 penalty, default=0.0) : <strong>[0.0, 0.5]</strong></li></ul><h4><strong>Random Forest Classifier</strong></h4><ul><li><strong><em>maxDepth</em></strong> (maximum tree depth, default=5) : <strong>[4, 5, 6, 7]</strong></li><li><strong><em>numTrees</em></strong> (number of trees, default=20) : <strong>[20, 40]</strong></li></ul><h4><strong>Gradient-Boosted Tree Classifier</strong></h4><ul><li><strong><em>maxDepth</em></strong> (maximum tree depth, default=5) : <strong>[4, 5]</strong></li><li><strong><em>maxIter</em></strong> (maximum number of iterations, default=20) : <strong>[20, 100]</strong></li></ul><p>In the defined grid search objects the performance of each parameter combination is by default measured by average <strong>AUC</strong> score (area under the ROC) obtained in <strong>4-fold cross validation</strong>. AUC is briefly explained in Section 4.4 below.</p><pre>numeric_columns = [‘nsongs_perh’, ‘ntbup_perh’,’ntbdown_perh’, ‘nfriend_perh’, <br>‘nadvert_perh’, ‘nerror_perh’, ‘upgradedowngrade’, ‘songratio’, ‘positiveratio’,’negativeratio’, <br>‘updownratio’, ‘trend_songs’, ‘avgsessionitems’,’avgsongs’]</pre><pre># Combining multiple numerical features using VectorAssembler<br>numeric_assembler = VectorAssembler(inputCols = numeric_columns, outputCol = “numericvectorized”)</pre><pre># Standardizing numerical features<br>scaler = StandardScaler(inputCol = “numericvectorized”, outputCol = “numericscaled”, withStd = True, withMean = True)</pre><pre># Adding the two binary features<br>binary_columns = [‘lastlevel’, ‘gender’]<br>total_assembler = VectorAssembler(inputCols = binary_columns + [“numericscaled”], outputCol = “features”)</pre><pre># Defining three different pipelines with three different classifiers, all with default parameters<br># Logistic regression <br>lr = LogisticRegression()<br>pipeline_lr = Pipeline(stages = [numeric_assembler, scaler, total_assembler, lr])</pre><pre># Random forest classifier<br>rf = RandomForestClassifier()<br>pipeline_rf = Pipeline(stages = [numeric_assembler, scaler, total_assembler, rf])</pre><pre># Gradient-boosted tree classifier<br>gb = GBTClassifier()<br>pipeline_gb = Pipeline(stages = [numeric_assembler, scaler, total_assembler, gb])</pre><h3>4.2 Performance Metrics</h3><p><strong>F1 score</strong> is preferred performance metrics to this problem. The input user-level data-set is imbalanced. Music streaming service aims to identify most of the users that are likely to churn (<strong>aiming for high recall</strong>), but at the same time does not want to give too many discounts for no reason (<strong>aiming for high precision</strong>), i.e. to users who are actually happy with the service (false positives) — this can help music streaming business prevent financial losses.</p><pre>class F1score(Evaluator):<br>def __init__(self, predictionCol = “prediction”, labelCol=”label”):<br> self.predictionCol = predictionCol<br> self.labelCol = labelCol</pre><pre>def _evaluate(self, dataset):<br> <br> # Calculate F1 score <br> tp = dataset.where((dataset.label == 1) &amp; (dataset.prediction == 1)).count()<br> fp = dataset.where((dataset.label == 0) &amp; (dataset.prediction == 1)).count()<br> tn = dataset.where((dataset.label == 0) &amp; (dataset.prediction == 0)).count()<br> fn = dataset.where((dataset.label == 1) &amp; (dataset.prediction == 0)).count()<br> <br> # Add epsilon to prevent division by zero<br> precision = tp / (tp + fp + 0.00001)<br> recall = tp / (tp + fn + 0.00001)<br> <br> f1 = 2 * precision * recall / (precision + recall + 0.00001)<br> <br> return f1</pre><pre>def isLargerBetter(self):<br> return True</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HvQyAhPQYgY0gjOOGeaY1w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*R3S2ulRC7sy40Tze5Hyq3g.png" /><figcaption>Testing on full dataset</figcaption></figure><p>The best performing model has AUC score of 0.981 and F1 score of 0.855.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eu_RJ5U1M22TMuu7QIHwOQ.png" /></figure><p>As seen in the visualisation above, the most important feature for identifying churned users is the <strong>nerror_perh</strong> which measures how many error pages have been shown to the user per hour. The more errors a user has to experience the more likely it is that he/she is dissatisfied with the service.</p><p>Similar holds also for the second and third most important feature, <strong>ntbdown_perh</strong> and <strong>nadvert_perh</strong> which measure the number of thumbs down given per hour and number of advertisements seen per hour, respectively.</p><p>Most interesting feature is the <strong>trend_songs</strong> variable which measures a user’s song listening activity trend, as the fourth most important.</p><h3>5. Conclusions and improvements</h3><p>The Gradient-boosted tree classifier has a F1 score (precision and recall) of 0.855 and can identify churned users based on past user activity and interaction with the music streaming service, which can help the business prevent from severe financial losses.</p><p>Some improvements are to perform <strong>comprehensive grid search</strong> for the model on the full Sparkify data-set. <strong>Utilise song-level features</strong> that have been ignored so far, e.g. calculate the user’s listening diversity in terms of different songs/artists listened to in the specified observation period, etc. <strong>Build new features </strong>such as e.g. average length of song listening sessions, ratios of skipped or partially listened songs, etc.</p><p>For more details about this project, see the link to my Github available <a href="https://github.com/isakkabir/isakkabir-Customer-Churn-Prediction-Music-Streaming/blob/master/CustomerChurn_cluster.ipynb">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a96edd4beae8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/customer-churn-prediction-within-music-streaming-using-pyspark-a96edd4beae8">Customer Churn Prediction within Music Streaming using PySpark</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top 8 Books to Study Data Science and Machine Learning in 2020]]></title>
            <link>https://medium.com/data-science/top-10-books-to-study-data-science-and-machine-learning-in-2020-483a8c9279b1?source=rss-d6209d17d3f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/483a8c9279b1</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Isak Kabir]]></dc:creator>
            <pubDate>Mon, 06 Jul 2020 18:47:42 GMT</pubDate>
            <atom:updated>2020-07-17T11:22:24.903Z</atom:updated>
            <content:encoded><![CDATA[<p>This article covers some of the most popular books on Data Science and is to assist newcomers in exploring the world of data science and experienced practitioners to get deeper knowledge. Below is a list of the top 8 that I have found useful or been recommended.</p><p>The following books will give you knowledge and understanding of important areas of data science such as <strong>Statistics, Data Science, Machine Learning, Deep Learning and Deployment</strong>.</p><h3>Introductory Level</h3><h3>1. An Introduction to Statistical Learning</h3><p>by Gareth James, Daniela Witten, Trevor Hastie, and Robert Tibshirani</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*W8_V9ZY7lm-eiWkQ0EWHVA.png" /></figure><p>This book is very <strong>beginner-friendly </strong>with a lot of illustrations and real-world scenarios which it combines for an easy to comprehend machine-learning lesson. The strength of the book lies in explaining key concepts. I can highly recommend this to Python developers also. Widely used in University courses.</p><h3>2. Practical Statistics for Data Scientists</h3><p>by Peter Bruce</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/0*TSyICtoC1dqJ5m1s.png" /></figure><p>This is a comprehensive reference guide for many of the concepts in statistics for data science. It’s a good book to <strong>bridge the gap between statistics and data science</strong>. Although the book assumes familiarity with R, it’s still a good book to learn statistical concepts for Python programmers.</p><h3>3. <strong>Data Science and Big Data Analytics: Discovering, Analyzing, Visualizing and Presenting Data</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*MaUBMv3bGIWzczFuilH1Fw.png" /></figure><p>This book introduces<strong> big data and covering data analytics lifecycle</strong>. Its Easy-to-read and it clears all the concepts which otherwise one may struggle to find elsewhere. Advanced analytics using <strong>MapReduce, Hadoop, and SQL</strong> are also introduced to the reader.</p><h3>4. Good Charts, Tips Tools and Exercises for Making Better Data Visualizations</h3><p>by Scott Berinato</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*WpHiJ5Xdu9QJt0AIqoPdqA.png" /></figure><p>In this book, you will learn how to choose the best <strong>chart that fits your data</strong>; the most effective way to communicate with decision makers when you have five minutes of their time; how to use colour effectively.</p><h3>Intermediate Level</h3><h3>5. Python Data Science Handbook</h3><p>by Jake VanderPlas</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*R3L_I989_6Dw7YzUeidMMg.png" /></figure><p>Python Data Science Handbook is a great guide through all standard Python libraries as well: NumPy, pandas, Matplotlib, Scikit-learn. It’s perfect for someone who has experience with Python but needs a guide on the tools available for Data Science work.</p><h3>Expert Level</h3><p>If you are on an expert level, then I would recommend reading scientific papers.</p><h3>6. Machine Learning A Probablistic Perspective</h3><p>by Kevin P. Murphy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*7R7ChKSyKpHiCSv8ZQBJjA.png" /></figure><p>If you’re into <strong>mathematics</strong>, then you’ll like this book and is very useful as a reference in machine learning research.</p><h3>7. Machine learning yearning</h3><p>by Andrew Ng</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*KVt3tn2iamzbd7bF0HQALA.png" /></figure><p>This book is designed to teach data scientists <strong>how to structure Machine Learning projects</strong>, and set direction for a data science team. It is a good overview of when and how to use Machine Learning, and how to handle the complexities involved in implementing AI in the real world.</p><h3>8. Data Science in Production; Building Scalable Model Pipelines with Python</h3><p>by Ben G Weber</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*W0qwT-Tvybp4t2GrRAYsOw.png" /></figure><p>The book covers <strong>cloud deployment</strong>, <strong>developing web end points</strong> and <strong>machine learning models. </strong>Weber teaches from a top-down approach: build reproducible models that can scale well in production. Between <strong>PySpark</strong>, <strong>Pub/Sub</strong> techniques, and <strong>Kafka</strong>, Weber deeps dive into essential data science tools.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=483a8c9279b1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/top-10-books-to-study-data-science-and-machine-learning-in-2020-483a8c9279b1">Top 8 Books to Study Data Science and Machine Learning in 2020</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Whom Should Starbucks Send Offerings To? — A Predictive Analysis on Customer Behaviour]]></title>
            <link>https://medium.com/data-science/whom-should-starbucks-send-offerings-to-a-predictive-analysis-on-customer-behaviour-ce82fc87a8a0?source=rss-d6209d17d3f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce82fc87a8a0</guid>
            <category><![CDATA[predictiveanalysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[starbucks]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <dc:creator><![CDATA[Isak Kabir]]></dc:creator>
            <pubDate>Wed, 03 Jun 2020 01:43:34 GMT</pubDate>
            <atom:updated>2020-06-06T20:58:12.444Z</atom:updated>
            <content:encoded><![CDATA[<h3>Whom Should Starbucks Send Offerings To?</h3><h3>A Predictive Analysis of Customer Behaviour</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DLOHXBYrUb6QhkXwSVIyVw.jpeg" /><figcaption>@<a href="https://medium.com/u/bf780c58fb40">Unsplash</a></figcaption></figure><h3>Business Understanding</h3><p>Once every few days, Starbucks sends out an offer to users of the mobile app. An offer can be merely an advertisement for a drink or an actual offer such as a <strong>discount</strong>, <strong>BOGO (buy one get one free)</strong> or just an <strong>informational offer</strong> which includes the product information. Some users might not receive any offers during certain weeks. In this way, Starbucks can probably increase the possibility that the customer opens the offer after they receive it and eventually finish the transaction. Starbucks wants to analyse customer behaviour and understand which type of customers opens the offer and finish the transactions?</p><h4>Problem Statement</h4><p>We are interested to answer the following two questions:</p><p>1. Which offer should be sent to a particular customer to let the customer buy more?<br>2. Are there any common characteristics of the customers who take the offer?</p><h3>Problem Solving Approach</h3><ul><li><strong>Data Exploring</strong> and <strong>Data Visualisation </strong>each of the portfolio, profile and transaction data.</li><li><strong>Pre-processing</strong> <em>(cleaning &amp; transformation) </em>the data and <em>feature engineering </em>to form a combined master dataset</li><li>Applying <strong>Data Analysis</strong> on the cleaned pre-processed data</li><li><strong>Scaling</strong> the numerical features.</li><li>Using <strong>Supervised Learning Models</strong> to understand which customers are influenced by the offering. The trained classification models would classify the customers into target classes (1 if a customer would respond or 0 if a customer would not respond)</li><li><strong>Evaluating</strong> the models using accuracy, f-beta score, training time. Accuracy and precision are common metrics within classification problem. The evaluation will showcase the accuracy (ratio of correct predictions out of total number of prediction). Select best performing model based on the metric and training time.</li><li><strong>Model tuning</strong> using GridSearchCV to find the best hyperparameters (in order to improve the performance of the selected model).</li><li>Calculate the <strong>Feature Importances</strong> given by best estimator of the trained model.</li><li>Compute the <strong>performance of best model </strong>on test set.</li></ul><h3>Dataset Description</h3><p>The data is contained in three files:</p><ul><li><strong>portfolio.json</strong> — containing offer ids and metadata about each offer (duration, type, etc.)</li><li><strong>profile.json</strong> — demographic data for each customer</li><li><strong>transcript.json</strong> — records for “transactions”, “offers received”, “offers viewed”, and “offers completed”</li></ul><p>Here is the schema and explanation of each variable in the files:</p><p><strong>portfolio.json</strong></p><ul><li>id (string) — offer id</li><li>offer_type (string) — the type of offer ie BOGO, discount, informational</li><li>difficulty (int) — the minimum required to spend to complete an offer</li><li>reward (int) — the reward is given for completing an offer</li><li>duration (int) — time for the offer to be open, in days</li><li>channels (list of strings)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AKcbW6EGv5-Ladz7q7MJ8w.png" /></figure><p><strong>profile.json</strong></p><ul><li>age (int) — age of the customer</li><li>became_member_on (int) — the date when customer created an app account</li><li>gender (str) — gender of the customer (note some entries contain ‘O’ for other rather than M or F)</li><li>id (str) — customer-id</li><li>income (float) — customer’s income</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X-bvCxILs26rOYmn4bJEVQ.png" /></figure><p><strong>transcript.json</strong></p><ul><li>event (str) — record description (ie transaction, offer received, offer viewed, etc.)</li><li>person (str) — customer-id</li><li>time (int) — time in hours since the start of the test. The data begins at time t=0</li><li>value — (dict of strings) — either an offer id or transaction amount depending on the record</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XCxRcWKLiwTjSqGsXDGB-A.png" /></figure><p>Starbucks wants to<strong> connect offer data, customer data and transaction data(operational data) to gain insights about customer behaviour </strong>and overall effectiveness of offers as a value for business.</p><h3>Data Exploration</h3><p><strong><em>Portfolio data description</em></strong></p><h4>Age, Income and Gender Distribution</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VsBjxmEEm3Yeal_p-nD29g.png" /></figure><p>Age distribution plot illustrates that the median age of a customer is 60 and most of the customers belong to the age range between 40 to 70. The average value of customers salary is around 60 K. The gender distribution indicates that more customers are men.</p><h4>Number of customer joined Starbucks per year and month</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qClC9wyOf3A-dSz-auJGZw.png" /></figure><p>The distribution of customers joining per years, indicates the the number of customers joining per year increased over time. The customer membership increased during later cold season especially in (August, October, December, January) which is probably correlated with that more customers have more coffee during cold weather.</p><h4>Gender distribution by membership year</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JAIIt16BmZ4lOW76O4yFuQ.png" /><figcaption>Gender: 1 (Female) ,2 (Male) and 3 (Other)</figcaption></figure><p>The above plot visualise that more men have become Starbucks member recently compared to earlier years where the membership distribution across gender has been equal.</p><h4>Customer Income Distribution</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vzR5BtPY2da-Pg2khXceSA.png" /></figure><p>Starbucks female customer have a higher average income salary compared to male customers.</p><p><strong><em>Profile data description</em></strong></p><pre><strong># </strong><em>Plot distribution of ages in profile dataframe </em>profile[‘age’].value_counts().sort_index(ascending=<strong>True</strong>).plot.bar(figsize=(20,8), fontsize=12,color=’teal’); plt.xlabel(‘Age’, fontsize=18) plt.ylabel(‘Count’, fontsize=18) plt.title(‘Distribution of age counts’, fontsize=18) plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1bd99KePxhrH3E29Loe2Dg.png" /><figcaption>Customers with age 118 seems to be an outlier, where the number of customers with age 118 is 2175, which is unrealistic and will be dropped fromt the dataframe.</figcaption></figure><pre><em>#Gender counts </em><br>profile.gender.value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s9RolBKx993sneIbWAXTow.png" /></figure><p><strong><em>Transcript data description</em></strong></p><pre><em># Calculate the percentage of unique values in event feature</em> round((transcript[‘event’].value_counts()/transcript[‘event’].value_counts().sum())*100,2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FvFHY0XA1ffxssJNjl4kAA.png" /></figure><h3>Data Preprocessing</h3><h4>Clean Portfolio Data:</h4><ul><li>Rename id col name to offer_id.</li><li>Scale and normalise columns difficulty and reward</li><li>Convert time feature from days to hours</li></ul><pre><strong># </strong><em>renaming &#39;id&#39; column to offer_id.</em> portfolio.rename(columns={&#39;id&#39;:&#39;offer_id&#39;},inplace=<strong>True</strong>)  </pre><pre><em># Initialize a scaler, then apply it to the features</em> <br>scaler = MinMaxScaler() <em># default=(0, 1)</em> </pre><pre>columns_to_scale = [&#39;difficulty&#39;,&#39;reward&#39;] portfolio[columns_to_scale] = scaler.fit_transform(portfolio[columns_to_scale])  </pre><pre><em># Convert time feature from days to hours</em> portfolio[&#39;duration_hour&#39;] = portfolio[&#39;duration&#39;]*24  </pre><pre><em># Drop duration and channels</em> portfolio.drop(columns=[&#39;duration&#39;],axis=1, inplace=<strong>True</strong>)  </pre><pre>portfolio</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QxcOchLkjsPGe0C1MgfNbQ.png" /></figure><h4>Cleaning Profile Data:</h4><ul><li>Rename id col name to customer_id.</li><li>Encode age value 118 to NaN.</li><li>Create readable date format in became_member_on column.</li><li>Drop rows with no gender, income, age data</li><li>Convert gender values to numeric 1s,2s and 3s.</li><li>Convert age and income from float to int</li><li>Add start year and start month columns</li><li>Adding a new column ‘membership_days’ ,that will present the number of days since the customer become a member</li><li>Creating a new column ‘member_type’</li></ul><pre>#rename id col name to customer_id.<br>profile.rename(columns={‘id’:’customer_id’},inplace=True)</pre><pre>#encode age value 118 to NaN<br>profile[‘age’] = profile[‘age’].apply(lambda x: np.nan if x == 118 else x)</pre><pre>#create readable date format for became_member_on column.<br>profile.became_member_on = profile[‘became_member_on’].astype(str).astype(‘datetime64[ns]’, format = “%Y%m%d”)</pre><pre># dropping rows with NaNs in ‘age’, ‘gender’ and ‘income’ columns<br>profile.dropna(inplace=True)</pre><pre>#encode gendr column<br>profile[‘gender’] = profile[‘gender’].map({‘F’: 1, ‘M’: 2, ‘O’: 3})</pre><pre>#add start_year column<br>profile[‘start_year’] = profile.became_member_on.dt.year<br>profile[“start_month”] = profile.became_member_on.dt.month</pre><pre># changing the datatype of ‘age’ and ‘income’ columns to ‘int’<br>profile[[‘age’,’income’]] = profile[[‘age’,’income’]].astype(int)</pre><pre># adding a new column ‘membership_days’ ,that will present the number of days since the customer become a member<br>profile[‘membership_days’] = datetime.now() — profile[‘became_member_on’]</pre><pre># removing the ‘days’ unit<br>profile[‘membership_days’] = profile[‘membership_days’].dt.days</pre><pre># creating a new column ‘member_type’ representing the type of the member: new, regular or loyal depending on the number of his ‘membership_days’<br>profile[‘member_type’] = pd.cut(profile[‘membership_days’], bins=[390, 1000, 1600, 2500],labels=[‘new’, ‘regular’, ‘loyal’])</pre><pre># Drop channels and offertype column<br>profile.drop(columns=[‘became_member_on’,’membership_days’ ],axis=1, inplace=True)</pre><pre># Re-arranging the columns to have ‘customer_id’ column the first column in dataset<br>profile = profile.reindex(columns=[‘customer_id’, ‘age’, ‘gender’, ‘income’, ‘start_year’, ‘start_month’, ‘member_type’])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o2svA5yzltTGB5Gta-VCBg.png" /></figure><h4>Cleaning Transcript Data:</h4><p>Iterate over value column and update offer_id, amount, reward columns with values from the list.</p><pre><strong>def</strong> cleaning_transcript(transcript):<br>    <em>&#39;&#39;&#39;</em><br><em>    data cleaning the transcript dataframe, return usable dataframe need contain offer events</em><br><em>    </em><br><em>    INPUT:</em><br><em>    transcript - the transcript dataframe to be cleaned</em><br><em>    </em><br><em>    OUTPUT:</em><br><em>    transcript - the cleaned offer dataframe</em><br><em>    </em><br><em>    &#39;&#39;&#39;</em><br>    <em>#Change name of feature person to customer_id in transcript dataframe</em><br>    transcript.rename(columns={&#39;person&#39;: &#39;customer_id&#39;}, inplace=<strong>True</strong>)<br>    <br>    transcript[&#39;offer_id&#39;] = &#39;&#39;<br>    transcript[&#39;amount&#39;] = 0<br>    transcript[&#39;reward&#39;] = 0  <br>    <em>#Iterate over value column, check it and update offer_id, amount, reward columns</em><br>    <strong>for</strong> idx, row <strong>in</strong> transcript.iterrows():<br>        <strong>for</strong> k <strong>in</strong> row[&#39;value&#39;]:<br>            <strong>if</strong> k == &#39;offer_id&#39; <strong>or</strong> k == &#39;offer id&#39;: <em># b/c &#39;offer_id&#39; and &#39;offer id&#39; are representing the same thing</em><br>                transcript.at[idx, &#39;offer_id&#39;] = row[&#39;value&#39;][k]<br>            <strong>if</strong> k == &#39;amount&#39;:<br>                transcript.at[idx, &#39;amount&#39;] = row[&#39;value&#39;][k]<br>            <strong>if</strong> k == &#39;reward&#39;:<br>                transcript.at[idx, &#39;reward&#39;] = row[&#39;value&#39;][k]<br>                <br>    <br>    <em># Drop event_transaction since they cause missing values in &#39;order id&#39; column </em><br>    transcript = transcript[transcript[&#39;event&#39;] != &#39;transaction&#39;]<br>    <em># Drop value column</em><br>    transcript.drop(columns=[&#39;value&#39;], axis = 1, inplace = <strong>True</strong>)<br><br>    <strong>return</strong> transcript</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MQFJN3YuqxgWAg0adgB10w.png" /></figure><h3>Data Exploration of Master Dataset</h3><pre><em># merge &#39;cleaning_transcript&#39; dataset with &#39;profile&#39; on &#39;offer_id&#39;</em><br>master_df = cleaning_transcript_df.merge(portfolio,how=&#39;left&#39;,on=&#39;offer_id&#39;)</pre><pre><em># join &#39;master_df&#39; dataset with &#39;portfolio&#39; on &#39;customer_id&#39;</em><br>master_df = master_df.merge(profile,how=&#39;left&#39;,on=&#39;customer_id&#39;)</pre><h4>Most popular offers to each age group are BOGO (Buy One Get One)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BUMJIh8VxFF-Ss9Mkt5dGQ.png" /></figure><h4>Female and Male customers prefer BOGO and discount offerings</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kqxc60plUZr8l7QVpW0p_g.png" /></figure><h4>Female customers where more impacted by the offerings than men</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KpeYRqOFFGBlG7r278Dy3A.png" /><figcaption><strong>Females </strong>completed around <strong>75%</strong> of the offers they viewed while men completed <strong>58%</strong> of the offers they viewed.</figcaption></figure><h4>The regular customers (3–4 years membership) completes the offerings in higher range among member types</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RqIpkE3h3hXBsHIwoxDqKQ.png" /></figure><pre>Number of offer completed by Female: 15477, 74.46% of total offers viewed.<br>Number of offer viewed by Female: 20786.<br>Number of offer completed by Males: 16461, 58.17% of total offers viewed.<br>Number of offer viewed by Males: 28297.</pre><h4>Average time spent on completing an offer is 17 days</h4><pre># excluding all events of ‘offer received’, just focus on offer viewed or offer completed<br>copy_master_df = master_df[master_df[‘event’] != ‘offer received’]<br>copy_master_df = copy_master_df[copy_master_df[‘event’] != ‘transaction’]<br>avg_time_spent_offer = copy_master_df.groupby([‘gender’, ‘offer_id’])[‘time’].mean().reset_index()</pre><pre>print(avg_time_spent_offer[avg_time_spent_offer[‘gender’] == 1][‘time’].values[0] / 24)<br>print(avg_time_spent_offer[avg_time_spent_offer[‘gender’] == 2][‘time’].values[0] / 24)</pre><pre>16.9176908752<br>16.8785739814</pre><h3>Converting categorical values to numerical values</h3><pre># OneHotEncoding feature ‘offer type’<br>master_df = pd.get_dummies(master_df, columns = [‘offer_type’], prefix= ‘’, prefix_sep=’’)<br> <br># OneHotEncoding feature ‘event’<br>master_df = pd.get_dummies(master_df, columns = [‘event’], prefix= ‘’, prefix_sep=’’)<br> <br># Change column names<br>master_df.rename(columns = {‘offer received’:’offer_received’,<br> ‘offer viewed’:’offer_viewed’,<br> ‘offer completed’:’offer_completed’}, inplace=True)<br> <br># One-hot encode channels<br>master_df[‘web’] = master_df[‘channels’].apply(lambda x: int(1) if ‘web’ in x else int(0))</pre><pre>master_df[‘email’] = master_df[‘channels’].apply(lambda x: int(1) if ‘email’ in x else int(0))</pre><pre>master_df[‘mobile’] = master_df[‘channels’].apply(lambda x: int(1) if ‘mobile’ in x else int(0))</pre><pre>master_df[‘social’] = master_df[‘channels’].apply(lambda x: int(1) if ‘social’ in x else int(0))</pre><pre># Drop channels column<br>master_df.drop(columns=[‘channels’], axis = 1, inplace = True)</pre><pre># creating a new column representing the income group to which the customer belongs </pre><pre>master_df[‘income_range’] = pd.cut(master_df[‘income’], bins=[29999, 60000, 90000, 120001],labels=[‘average’, ‘above-average’, ‘high’])</pre><pre># replacing the ‘income_range’ categorical labels by numerical labels</pre><pre>labels_income_range = master_df[‘income_range’].astype(‘category’).cat.categories.tolist()<br>replace_map_comp_income_range = {‘income_range’ : {k: v for k,v in zip(labels_income_range,list(range(1,len(labels_income_range)+1)))}}<br>master_df.replace(replace_map_comp_income_range, inplace=True)</pre><pre>#replacing the ‘member_type’ categorical labels by numerical labels</pre><pre>labels_member_type = master_df[‘member_type’].astype(‘category’).cat.categories.tolist()<br>replace_map_comp_member_type = {‘member_type’ : {k: v for k,v in zip(labels_member_type,list(range(1,len(labels_member_type)+1)))}}<br>master_df.replace(replace_map_comp_member_type, inplace=True)</pre><pre>#replacing the ‘offer_id’ categorical labels by numerical labels</pre><pre>labels_member_type = master_df[‘offer_id’].astype(‘category’).cat.categories.tolist()<br>replace_map_comp_member_type = {‘offer_id’ : {k: v for k,v in zip(labels_member_type,list(range(1,len(labels_member_type)+1)))}}<br>master_df.replace(replace_map_comp_member_type, inplace=True)</pre><pre># replacing the ‘age_group’ categorical labels by numerical labels</pre><pre>labels_age_group = master_df[‘age_group’].astype(‘category’).cat.categories.tolist()<br>replace_map_comp_age_group = {‘age_group’ : {k: v for k,v in zip(labels_age_group,list(range(1,len(labels_age_group)+1)))}}</pre><pre># replace categorical labels in ‘age_group’ column with numerical labels</pre><pre>master_df.replace(replace_map_comp_age_group, inplace=True)</pre><h3>Data Modelling</h3><p>Six different machine learning models will predict whether a customer will respond to an offer. Before building models, our dataset should be split into train and test datasets and a selection of features and target table have been chosen.</p><p><strong>Features: </strong>time_h, offer_id, amount, reward, difficulty, duration_hour, age_group, bogo, discount, informational, gender, member_type, income_range, web, email, mobile, social.</p><p><strong>Target label: </strong>offer_completed</p><pre># Split the data into features and target label</pre><pre>X = master_df[[‘time’,’offer_id’,’amount’,’reward’,’difficulty’, ’duration_hour’,’age_group’,’bogo’,’discount’,’informational’,’gender’, ‘member_type’,’income_range’,’web’,’email’,’mobile’, ‘social’]]</pre><pre>Y = master_df[‘offer_completed’]</pre><h4>Creating a Training and Predicting Pipeline</h4><ul><li>Import fbeta_score and accuracy_score from <a href="http://scikit-learn.org/stable/modules/classes.html#sklearn-metrics-metrics">sklearn.metrics</a>.</li><li>Fit the learner to the sampled training data and record the training time.</li><li>Perform predictions on the test data X_test, and also on the first 300 training points X_train[:300].</li><li>Record the total prediction time.</li><li>Calculate the accuracy score for both the training subset and testing set.</li><li>Calculate the F-score for both the training subset and testing set.</li></ul><pre># Import two metrics from sklearn - fbeta_score and accuracy_score<br>from sklearn.metrics import fbeta_score, accuracy_score</pre><pre>def train_predict(learner, sample_size, X_train, y_train, X_test, y_test): <br>    &#39;&#39;&#39;<br>    inputs:<br>       - learner: the learning algorithm to be trained and predicted on<br>       - sample_size: the size of samples (number) to be drawn from training set<br>       - X_train: features training set<br>       - y_train: income training set<br>       - X_test: features testing set<br>       - y_test: income testing set<br>    &#39;&#39;&#39;<br>    <br>    results = {}<br>    <br>    # Fit the learner to the training data using slicing with &#39;sample_size&#39; using .fit(training_features[:], training_labels[:])<br>    start = time() # Get start time<br>    learner.fit(X_train[:sample_size],y_train[:sample_size])<br>    end = time() # Get end time<br>    <br>    # Calculate the training time<br>    results[&#39;train_time&#39;] = end-start<br>        <br>    # Get the predictions on the test set(X_test),<br>    # then get predictions on the first 300 training samples(X_train) using .predict()<br>    start = time() # Get start time<br>    predictions_test = learner.predict(X_test)<br>    predictions_train = learner.predict(X_train[:300])<br>    end = time() # Get end time<br>    <br>    # Calculate the total prediction time<br>    results[&#39;pred_time&#39;] = start-end<br>            <br>    # Compute accuracy on the first 300 training samples which is y_train[:300]<br>    results[&#39;acc_train&#39;] = accuracy_score(y_train[:300],predictions_train)<br>        <br>    # Compute accuracy on test set using accuracy_score()<br>    results[&#39;acc_test&#39;] =  accuracy_score(y_test,predictions_test)<br>    <br>    # Compute F-score on the the first 300 training samples<br>    results[&#39;f_train&#39;] = fbeta_score(y_train[:300],predictions_train,beta=0.5)<br>        <br>    # Compute F-score on the test set<br>    results[&#39;f_test&#39;] = fbeta_score(y_test,predictions_test,beta=0.5)<br>       <br>    # Success<br>    print(&quot;{} trained on {} samples.&quot;.format(learner.__class__.__name__, sample_size))   <br>    # Return the results<br>    return results</pre><h4>Initial Model Evaluation</h4><ul><li>Initialize three models and store them in ‘clf_D’, ‘clf_E’, and ‘clf_F’.</li></ul><pre># Initialize the three models<br>clf_D = LogisticRegression(random_state=42) <br>clf_E = RandomForestClassifier(random_state=42)<br>clf_F = GradientBoostingClassifier(random_state=42)</pre><pre># Calculate the number of samples for 1%, 10%, and 100% of the training data<br># samples_100 is the entire training set i.e. len(y_train)<br># samples_10 is 10% of samples_100 (ensure to set the count of the values to be `int` and not `float`)<br># samples_1 is 1% of samples_100 (ensure to set the count of the values to be `int` and not `float`)<br>samples_100 = len(X_train)<br>samples_10 = int(0.1 * samples_100)<br>samples_1 = int(0.01 * samples_100)</pre><pre># Collect results on the learners<br>results = {}<br>for clf in [clf_D, clf_E, clf_F]:<br>    clf_name = clf.__class__.__name__<br>    results[clf_name] = {}<br>    for i, samples in enumerate([samples_1, samples_10, samples_100]):<br>        results[clf_name][i] = \<br>        train_predict(clf, samples, X_train, y_train, X_test, y_test)</pre><pre># Run metrics visualization for the three supervised learning models chosen<br>vs.evaluate(results, accuracy, fscore)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ONQLj4ts4J97RkKx1uXzA.png" /></figure><h3>Model tuning</h3><p>In this section we will choose the best model to use on our data, and then, perform a grid search optimisation.</p><pre># Import &#39;GridSearchCV&#39;, &#39;make_scorer&#39;, and any other necessary libraries<br>from sklearn.grid_search import GridSearchCV<br>from sklearn.metrics import make_scorer</pre><pre># Initialize the classifier<br>clf = RandomForestClassifier(random_state = 1)</pre><pre>parameters = {&#39;n_estimators&#39;: [10, 50, 80],&#39;max_depth&#39;: [None, 2, 3, 4],&#39;min_samples_split&#39;: [2,3,4],&#39;min_samples_split&#39;: [3],&#39;min_samples_leaf&#39;: [1]}</pre><pre># Make an fbeta_score scoring object using make_scorer()<br>scorer = make_scorer(fbeta_score, beta=0.5)</pre><pre># Perform grid search on the classifier using &#39;scorer&#39; as the scoring method using GridSearchCV()<br>grid_obj =  GridSearchCV(estimator=clf, param_grid=parameters, scoring=scorer, cv=None)</pre><pre># Fit the grid search object to the training data and find the optimal parameters using fit()<br>grid_fit = grid_obj.fit(X_train, y_train)</pre><pre># Get the estimator<br>best_clf = grid_fit.best_estimator_</pre><pre># Make predictions using the unoptimized and model<br>predictions = (clf.fit(X_train, y_train)).predict(X_test)<br>best_predictions = best_clf.predict(X_test)</pre><pre># Report the before-and-afterscores<br>print(&quot;Unoptimized model\n------&quot;)<br>print(&quot;Accuracy score on testing data: {:.4f}&quot;.format(accuracy_score(y_test, predictions)))<br>print(&quot;F-score on testing data: {:.4f}&quot;.format(fbeta_score(y_test, predictions, beta = 0.5)))<br>print(&quot;\nOptimized Model\n------&quot;)<br>print(&quot;Final accuracy score on the testing data: {:.4f}&quot;.format(accuracy_score(y_test, best_predictions)))<br>print(&quot;Final F-score on the testing data: {:.4f}&quot;.format(fbeta_score(y_test, best_predictions, beta = 0.5)))</pre><p>Unoptimized model<br>Accuracy score on testing data: 0.8021<br>F-score on testing data: 0.5381</p><p>Optimized Model<br>Final accuracy score on the testing data: 0.8031<br>Final F-score on the testing data: 0.5415</p><pre># Import a supervised learning model that has &#39;feature_importances_&#39;<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.ensemble import GradientBoostingClassifier</pre><pre># Train the supervised model on the training set using .fit(X_train, y_train)<br>model_rforest = RandomForestClassifier().fit(X_train, y_train)</pre><pre># Extract the feature importances<br>importances_rforest = model_rforest.feature_importances_</pre><pre># Plot<br>print(&quot;Random Forest&quot;)<br>vs.feature_plot(importances_rforest, X_train, y_train)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5lnhOHKt94R2ycvAyrkojA.png" /></figure><p>The most important factor that largely affects if the customer will complete the offering is the eventually is the length of membership (time). The longer the customer as a member of Starbucks, the more likely the customer will respond to the offer they receive. Then the second and third important factors which affect the possibility of customer’s response are age and income which very make sense. Also, the number of offers they received will also affect the response a lot.</p><pre># Prepare the dataframe of feature importances given to features by best estimator of RandomForest<br>feat_imp_df = pd.DataFrame(model_rforest.feature_importances_,\<br>                           index=X_train.columns.tolist(),\<br>                           columns=[&#39;feat_imp&#39;]).reset_index()</pre><pre>feat_imp_df.rename(columns={&#39;index&#39;: &#39;feature&#39;}, inplace=True)<br>feat_imp_df[&#39;feat_imp_perc&#39;] = np.round((feat_imp_df[&#39;feat_imp&#39;]/feat_imp_df[&#39;feat_imp&#39;].sum())*100,2)<br>feat_imp_df = feat_imp_df.sort_values(by=[&#39;feat_imp_perc&#39;], ascending=False).reset_index(drop=True)<br>feat_imp_df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*6mvbjguDvmpwDNWIIInz4w.png" /></figure><h4>Feature Selection and New Model Testing Performance</h4><pre># Import functionality for cloning a model<br>from sklearn.base import clone</pre><pre>importances = importances_ada<br># Reduce the feature space<br>X_train_reduced = X_train[X_train.columns.values[(np.argsort(importances)[::-1])[:5]]]<br>X_test_reduced = X_test[X_test.columns.values[(np.argsort(importances)[::-1])[:5]]]</pre><pre># Train on the “best” model found from grid search earlier<br>clf = (clone(best_clf)).fit(X_train_reduced, y_train)</pre><pre># Make new predictions<br>y_pred = clf.predict(X_test_reduced)</pre><pre># Report scores from the final model using both versions of data<br>print(“Final Model trained on full data\n — — — “)<br>print(“Accuracy on testing data: {:.4f}”.format(accuracy_score(y_test, best_predictions)))<br>print(“F-score on testing data: {:.4f}”.format(fbeta_score(y_test, best_predictions, beta = 0.5)))<br>print(“\nFinal Model trained on reduced data\n — — — “)<br>print(“Accuracy on testing data: {:.4f}”.format(accuracy_score(y_test, y_pred)))<br>print(“F-score on testing data: {:.4f}”.format(fbeta_score(y_test, y_pred, beta = 0.5)))</pre><p>Unoptimized model<br>Accuracy score on testing data: 0.8031<br>F-score on testing data: 0.5415</p><p>Optimized Model<br>Final accuracy score on the testing data: 0.8253<br>Final F-score on the testing data: 0.6007</p><h3>Conclusion</h3><p>The analysis showcase that a random forest model has the best training data accuracy and F1-score. The analysis suggests that the random forest model has a testing accuracy of 0.82 and an F1-score of 0.6. The main factors such as the length of membership, age and income do impact the possibility of customer’s responding to the offer.</p><blockquote>Both gender prefer BOGO and discount offerings, preferably BOGO (Buy One Get One)</blockquote><blockquote>Female customers where more impacted by the offerings than men — Females completed around 75% of the offers they viewed while men completed 58% of the offers they viewed.</blockquote><blockquote>57% of customers are Males compared to 41% Females.</blockquote><blockquote>The regular customers (3–4 years membership) completes the offerings in higher range among member types.</blockquote><blockquote>Both gender spent almost 17 days on completing an offer.</blockquote><blockquote>Most members joined during 2017. The customer membership increased during later cold season especially in (August, October, December, January) which is probably correlated with that more customers have more coffee during cold weather.</blockquote><blockquote>The machine learning model suggests to send offerings to higher income females who have been members for 3–4 in Starbucks during autumn/winter time.</blockquote><h3>Improvements</h3><p>Access to additional features would have helped providing better classification results, since we where limited to just age, gender and income for example.</p><p>Improvements can also be made on feature engineering steps to see if there are other new features to introduce and perform feature reduction methods to see how it will affect the model performance. However, feature dimension reduction is not critical in our case, since we don’t have that many feature in place.</p><p>Another improvement is to explore the impact of duration, rewards and difficulty and how they impact the offer response and purchase and create new features based on these factors.</p><p>Finally, we can improve the model by analysing the amount spent per customer using regression algorithms to answer the question how likely they are to respond to an offer, assuming that there might be a correlation between amount spent and response to an offer.</p><p>Code can be found <a href="https://github.com/isakkabir/Starbucks-Challenge/blob/master/Starbucks_Capstone_notebook.ipynb">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce82fc87a8a0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/whom-should-starbucks-send-offerings-to-a-predictive-analysis-on-customer-behaviour-ce82fc87a8a0">Whom Should Starbucks Send Offerings To? — A Predictive Analysis on Customer Behaviour</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Classifying twitter disaster response messages]]></title>
            <link>https://medium.com/analytics-vidhya/classifying-twitter-disaster-response-messages-f551e9e60c71?source=rss-d6209d17d3f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/f551e9e60c71</guid>
            <dc:creator><![CDATA[Isak Kabir]]></dc:creator>
            <pubDate>Sun, 26 Apr 2020 16:04:19 GMT</pubDate>
            <atom:updated>2020-04-27T16:26:41.879Z</atom:updated>
            <content:encoded><![CDATA[<h3>Classifying Twitter Disaster Response Messages Trough NLP</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rt-87PjMn2tWrPsrwccPuA.jpeg" /><figcaption>Woman sitting on brown concrete ground beside brown wicker basket [1]</figcaption></figure><p>We are facing a global health crisis due to COVID-19 — one that is killing people, spreading human suffering, and upending people’s lives. But this is much more than a health crisis. It is a human, economic and social crisis [2].</p><p>During a pandemic or a natural disaster, it is crucial to respond quickly to people’s needs, which are expressed in messages sent across various channels. <strong>Machine learning algorithms using NLP could help to categorise messages so that they can be sent to appropriate disaster relief agencies </strong>that takes care of medical aid, water, shelter, food, logistics etc. This article uses a data set containing real Twitter messages that were sent during disaster events provided by <a href="https://appen.com/">Figure Eight</a> to build a model for an API that classifies disaster messages.</p><p>The code was divided in three sections:</p><ul><li><strong>ETL Pipeline</strong>: Pipeline to read in data , cleans and stores it in a SQL database.The script merges the messages and categories datasets, splits the categories column into separate, converts values to binary, and drops duplicates.</li><li><strong>Machine Learning Pipeline</strong>: Transforms the data using Natural language processing, train a machine learning model using GridSearchCV, RandomForest to classify the message behind the tweet among 36 categories.</li><li><strong>Web development:</strong> Flask app and the user interface used to predict results and display them.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ht1yULJ3t0jyytkb4_3p5A.png" /></figure><h3>ETL Pipeline</h3><h4>Loading and merging data</h4><pre><strong># import libraries</strong><br>import pandas as pd<br>from sqlalchemy import create_engine</pre><pre><strong># load messages dataset</strong><br>messages = pd.read_csv(&#39;messages.csv&#39;)<br># load categories dataset<br>categories = pd.read_csv(&#39;categories.csv&#39;)<br># merge datasets<br>df = messages.merge(categories, on=&#39;id&#39;)</pre><pre><strong># Split categories into separate category columns.</strong><br># create a dataframe of the 36 individual category columns<br>categories_split = df [&#39;categories&#39;].str.split (pat = &#39;;&#39;, expand = True)<br>categories_split.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZBtNSZQbygISrfJAAhjXcw.png" /><figcaption>Merge of datasets before split categories into separate columns</figcaption></figure><h4>Data cleaning</h4><pre><strong># rename the columns of &#39;categories&#39;<br></strong><em># select the first row of the categories dataframe</em><br>row = categories_split.iloc [0]<br><em># use this row to extract a list of new column names for categories.</em><br>category_colnames = row.apply (<strong>lambda</strong> x: x.rstrip (&#39;- 0 1&#39;))<br>categories_split.columns = category_colnames</pre><pre><strong># convert category values to 0 and 1 </strong><br><strong>for</strong> column <strong>in</strong> categories_split:<br>    <em># set each value to be the last character of the string</em><br>    categories_split[column] = categories_split[column].str [-1]<br>    <em># convert column from string to numeric</em><br>    categories_split[column] = pd.to_numeric(categories_split[column], errors = &#39;coerce&#39;)</pre><pre><strong><em># drop the original categories column from `df`</em></strong><br>df.drop ([&#39;categories&#39;], axis = 1, inplace = <strong>True</strong>)</pre><pre><strong><em># concatenate the original dataframe with the new `categories` dataframe</em></strong><br>df = pd.concat([df,categories_split], axis = 1, sort = <strong>False</strong>)</pre><pre><strong><em># drop duplicates</em></strong><br>df.drop_duplicates(inplace=<strong>True</strong>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ClLODjRrL1tuMwobsb1PA.png" /></figure><h4>Save dataframe in SQL database</h4><pre>engine = create_engine(‘sqlite:///InsertDatabaseName.db’) df.to_sql(‘InsertTableName’, engine, index=<strong>False</strong>)</pre><h3><strong>Machine Learning Pipeline</strong></h3><h4>Import libraries and load data from database.</h4><pre><em># import libraries</em><br><strong>import</strong> <strong>nltk</strong><br>nltk.download(&#39;punkt&#39;)<br>nltk.download(&#39;wordnet&#39;)<br>nltk.download(&#39;stopwords&#39;)<br><strong>import</strong> <strong>pandas</strong> <strong>as</strong> <strong>pd</strong><br><strong>from</strong> <strong>sqlalchemy</strong> <strong>import</strong> create_engine<br><strong>from</strong> <strong>sklearn.pipeline</strong> <strong>import</strong> Pipeline, FeatureUnion<br><strong>from</strong> <strong>sklearn.feature_extraction.text</strong> <strong>import</strong> CountVectorizer, TfidfTransformer<br><strong>from</strong> <strong>sklearn</strong> <strong>import</strong> multioutput<br><strong>from</strong> <strong>nltk.tokenize</strong> <strong>import</strong> word_tokenize<br><strong>from</strong> <strong>nltk.stem.porter</strong> <strong>import</strong> PorterStemmer<br><strong>from</strong> <strong>nltk.stem.wordnet</strong> <strong>import</strong> WordNetLemmatizer<br><strong>from</strong> <strong>sklearn.feature_extraction.text</strong> <strong>import</strong> TfidfVectorizer<br><strong>from</strong> <strong>nltk.corpus</strong> <strong>import</strong> stopwords<br><strong>from</strong> <strong>sklearn.ensemble</strong> <strong>import</strong> RandomForestClassifier,AdaBoostClassifier<br><strong>from</strong> <strong>sklearn.model_selection</strong> <strong>import</strong> train_test_split<br><strong>from</strong> <strong>sklearn.metrics</strong> <strong>import</strong> precision_recall_fscore_support<br><strong>import</strong> <strong>re</strong><br><strong>from</strong> <strong>sklearn.metrics</strong> <strong>import</strong> fbeta_score, make_scorer<br><strong>from</strong> <strong>sklearn.model_selection</strong> <strong>import</strong> GridSearchCV<br><strong>import</strong> <strong>pickle</strong></pre><h4>Tokenization function to process text data</h4><pre><strong>def</strong> tokenize(text):<br>    <em>#normalize text</em><br>    text = re.sub(r&quot;[^a-zA-Z0-9]&quot;, &quot; &quot;, text.lower())<br>    <br>    <em># stopword list </em><br>    stop_words = stopwords.words(&quot;english&quot;)<br>    <br>    <em>#tokenize</em><br>    words = word_tokenize(text)<br>    <br>    <em>#stemming</em><br>    stemmed = [PorterStemmer().stem(w) <strong>for</strong> w <strong>in</strong> words]<br>    <br>    <em>#lemmatizing</em><br>    words_lemmed = [WordNetLemmatizer().lemmatize(w) <strong>for</strong> w <strong>in</strong> stemmed <strong>if</strong> w <strong>not</strong> <strong>in</strong> stop_words]<br>   <br>    <strong>return</strong> words_lemmed</pre><p><strong>Build a machine learning pipeline</strong></p><p>This ML pipeline should take message as input and output classification results on 36 categories.</p><pre>pipeline = Pipeline([<br>        (&#39;vect&#39;, CountVectorizer(tokenizer=tokenize)),<br>        (&#39;tfidf&#39;, TfidfTransformer()),<br>        (&#39;clf&#39;, multioutput.MultiOutputClassifier (RandomForestClassifier()))<br>        ])</pre><h3>Train pipeline</h3><p>Split data into train and test sets and train pipeline</p><pre>X_train, X_test, y_train, y_test = train_test_split(X, y, X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 22)<br><em># train classifier</em><br>new_pipeline.fit(X_train, y_train)</pre><h3>Test your model</h3><p>Report the f1 score, precision and recall for each output category of the dataset. You can do this by iterating through the columns and calling sklearn’s classification_report on each.</p><pre>y_pred = new_pipeline.predict(X_test)<br><em># Get results and add them to a dataframe.</em><br><strong>def</strong> get_results(y_test, y_pred):<br>    results = pd.DataFrame(columns=[&#39;Category&#39;, &#39;f_score&#39;, &#39;precision&#39;, &#39;recall&#39;])<br>    num = 0<br>    <strong>for</strong> cat <strong>in</strong> y_test.columns:<br>        precision, recall, f_score, support = precision_recall_fscore_support(y_test[cat], y_pred[:,num], average=&#39;weighted&#39;)<br>        results.set_value(num+1, &#39;Category&#39;, cat)<br>        results.set_value(num+1, &#39;f_score&#39;, f_score)<br>        results.set_value(num+1, &#39;precision&#39;, precision)<br>        results.set_value(num+1, &#39;recall&#39;, recall)<br>        num += 1<br>    print(&#39;Aggregated f_score:&#39;, results[&#39;f_score&#39;].mean())<br>    print(&#39;Aggregated precision:&#39;, results[&#39;precision&#39;].mean())<br>    print(&#39;Aggregated recall:&#39;, results[&#39;recall&#39;].mean())<br>    <strong>return</strong> results<br>#---------------------------------------------------------</pre><pre>y_pred_tuned_ada = new_pipeline.predict(X_test)<br>results_tuned = get_results(y_test, y_pred_tuned_ada)<br>results_tuned</pre><p>Aggregated f_score: 0.940272096531 <br>Aggregated precision: 0.94022097111 <br>Aggregated recall: 0.947979181501</p><p>Code can be found in this <a href="https://github.com/isakkabir/Disaster-Response-ML-Pipeline">repository</a></p><p>References:</p><ol><li><a href="https://unsplash.com/photos/iZ2v4FwtMLc">https://unsplash.com/photos/iZ2v4FwtMLc</a></li><li><a href="https://www.un.org/development/desa/dspd/2020/04/social-impact-of-covid-19/">https://www.un.org/development/desa/dspd/2020/04/social-impact-of-covid-19/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f551e9e60c71" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/classifying-twitter-disaster-response-messages-f551e9e60c71">Classifying twitter disaster response messages</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>