<?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 Nesreen Sada on Medium]]></title>
        <description><![CDATA[Stories by Nesreen Sada on Medium]]></description>
        <link>https://medium.com/@nesreensada?source=rss-debc18e6a446------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*UJjr4mQp5_FbyT9UyZ1gCg.jpeg</url>
            <title>Stories by Nesreen Sada on Medium</title>
            <link>https://medium.com/@nesreensada?source=rss-debc18e6a446------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 17:41:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nesreensada/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[How to Setup Pyflink on Amazon EMR]]></title>
            <link>https://medium.com/analytics-vidhya/how-to-setup-pyflink-on-amazon-emr-bb466fbcfc6e?source=rss-debc18e6a446------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb466fbcfc6e</guid>
            <category><![CDATA[amazon-emr]]></category>
            <category><![CDATA[apache-flink]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Nesreen Sada]]></dc:creator>
            <pubDate>Fri, 10 Jul 2020 06:08:17 GMT</pubDate>
            <atom:updated>2020-07-28T08:24:17.569Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kw8u3n4-Uwk2K-ONZG78fw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*x5gN2gSUG48tOJlfuu15hw.png" /></figure><h3>What is Flink?</h3><p>Apache Flink is an open-source distributed stream-processing framework developed by Apache. The core of Flink is built on Java and Scala. Recently, Flink gained popularity over other streaming frameworks such as Spark, Samza, and Storm.</p><h4><strong>The main features of Flink:</strong></h4><ul><li>High throughput and low latency(milliseconds) which makes it ideal for stream processing.</li><li>Provides job scheduling, resource assignments, parallel processing, and reliability.</li><li>It is distributed and can scale horizontally.</li><li>In-memory computations.</li><li>Flink is a pure stream computing engine with a unified stream and batch processing capabilities.</li><li>Provides data-source and sink connectors to systems such as <a href="https://en.wikipedia.org/wiki/Amazon_Web_Services#Analytics">Amazon Kinesis</a>, <a href="https://en.wikipedia.org/wiki/Apache_Kafka">Apache Kafka</a>, <a href="https://en.wikipedia.org/wiki/Alluxio">Alluxio</a>, <a href="https://en.wikipedia.org/wiki/HDFS">HDFS</a>, <a href="https://en.wikipedia.org/wiki/Apache_Cassandra">Apache Cassandra</a>, and <a href="https://en.wikipedia.org/wiki/Elasticsearch">ElasticSearch</a>.</li><li>Flink is the most active open-source project in 2019 according to objective statistics of ASF.</li></ul><h4><strong>What programming languages does Flink support?</strong></h4><p>Flink natively supports Java and Scala But It also supports Python.</p><h3>Why PyFlink Is Necessary?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fSRUElyaQcQjsXFg-cG3Cg.png" /></figure><p>Pyflink is simply a combination of Apache Flink with python. This combination allows us to make use of all the computing capabilities of python on Flink and all the features of Flink can be used on python. Additionally, PyFlink provides support for Python user-defined functions to enable you to register and use these functions in Table APIs and SQL</p><h4><strong>Why Flink and python</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DO6ywVzrSdXka-u6bJmYWg.png" /></figure><ul><li>The number of python users for data analysis and machine learning applications has increased in the last few years.</li><li>The availability of Flink features Python users, will enable running Python’s analysis and computing functions on Flink to improve Python’s ability to resolve big data issues.</li></ul><h3><strong>Flink Installation</strong></h3><p>So, we have two options to install Flink on AWS. Either we use an Amazon EC2 instance, download the dependencies or make use of the pre-existent installation using EMR to download Flink. The latter is the <strong>recommended</strong> approach to run Flink on AWS.</p><h4>Why Use Amazon EMR?</h4><p><em>Here’s the description provided by Amazon for the EMR service:</em></p><blockquote>Amazon EMR is the industry-leading cloud big data platform for processing vast amounts of data using open source tools such as <a href="https://aws.amazon.com/emr/features/spark/">Apache Spark</a>, <a href="https://aws.amazon.com/emr/features/hive/">Apache Hive</a>, <a href="https://aws.amazon.com/emr/features/hbase/">Apache HBase</a>, <a href="https://aws.amazon.com/blogs/big-data/use-apache-flink-on-amazon-emr/">Apache Flink</a>, <a href="https://aws.amazon.com/emr/features/hudi/">Apache Hudi</a>, and <a href="https://aws.amazon.com/emr/features/presto/">Presto</a>. With EMR you can run Petabyte-scale analysis at <a href="https://pages.awscloud.com/Gated-IDC-The-Economic-Benefits-of-Migrating-Apache-Spark-and-Hadoop-to-Amazon-EMR.html">less than half of the cost</a> of traditional on-premises solutions and <a href="https://aws.amazon.com/blogs/big-data/amazon-emr-introduces-emr-runtime-for-apache-spark/">over 3x faster</a> than standard Apache Spark. For short-running jobs, you can spin up and spin down clusters and pay per second for the instances used. For long-running workloads, you can create <a href="https://aws.amazon.com/about-aws/whats-new/2019/05/amazon-emr-now-supports-multiple-master-nodes-to-enable-high-availability-for-hbase-clusters/">highly available</a> clusters that <a href="https://aws.amazon.com/blogs/big-data/best-practices-for-resizing-and-automatic-scaling-in-amazon-emr/">automatically scale</a> to meet demand. If you have existing on-premises deployments of open source tools such as Apache Spark and Apache Hive, you can also run <a href="https://aws.amazon.com/emr/features/outposts/">EMR clusters on AWS Outposts</a>.</blockquote><h4><strong>So, What is Amazon EMR?</strong></h4><p>Amazon EMR is an AWS service, EMR stands for Elastic MapReduce. As the name implies, it is an elastic service that allows the users to use resizable Hadoop clusters and it has map-reduce components for the computations.</p><p>So, it is an in-the-cloud solution hosted in Amazon’s data center to supply the needed computing power and on-demand capacity to resolve big data challenges. Moreover, using Amazon EMR simplifies the setup and management of the cluster of Hadoop and MapReduce components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*uhWmiKoX20g8K-RR6841RQ.jpeg" /><figcaption><a href="https://www.oreilly.com/library/view/programming-elastic-mapreduce/9781449364038/ch01.html#Fig1.3">Figure </a>4 shows an architectural view of the EMR cluster.</figcaption></figure><h3>Flink setup</h3><p>I will start by outlining the steps I followed to install Flink on my local device (OS ubuntu 18.04), then the EMR setup.</p><h4><strong>Flink local setup</strong></h4><p>I used the local installation guide from Apache Flink, and the steps were as followed:</p><ul><li>Check Java installed for compatibility. Flink requires Java 8 or 11</li></ul><pre>java -version</pre><ul><li>Download the 1.10.1 release and untar it.</li></ul><pre>$ tar -xzf flink-1.10.1-bin-scala_2.11.tgz<br>$ cd flink-1.10.1/</pre><ul><li>Start a Cluster</li></ul><pre>$ ./bin/start-cluster.sh<br>Starting cluster.<br>Starting standalonesession daemon on host.<br>Starting taskexecutor daemon on host.</pre><ul><li>Submit a job</li></ul><pre>$ ./bin/flink run examples/streaming/WordCount.jar<br>$ tail log/flink-<strong>*</strong>-taskexecutor-<strong>*</strong>.out<br>  <strong>(</strong>to,1<strong>)</strong><br>  <strong>(</strong>be,1<strong>)</strong><br>  <strong>(</strong>or,1<strong>)</strong><br>  <strong>(</strong>not,1<strong>)</strong><br>  <strong>(</strong>to,2<strong>)</strong><br>  <strong>(</strong>be,2<strong>)</strong></pre><ul><li>In order to run python code on Flink, we need to ensure that the default version of python is 3.5 or higher.</li></ul><pre>$python --version<br>Python 3.7.3</pre><p>I have faced an issue while running Flink with the system path configurations for python. So ensure that python3 is added to the path and it does not conflict with Anaconda.</p><h4><strong>Flink EMR setup</strong></h4><ul><li>From AWS UI choose EMR service.</li><li>Choose create an EMR cluster with Hadoop, zookeeper, and Flink installed.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*zhscke650fPj4wCB4lzPsw.png" /></figure><ul><li>Storage: two instances with m5.xlarge storage.</li><li>ensure that web UI port is accessible through an ssh tunnel.</li></ul><p>The cluster will require some time to be ready for usage. Once it is ready, we can test Flink on EMR.</p><ul><li>Access EMR through ssh tunnel</li></ul><pre>ssh <a href="/service/mailto:hadoop@ec2-52-208-105-107.eu-west-1.compute.amazonaws.com">hadoop@******.compute.amazonaws.com</a> -i flink-poc.pem -L 8081:localhost:8081</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*E7OPbDYSD3tD2VGU7uTTqg.png" /></figure><ul><li>Locate Flink installation folder</li></ul><pre>$ whereis flink<br>flink: /usr/bin/flink /usr/lib/flink /etc/flink<br>$ cd /usr/lib/flink</pre><ul><li>Run Flink cluster</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ie7Pt5FeqcO4S51HjOb9bA.png" /><figcaption>running Flink cluster</figcaption></figure><p>It is worth mentioning that I had to fix Flink configurations to run the cluster due to memory errors using the default configurations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*77pIXLl6mUKVlu6FeZ7zwA.png" /><figcaption>Errors with default Flink configurations</figcaption></figure><pre>$ cd conf<br>$ vim flink-conf.yaml</pre><p>The default configurations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*0HDYhfW0RuSuYTjrK9lZSw.png" /><figcaption>flink-conf.yaml</figcaption></figure><p><strong><em>So, what was the issue with the configurations? </em></strong>the size of the task manager heap and job manager heap configurations is commented.</p><p>so, I replaced the following configurations and then the cluster ran successfully.</p><pre># The heap size for the JobManager JVM</pre><pre>jobmanager.heap.size: 1024m<br>taskmanager.memory.process.size: 1728m</pre><p><em>Settings</em> <em>required to enable the web interface:</em></p><pre># The address under which the web-based runtime monitor listens.<br>#<br>jobmanager.web.address: 0.0.0.0</pre><pre># The port under which the web-based runtime monitor listens.<br># A value of -1 deactivates the web server.</pre><pre>rest.port: 8081</pre><h3>Running Word Count Example</h3><p>Let’s test if Flink is working by using the examples provided by Flink:</p><h4><strong>Java Example</strong></h4><p>For this, I choose the word count batch example. This program will return the number of occurrences of each word from a given input file. To run a Flink job we use the following command:</p><pre>./bin/flink run </pre><p>To run the wordcount example, we just provide the jar location to the Flink running command as follows:</p><pre>./bin/flink run ./examples/batch/WordCount.jar</pre><p>From the console we notice:</p><ol><li>The Job has been submitted and the JobID</li><li>Job Runtime is 1144 ms.</li><li>key-value pair for the word and count of this word.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hk_94NdWS88mcV2ztsB4MA.png" /><figcaption>console output for word count</figcaption></figure><p>Next, let’s check the web service UI:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-CC_bcnB_1utEYRbX3441g.png" /><figcaption>Completed Jobs WebServer UI</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1o186E3JgQXSmIQOPp2qGQ.png" /><figcaption>Job details Web server UI</figcaption></figure><p>The web service UI main page outlines information about the submitted jobs, the number of tasks, and the status of these jobs. If we click on the Job we will be directed to a detailed description of the job executed. The overview includes information about each task (duration, parallelism, records sent and bytes) and the DAG diagram.</p><h4><strong>Python Example</strong></h4><p>The python example for word_count.py will store the results in /tmp/result file, to run a python file with Flink we just need to add -py argument to Flink run command:</p><pre>./bin/flink run -py /examples/python/table/batch/word_count.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wQOLj42rEJ1s-OYIo0M0nw.png" /><figcaption>Python console output</figcaption></figure><p><strong><em>Failed to run a Python script! but why?</em></strong></p><p>The above fails because Flink is trying to use python 2.7 to run the program which is an incompatible version with Flink, we need python version above 3.5. Let’s try to check the python version installed on EMR:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*BZEQfqaZ1_bj7UBK4NrJyA.png" /></figure><p>So even though the default python is set to python 3.7.6, Flink was running python 2.7.</p><p><strong>So, How to resolve this issue:</strong></p><ul><li>Download the virtual environment script(<a href="https://ci.apache.org/projects/flink/flink-docs-release-1.10/downloads/setup-pyflink-virtual-env.sh">setup-pyflink-virtual-env.sh</a>).</li><li>Run the required virtual environment setup from the EMR:</li></ul><pre>$ setup-pyflink-virtual-env.sh 1.10.0</pre><ul><li>Activate the virtual environment</li></ul><pre><em># activate the conda python virtual environment</em><br>$ source venv/bin/activate</pre><p><strong>Let’s run it!</strong></p><pre>./bin/flink run -py /examples/python/table/batch/word_count.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pKzGi7e9Xmh6x7x9xHCaGA.png" /><figcaption>word_count.py working console output</figcaption></figure><p>So now the code is running successfully, what we can infer from the above:</p><ol><li>Job ID</li><li>The Job run time</li><li>The /tmp/result file, we can see the count for each word.</li></ol><p>What about the web UI:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xH4SN8l_SnsQyH8ErJiJKA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FxwQqoCGJk6Q1HMgEE_pOQ.png" /></figure><p>When you don’t want to use Flink cluster, you can stop the cluster with:</p><pre>sudo ./bin/stop-cluster.sh</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gEOx4EHuOO9NXaVOhp2Oiw.png" /><figcaption>stop cluster console</figcaption></figure><p>I have just started learning Apache Flink, so I decided to start blogging about this learning process with a series of blogs covering realtime and batch streaming.</p><blockquote>Looking forward to the feedback or questions. I can be reached with <a href="https://www.linkedin.com/in/nisreinsada/">Linkedin</a>, <a href="http://nesreensada@gmail.com/">Email</a>, and <a href="https://github.com/nesreensada">Github</a>.</blockquote><blockquote>Thank You!</blockquote><h3>References</h3><ul><li><a href="https://ci.apache.org/projects/flink/flink-docs-release-1.10/">https://ci.apache.org/projects/flink/flink-docs-release-1.10/</a></li><li><a href="https://www.linkedin.com/learning/apache-flink-batch-mode-data-engineering/">https://www.linkedin.com/learning/apache-flink-batch-mode-data-engineering/</a></li><li><a href="https://www.linkedin.com/learning/apache-flink-real-time-data-engineering">https://www.linkedin.com/learning/apache-flink-real-time-data-engineering</a></li><li><a href="https://ci.apache.org/projects/flink/flink-docs-release-1.11/try-flink/local_installation.html">https://ci.apache.org/projects/flink/flink-docs-release-1.11/try-flink/local_installation.html</a></li><li><a href="https://docs.aws.amazon.com/emr/latest/ReleaseGuide/flink-configure.html">https://docs.aws.amazon.com/emr/latest/ReleaseGuide/flink-configure.html</a></li><li><a href="https://aws.amazon.com/emr/?whats-new-cards.sort-by=item.additionalFields.postDateTime&amp;whats-new-cards.sort-order=desc">https://aws.amazon.com/emr/?whats-new-cards.sort-by=item.additionalFields.postDateTime&amp;whats-new-cards.sort-order=desc</a></li><li><a href="https://www.oreilly.com/library/view/programming-elastic-mapreduce/9781449364038/ch01.html">https://www.oreilly.com/library/view/programming-elastic-mapreduce/9781449364038/ch01.html</a></li><li><a href="https://github.com/mathiaspet/pyflink/blob/master/docs/setup/aws.md">https://github.com/mathiaspet/pyflink/blob/master/docs/setup/aws.md</a></li><li><a href="https://www.alibabacloud.com/blog/the-flink-ecosystem-a-quick-start-to-pyflink_596150">https://www.alibabacloud.com/blog/the-flink-ecosystem-a-quick-start-to-pyflink_596150</a></li><li><a href="https://ci.apache.org/projects/flink/flink-docs-release-1.10/dev/table/python/common_questions.html#execute-pyflink-jobs-with-python-virtual-environment">https://ci.apache.org/projects/flink/flink-docs-release-1.10/dev/table/python/common_questions.html#execute-pyflink-jobs-with-python-virtual-environment</a></li><li><a href="https://github.com/apache/flink/blob/c23787093a9da0e12561fbe22dd6da6164ffe951/flink-examples/flink-examples-batch/src/main/java/org/apache/flink/examples/java/wordcount/util/WordCountData.java#L29">https://github.com/apache/flink/blob/c23787093a9da0e12561fbe22dd6da6164ffe951/flink-examples/flink-examples-batch/src/main/java/org/apache/flink/examples/java/wordcount/util/WordCountData.java</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb466fbcfc6e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/how-to-setup-pyflink-on-amazon-emr-bb466fbcfc6e">How to Setup Pyflink on Amazon EMR</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[How to Build A Profitable Promotion Strategy Easily with Uplift Modeling]]></title>
            <link>https://medium.com/@nesreensada/how-to-build-a-profitable-promotion-strategy-easily-with-uplift-modeling-26b2addc3e46?source=rss-debc18e6a446------2</link>
            <guid isPermaLink="false">https://medium.com/p/26b2addc3e46</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[starbucks]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[promotion-strategies]]></category>
            <dc:creator><![CDATA[Nesreen Sada]]></dc:creator>
            <pubDate>Wed, 23 Oct 2019 05:20:55 GMT</pubDate>
            <atom:updated>2019-10-23T05:20:55.793Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>In this article, we will design a promotional strategy for Starbucks starting from the data understanding to building an uplift predictive model. This project is part of the Data Scientist Nanodegree Capstone project.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iMgb4RZAchyNC1Oi1aTW4g.jpeg" /></figure><h3>Introduction</h3><p>In this article, we will analyze simulated data that mimics customer behavior on the Starbucks rewards mobile app. The data provides information about the user demographics, offer details, and the user event log.</p><p>Starbucks sends out an offer to users of the mobile app, once every few days. An offer can be merely an advertisement for a drink or an actual offer such as a discount or BOGO (buy one get one free). Also, some users might not receive an offer during certain weeks. The offers can be divided into 3 main types:</p><ol><li>BOGO(buy-one-get-one): the user needs to spend a certain amount to get a reward equal to a threshold amount.</li><li>Discount: the user gains a reward equal to a fraction of the amount spent.</li><li>Informational: This offer contains no reward nor a minimum amount spent.</li></ol><p>The main questions we are interested in answering from the analysis:</p><ol><li>Can we identify which groups of people are most responsive to each type of offer?</li><li>Can we increase Starbucks ‘ profit by adopting a selective promotion strategy instead?</li></ol><p>Furthermore, we will use RFM(Recency-Frequency-Monetary) clustering which is a method for customer segmentation. This method divides the customer’s into groups based on their purchase recency, frequency, and monetary value.<br>This article will be divided into the following section:</p><p>1. Data Understanding.</p><p>2. Basic Preprocessing.</p><p>3. Basic Exploratory Data Analysis(EDA).</p><p>4. Feature Engineering.</p><p>5. Data Modeling.</p><p>The complete code and the data can be found on my <a href="https://github.com/nesreensada/Data-Scientist-Udacity-Nanodegree-Term2/blob/capstone_project/Starbucks_Project/Mine_Starbucks_Capstone_Notebook.ipynb">Github</a> repository.</p><h3>Data Understanding</h3><p>In this section, we will look into the data provided in more depth, get a grasp over the different and decide the required preprocessing.</p><p>First, let’s look at the data provided in this project:</p><ol><li>Portfolio<strong>: </strong>this file contains the details of the offers; such as the duration(days), offer_type([bogo, informational, discount]), channels([email, mobile, social, web]), difficulty(amount to be spent by the customer to unlock the offer) and the reward(upon received upon offer completion).</li></ol><figure><img alt="Portfolio file data" src="https://cdn-images-1.medium.com/max/606/1*9WXqCpoAx7V3s638vToJiQ.png" /><figcaption>Portfolio</figcaption></figure><p><strong><em>From the above image of the portfolio content, we notice the following:</em></strong></p><ul><li><em>The offers can be divided further by the channels(mobile, email, social, web) they are sent through, the validity period, the total amount spent to unlock the offer(difficulty) and each offer reward.</em></li><li><em>The channels column has a list of values: this needs to be split into several columns for each value.</em></li></ul><p>2. Profile: User’s demographics such as gender, age, became_member_on, and income.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*xhcMaJfZkweFx7RWFHZ7WA.png" /><figcaption>Profile data</figcaption></figure><p><em>From the picture above and the analysis that can be on the notebook:</em></p><ul><li>Handle the missing data in age, gender, income columns. The missing values in the age column had a value of 118 and if a field was found missing in one of those fields, it was missing in the remaining columns.</li><li>Change the become_member_on data type to DateTime instead of the current int.</li></ul><p>3. Transcript: Event log</p><ul><li>event: event type [offer received, offer completed, offer viewed, transaction].</li><li>person: customer id.</li><li>time: event time in hours.</li><li>value: a dictionary containing either the amount if the event type was transaction otherwise it will contain the offer_id.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*yYT3mqDu5t62DUlIL1W9QA.png" /><figcaption>Transcript</figcaption></figure><p>from the analysis, the basic preprocessing required includes:</p><ul><li>Extracting the transaction amount or the offer id from the value field.</li><li>Convert the time into days instead of hours.</li></ul><p>To build the predicative uplift modeling, we will need to preprocess the data from these different sources to be able to combine them effectively.</p><h4>Important Considerations</h4><p>Other things to take into account as part of preprocessing the data:</p><ul><li>The flow of events for a typical Offer is as follows: offer_received → offer_viewed → transactions→offer_completed.</li><li>The transaction events are not associated with an offer_id.</li><li>An offer might be completed for users even if they have not viewed it.</li><li>An offer might be complete even if the user spends the unlocking amount after the offer validity time.</li><li>The informational offers don’t have an offer completed event.</li></ul><p><em>Example of the above issues:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*r-UgncUgXz5O6vzq-hXG4w.png" /><figcaption>Merged transcript &amp; portfolio to highlight issues</figcaption></figure><p><em>The issue for this customer highlights the third point mentioned before. The user for offer ‘fafdcd668e3743c1bb461111dcafc2a4’ has completed the offer before viewing the offer.</em></p><p>Validating the offer type and deriving additional customer attributes will be handled in the feature engineering section in more detail.</p><h3>Basic Pre-processing</h3><p>The following was done to pre-process the data:</p><p><strong>Portfolio</strong></p><ul><li>Handle the list of values in the channels column by creating a separate column for each channel and assigning a 1 value when it is present in the offer.</li><li>Rename id column to offer_id.</li></ul><p><strong>Profile</strong></p><ul><li>Change the ‘became_member_on’ datatype to the date. Also, extract month, year and day of becoming a member.</li><li>Rename id to customer_id</li><li>Handle the presence of 3 values in the gender variable by considering the 0 as a missing field with a Nan value.</li></ul><p><strong>Transcript</strong></p><ul><li>Handle the value column to extract either the transaction value or the offer_id.</li><li>Rename person to customer_id</li><li>Change the time to days instead of hours.</li></ul><p>So now after performing basic cleaning and preprocessing, we can move to exploratory data analysis(EDA).</p><h3>Basic EDA</h3><p>We will look into user demographics distributions and transaction distributions.</p><ol><li><strong>Income Groups Distribution</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*_rxnOyYbjdd2X0Cxyg-9xg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*OAARdw5OG0h2LKprfGUydw.png" /><figcaption>Customers Income Distribution</figcaption></figure><p><em>The Income range of [30000, 120000] is split into 10 groups. From these groups, we notice that most people are in the 40k-80k income-range, 19% of the earners which is the 50k-60k income range, and the histogram is a left-skewed.</em></p><p><strong>2. Gender Distribution</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*bXbSWiusHhiLisijV-5JZQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*JmIF68Z2lYdZF2A6OJXpnA.png" /><figcaption>Gender Groups Distribution</figcaption></figure><p><em>The Data contains more Males than females in this dataset with 58% male users compared to 42% Females.</em></p><p><strong>3. Age Groups Distribution</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*Z7FpE9K2kQ7pfYpxrjWpgA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*TvfHDnzK5B1S840X00p92g.png" /><figcaption>Age Distribution</figcaption></figure><p><em>The Age range of [18, 101] is split into 10 groups. From these groups, we notice that the age group with the highest percentage in the members is 48–58 with 24%, the smaller group consists of the older generation (88–98) and the</em> <em>distribution follows a normal distribution curve.</em></p><p><strong>4. Joining Date for Members</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*C42d_v_KLowRsgvxgsWJiw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*qRNgCDuF5X9I1QHtOP-a-Q.png" /><figcaption>Joining Date</figcaption></figure><p><em>From the figures above we can see that there was a boost in the memberships during the third quarter of 2017 and the peak of memberships at the Q4. from 2017 Q2 to Q3 2017 there was an increase of 160% compared to the Q2 of 2017. Also, the region of the increased memberships ranges from August 2017 — Feb 2018.</em></p><p><strong>5. Events Distributions</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*xRYTXx3Y1XEhHn3d_2TnSA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*JzrjV0P8fAvLAAuFtzPDeg.png" /><figcaption>Events Distribution</figcaption></figure><p><em>The events are segmented into 45% transactions, 25% received offers, 19% viewed offers and 11% completed offers.</em></p><h3>Feature Engineering</h3><p>In this section we tackle the following:</p><ul><li>Validate the viewed, completed and received offers and create customer transactions and stats.</li><li>Create RFM Clusters.</li><li>Handle missing values for age, gender, and income: the income and age missing values will be replaced by the mean value while the gender will be replaced by the most frequent value which is the Male.</li><li>Handle categorical variables: all the categorical variables need to be transformed using label encoding and pandas get dummies</li><li>Drop unnecessary columns for the analysis.</li></ul><p>The first two points will be discussed in detail and the complete code viewed from the code on the <a href="https://github.com/nesreensada/Data-Scientist-Udacity-Nanodegree-Term2/tree/master/Starbucks_Project">Github repository</a>.</p><p>Upon completing this step the data will be ready to be used for the uplift model.</p><h4>Handling the offers events and the transactions</h4><p>As have been discussed before in the data understanding section. The offer events need proper handling to identify received, complete and viewed offers by a customer. This can be achieved by checking if the offer time constraints and amount to unlock the offer have been met.</p><p>Therefore, we need to validate if the transactions occurred as a result of viewing the offer or if it is an independent event and confirm if the user has viewed and completed the offer within the validity period while handling the issue of missing offer_id with the transaction event and the missing offer complete event with the informational offers.</p><p>Since the completion of an offer is a variable of the offer type. The following convention was used to consider an offer complete:</p><ul><li><em>BOGO and discount offer condition:<br></em>offer_time_recieved &lt; offer_time_viewed &lt; transaction_time &lt; offer_time_completed &lt; offer_end_time (within the time validity)</li><li><em>Informational offers:</em><br> offer_time_received &lt; offer_time_viewed &lt; transaction_time &lt; offer_end_time</li></ul><p>After finding the completed offers. we can split the customers into 4 groups:</p><ol><li>People who responded to offers and completed an offer (Treatment response TR).</li><li>People who viewed an offer but did not complete the offer(Treatment no response TN)</li><li>People who have not received an offer or have not viewed the offer and have not made a completed the offer(control no response CN)</li><li>People who have not received an offer or have not viewed the offer but have completed the offer(control response CR).</li></ol><p>So in order to get the customers groups and create the uplift modeling. The following steps will be followed for each customer_id:</p><p>0. Merge the portfolio with the transactions.</p><ol><li>Split the transcripts dataframe on the event type into received, viewed, completed and transactions.</li><li>Find offers that have been received and completed. This step will create 2 additional columns: a completion flag and the offer finish time. Also, an offer is considered complete if it is within the validity period and the offer finish time is first completion event for this user when the customer completes the offer(The first offer completion event).</li><li>Get the viewed and successful offers. This step returns viewed and successful flag plus the offer view time.</li><li>Handle informational offers since the offer completion is not available as mentioned before.</li><li>Get the transaction summary and user stats such as the amount spent during the offer, the amount spent during the non-offer period, profit, the number of completed offers for each offer type.</li><li>Assign the customer to a group.</li></ol><p>Here is the resulting dataframe from this stage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*-AyhFJ5k8uQyMpvv5C3MXg.png" /><figcaption>Analyzed Transaction columns</figcaption></figure><h4>RFM(Recency-Frequency-Monetary) Clusters</h4><p>RFM is an abbreviation for Recency, Frequency, and Monetary Value which is a method for customer segmentation. This method helps in examining how recently did the customer purchase(recency), how often they purchase(frequency), and how much they spend(monetary). Also, it helps in targeted marketing.</p><p>These Recency, Frequency, and Monetary attributes will provide customer segments as follows:</p><ul><li>Low-value Segment: customers who are the less active, not very frequent buyer and generates very low or negative revenue.</li><li>Mid-value Segment: in between customers.</li><li>High-value Segment: customers who have bought recently, frequently and spend the most compared to other customers.</li></ul><p>To create RFM clusters, the following steps :</p><ul><li>Calculate the recency, frequency and monetary value for each customer.</li><li>Create a cluster for each of the attributes (recency, frequency and monetary).</li><li>Create the combined RFM clusters by summing all the clusters to create the customer overall score, then create the customer segments of low, mid and high-value customers.</li></ul><p><em>Here is how the overall score statistics are:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*aGpfJXsbaS_OwBAT7TXM5g.png" /><figcaption>The overall score statistics</figcaption></figure><blockquote>A customer who have a lower overall_score will have older purchases, least frequent purchases and the smallest revenue compared to the a customer with a score of 9.</blockquote><p>Let’s take a look at the RFM attributes for each segment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*lX0GLVhPidhFa1dxpCjoGA.png" /><figcaption>Recency vs Revenue</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*eK1VqMeyUDSIO0B4o8YRqQ.png" /><figcaption>Recency vs Frequency</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*W9S0ho6XVwIFHEUao8oGbg.png" /><figcaption>Frequency Vs Revenue</figcaption></figure><p>We can see from the plots above that each group segment provides a clear distinction for each RFM attribute.</p><p>The data frame from this feature engineering step will be merged with the dataframe from the previous step based on the customer_id. Here is a sample of the output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*Wdsn3n1Z-HNHqBrwNhFchA.png" /><figcaption>sample of the cleaned transactions dataframe with the RFM_combined</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DFWN-_t7wxNCLChLqzIx5Q.png" /><figcaption>Customers RFM scores and attributes</figcaption></figure><h3>Additional EDA</h3><p>Before we proceed to build the uplift model, let’s look do further exploration of the data:</p><ul><li>RFM segments distribution</li><li>Customer groups distribution</li><li>Demographics of RFM segments</li><li>The purchasing behavior for each RFM cluster, such as:<br> — Total Spent<br> — Profit<br> — Number of completed offers<br> — Segment (TR, TN, CR, CN)</li><li>The customer group vs purchasing behavior:<br> — total_spent<br> — age<br> — gender</li><li>Total_spent vs RFM vs Customer Group</li><li>Age vs RFM vs Customer Group</li><li>Gender vs RFM vs Customer Group</li><li>Income vs RFM vs Customer Group</li></ul><p><strong>RFM Segments Distribution</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*GyVNALJWNMCYdHcQDYbJ5A.png" /><figcaption>RFM Groups Distributions</figcaption></figure><p>So from the distribution, we see that 41% of the customers are in the Low-value RFM group followed by the Mid-value RFM group, and the High RFM group with 23% of customers.</p><p><strong>Customer Groups Distribution</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*8s_9orPBeExSEbD7gO_IVw.png" /><figcaption>Customer Groups Distribution</figcaption></figure><p><em>Summary</em></p><ul><li>40% of the customers are in the Treatment response(TR) group.</li><li>Control Response group(CR) had 14.9% of the customers.</li></ul><p><strong>Demographics of RFM segments</strong></p><p><em>Age</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*kWspfUeDgDiZbBAjZGGHGQ.png" /><figcaption>RFM segment versus customer age</figcaption></figure><p>The age is not a factor in the RFM segment it seems. though the RFM segment with low-value seems to contain a smaller age group range from 48–64 (quartile range).</p><p><em>Income</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*SR3WCeuPtin9CIHr7Sa8ew.png" /><figcaption>Income VS RFM Segment</figcaption></figure><p>The income of the different groups is very similar across the different groups.</p><p><em>Gender</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*liCJ_5xQpmIw6DTniT3y1w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*O5wYycMB-yNEMVyF0mMVxQ.png" /><figcaption>Gender Distribution Across RFM segments</figcaption></figure><p>Since this dataset contains more males than females I normalized the counts by the gender to compare the RFM segment distribution. The Males are present in the low-value and mid-value RFM while the females have a higher percentage in high value.</p><p><strong>The Purchasing Behavior in RFM Clusters</strong></p><p><em>Total spent vs RFM segment</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*7V7Y9Gc7CLNEri0wF60oiw.png" /><figcaption><em>Total spent vs RFM segment</em></figcaption></figure><p>As expected the high-value RFM has the highest amount spent by observing the upper and lower limit. The Q3 for the low-value segment is around 15 dollars compared to 37 in the mid-value while the high RFM cluster had 74 dollars spent.</p><p><em>Customer segments vs RFM clusters</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*RV9Zn5Pa6GfiGVFpWYRRRg.png" /></figure><p><em>In terms of the segments the RFM clusters are distributed as follows:</em></p><ul><li>CN comprises 56% of the Low-value RFM segment, followed by Mid value RFM clusters.</li><li>CR mostly in the Mid Value segment with 38.5% followed by 33.7% in the high-value RFM cluster.</li><li>TN comprises of 62% low-value RFM clusters with below 10% of the high-value RFM cluster.</li><li>TR: highest portion comes from the mid-value RFM cluster with 40% followed by high value with 35.6%</li></ul><p><em>Comparing with respect to the RFM cluster:</em></p><ul><li>Low-value have 42% in the TN segment and similar percentages for CN and TR.</li><li>Mid-value RFM cluster comprises of 40% for the TR segment which is double the other RFM clusters.</li><li>High-value comprises of 60% of TR then 44% of Mid-value Customers.</li></ul><p>The above observations make sense since the high-value customers are the ones who are most frequent, spent the most and had the most recent interactions. This indicates that high and mid-value customers are responsive to targeted marketing while it did not make a difference in the Low values.</p><p>Completed offers vs RFM Segment</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*eFN1HOQoThxYYGDrhDXSAw.png" /><figcaption>Number of completed offers vs RFM segment</figcaption></figure><p>As expected the number of completed offers for the High-value Cluster is the highest compared followed by mid-value and RFM clusters.</p><p><strong>Customer Groups vs Demographic</strong></p><p><em>Income vs Customer Segment</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*f9wH-T9IjaemxgQNvZpKgQ.png" /></figure><p>We can see that the highest income customers are in TR or CR group with the highest Q3 for the CR customer group. TN group had the least upper limit for income.</p><p><em>total spent vs customer segment</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*WrvcURX9hb_Y0IOQtm-8lw.png" /></figure><p>The difference in the amount of money spent between the treatment and control groups is significant. The highest spent value amount of value spent in TN and CN groups is less than the lower limit of the TR and CR groups.</p><p><em>Gender vs Customer Segment</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*fDoTaLvm9lVvqHGy6LW2Lw.png" /></figure><p>We Can observe that the highest percentage of females is in the TR group. the Males have equal percentages of TN and TR groups.</p><p><strong>Total_spent vs RFM vs Customer Group</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*KND-MwgDeB5TCPnnVsE1Jg.png" /></figure><p>We can conclude that the TR and CR have the highest amount spent with the high value of RFM cluster having the highest amount spent. and they have a similar range of money spent and this can be observed in the CN and TN groups.</p><p><strong>Age vs RFM vs Customer group</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*m0DEi9NjvJVIljjHEyPa9A.png" /></figure><p>The age have similar trends across different customer segments. with the high valued RFM cluster having a wider range of age covered and the response groups both have higher age.</p><p><strong>Income vs RFM vs Customer Group</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*qqCHiXaP-DDhfAryD-QTug.png" /></figure><ul><li>The highest income can be found with the customers from the response groups such as TR and CR groups.</li><li>The highest income ranges are for CR customer group</li><li>The lowest income range is for the CN group.</li></ul><p><strong>Gender vs RFM vs Customer Group</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*T5_YD1oPLYIGaUJ8VxAP-A.png" /></figure><p>The gender does not have an effect on the customer segments and the heat map has consistent values.</p><p>Now that we have completed the feature engineering and did some extra EDA step we are going to move to the modeling step.</p><h3>Data Modeling</h3><p>In this section, we will use uplift modeling for the analysis. We have 10 different offer types and the following convention will be used for the ease of reference:</p><ol><li>B3_10_7_10 as part BOGO: sent to 3 channels (email, mobile, social), difficulty 10, duration 7 days and a reward of 10.</li><li>B4_10_5_10</li><li>B3_5_7_5</li><li>B4_5_5_5</li><li>D2_20_10_5</li><li>D4_7_7_3</li><li>D4_10_10_2</li><li>D3_10_7_2</li><li>I3_0_4_0</li><li>I3_0_3_0</li></ol><p><em>The first letter is used for the offer type, followed by the difficulty, duration and the last value is for the reward and these values are separated by _.</em></p><p>Let&#39;s give a brief explanation of the components that will be used in this part:</p><h4>Uplift Modeling</h4><p>Uplift modeling is an incremental modeling technique that models the incremental impact of treatment such as a campaign. This type of modeling helps identify what type of promotions are effective to which customers thus creating a more profitable promotion strategy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*WgsCmtosgnh7P71QzVpjrg.png" /><figcaption>Customer Categories(<a href="https://www.predictiveanalyticsworld.com/patimes/uplift-modeling-making-predictive-models-actionable/8578/">ref</a>)</figcaption></figure><p>One way to look to understand the importance of uplift modeling is the above figure. This shows four categories of customers according to their response to promotions: (a) Persuadable, (b) Sure Thing, © Do-Not-Disturb, and (d) Lost Cause. To promote the desired response we target those who are in the <em>Persuadable </em>group. For all others, the treatment is wasteful and we might face the sleeping dog customer who doesn’t buy when promoted.</p><p>The uplift modeling objective is to find the persuadable group to improve the promotion campaigns.</p><p><strong><em>There are several approaches for uplift modeling:</em></strong></p><ol><li><strong>Traditional one model approach:</strong> This method predicts only customers who received promotions and completed the offer or purchased. The issue with this approach is that it discards the control group data.</li><li><strong>Two model Uplift Approach</strong>: create 2 models to predict the purchases from the treatment and the control group respectively. The difference in the predicted probabilities of these models represents the lift value which can be used as a cutoff point for the customers responsive to promotions. The issue with this model is that lifts indirectly.</li><li><strong>Four quadrant approach:</strong> split the customers into 4 Groups(treatment response: TR, treatment no response TN, control response CR, control no response CN). then build a model to predict the label the customer belongs to. The promotions can be either sent to only TR(sure thing to respond to promotion) or we can create an uplift score to divide the customer based on the probability of belonging to certain groups and use cut off to decide when to send a promotion or no.</li></ol><p>These uplift modeling approaches will be implemented for each offer type and evaluated with the Model metrics.</p><h4>Model Metrics</h4><p>The metrics that will be used to track the performance and the promotion strategy are:</p><ul><li><strong>NIR(net incremental revenue):</strong> depicts how much is made (or lost) by sending out the promotion. Mathematically, this is:</li></ul><blockquote>NIR = treatment_revenue — control_revenue</blockquote><ul><li><strong>IRR:</strong> How many customers purchased the product with promotion compared to those who did not receive it.</li></ul><blockquote>IRR = num_treatment_compelted_offers/num_treatment — num_control_purchase /num_control</blockquote><h4>Handling Imbalanced Data</h4><p>The SMOTE (Synthetic Minority Over-Sampling Technique) will allow us to handle the domination of one class in the training dataset by creating synthetic features to oversampling the minority classes in the data.</p><h4>XGboost algorithm</h4><p>Xgboost stands for extreme Gradient Boosting. It is an implementation of gradient boosted decision trees but with boosting (ensemble technique) that use models that corrects errors made by previous models. This algorithm offers speed and model performance. RandomGridsearch will be used to tune the parameters to get the best model.</p><p><em>Xgboost parameters that can be tuned:</em></p><ul><li>Max_depth which is the max number of different features used in each tree</li><li>Learning rate: the model learning rate (the update of parameters rate) which can help in combatting the overfitting of the model.</li><li>Subsample: percentage of rows taken to build the tree.</li><li>colsample_bytree: number of columns used by each tree.</li><li>gamma: regularization parameter.</li><li>n_estimators: 100.</li></ul><p><em>So we evaluate each offer independently based on the promotion strategy results and decide the best approach for it.</em></p><p>I will explain the full flow of the analysis for one of the offers and give a summary of the rest of the models.</p><h4>B3_10_7_10</h4><p>This is offer is a BOGO offer, sent through 3 channels (email, mobile, social), difficulty 10, duration 7 days and a reward of 10.</p><p><strong>Four Quadrant approach</strong></p><p>what was done here:</p><ul><li>Create a model that predicts the customer segment.</li><li>Study the importance of the features.</li><li>Use the Random GridSearch to Tune the model parameters</li><li>Compare the promotion strategies results against the current promotion strategy. The first strategy sends the promotion only to customers predicated in the treatment response group. While the second strategy uses an uplift formula to predict the promotion target group.</li></ul><blockquote>uplift forumla = Probability(customer is TR) + Probability(customer is CN) — Probability(customer is TN) —Probability(customer is CR)</blockquote><p>So how to create the xgboost model that predicts the customer segment:</p><ul><li>Split the data into train, validation, and test.</li><li>Handle imbalanced data using SMOTE.</li><li>Fit the train data.</li><li>Use the validation data for the classification report and the confusion matrix.</li><li>Use the test data for the promotion strategy.</li></ul><p>The results for the model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*3PWwgG2NPQkOxpLfdTGGzQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*UXdaJ-CTAdlgp_gyn9fpGw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*NzAw7YQWNEvHr_dZsFUwsA.png" /></figure><ul><li>The classification report provides a summary for the metrics for the model so the avg accuracy achieved was 0.82, recall 0.67, f1-score: 0.68, precision 0.70. The model was able to identify best the TN class followed by TR compared to the control segments CR and CN.</li><li>The classification report provides a summary for the metrics for the model so the avg accuracy achieved was 0.82, recall 0.67, f1-score: 0.68, precision 0.70. The model was able to identify best the TN class followed by TR compared to the control segments CR and CN.</li><li>The top features in the model are the total spent, income, profit, num_bogo_completed, revenue.</li></ul><p><em>Promotion Strategy results</em></p><pre>┌────────────┬─────────────────────────┬──────────┬───────┐<br>│   OFFER    │        Strategy         │   NIR    │  IRR  │<br>├────────────┼─────────────────────────┼──────────┼───────┤<br>│ B3_10_7_10 │ Base                    │ 17256.69 │ -0.25 │<br>│ B3_10_7_10 │ Quadrant_uplift_forumla │ 14428.54 │  0.12 │<br>│ B3_10_7_10 │ Quadrant_Simple         │ 14474.11 │ -0.01 │<br>└────────────┴─────────────────────────┴──────────┴───────┘</pre><p>The best NIR was achieved by the base strategy but the IRR was improved by The proposed promotion strategy resulted in an increase in the purchase response to the offer.</p><p><strong>Two Models Approach</strong></p><p>This approach uses two models that predict the completion of the promotion with one for the treatment group and another for the control group. Then an uplift score will be calculated and promotion will be sent to the top 3 percentile.</p><p><em>Model Performance</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*QY5VQcyx7Y-CU0yVUtC_CQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*wyBGdfOWMwyq6aSTZrzmJg.png" /><figcaption>Control Model Performance</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*FqNTu6-zxI-fsgIY6n8V8g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*40eNBcwcAC8aFo3q6EbEQA.png" /><figcaption>Treatment Model Performance</figcaption></figure><ul><li>This model for both the treatment and the control group achieved an accuracy of 100% which is much higher than the accuracy by the quadrant model.</li><li>The important features seem to be similar except the frequency importance got higher in the treatment model.</li></ul><p><em>Promotion Strategy</em></p><p>This promotion strategy sends promotions to top 3 percentile of the lift probability:</p><blockquote>lift = Probability(Offer_completion/ treatment) — Probability(Offer_completion/ control)</blockquote><p>The results for this is the NIR value of 1002.37 and the IRR value of -0.05.</p><p>This model achieved lower IRR compared to the previous 4 quadrant model and much lower NIR values. a possible improvement is to try different cut off for the uplift score.</p><p><strong>One Model Approach</strong></p><p>This approach uses one model that assigns 1 to treatment and completed the offer group while the rest of the groups gets 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*-6TDOTJllkNiQwi1vfpwWQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*93jMWpSksj6hTagNDtge6Q.png" /><figcaption>One Model performance</figcaption></figure><p>In this model, the profit had a higher influence on the results and the accuracy though less than the previous model it is still better than the 4 quadrant model.</p><p><em>Promotion Strategy</em></p><p>The IRR for this promotion strategy is -0.02 which is better than the base strategy and has a higher NIR compared to the previous.</p><p><strong>Summary for this offer type</strong></p><p>The best NIR achieved was for the base strategy(sending the promotion for all the customers) while the best IRR was achieved by the Four Quadrant model with uplift formula.</p><p><strong>All the Offers Models Result Summary</strong></p><pre>┌────────────┬─────────────────────────┬───────────┬───────┐<br>│   OFFER    │        Strategy         │    NIR    │  IRR  │<br>├────────────┼─────────────────────────┼───────────┼───────┤<br>│ B3_10_7_10 │ Base                    │ 17256.69  │ -0.25 │<br>│ B3_10_7_10 │ Quadrant_uplift_forumla │ 14428.54  │ 0.12  │<br>│ B3_10_7_10 │ Quadrant_Simple         │ 14474.11  │ -0.01 │<br>│ B3_10_7_10 │ two models              │ 1002.37   │ -0.05 │<br>│ B3_10_7_10 │ one model               │ 14842.48  │ 0.01  │<br>│ ---------- │ ----------------------  │ --------  │ ----- │<br>│ B4_10_5_10 │ Base                    │ 20523.88  │ -0.29 │<br>│ B4_10_5_10 │ Quadrant_uplift_forumla │ 17958.48  │ -0.03 │<br>│ B4_10_5_10 │ Quadrant_Simple         │ 17943.47. │ -0.02 │<br>│ B4_10_5_10 │ two    models           │ 288.12    │ -0.05 │<br>│ B4_10_5_10 │ one    model            │ 17936.55  │ -0.02 │<br>│ ---------- │ ----------------------  │ --------  │ ----- │<br>│ B3_5_7_5   │ Base                    │ 2076.69   │ 0.06  │<br>│ B3_5_7_5   │ Quadrant_uplift_forumla │ 9568.20   │ 0.56  │<br>│ B3_5_7_5   │ Quadrant_Simple         │ 9913.22   │ 0.0   │<br>│ B3_5_7_5   │ two    models           │ -20.04    │ 0.0   │<br>│ B3_5_7_5   │ one    model            │ 10245.07  │ 0.0   │<br>│ ---------- │ ----------------------  │ --------  │ ----- │<br>│ B4_5_5_5   │ Base                    │ 24503.24  │ -0.23 │<br>│ B4_5_5_5   │ Quadrant_uplift_forumla │ 23980.30  │ -0.01 │<br>│ B4_5_5_5   │ Quadrant_Simple         │ 23968.42  │ -0.01 │<br>│ B4_5_5_5   │ two    models           │ 96.22     │ -0.03 │<br>│ B4_5_5_5   │ one    model            │ 24478.09  │ -0.01 │<br>│ ---------- │ ----------------------  │ --------  │ ----- │<br>│ D2_20_10_5 │ Base                    │ -8215.02  │ 0.15  │<br>│ D2_20_10_5 │ Quadrant_uplift_forumla │ 6749.12   │ 0.57  │<br>│ D2_20_10_5 │ Quadrant_Simple         │ 9129.98   │ 0.0   │<br>│ D2_20_10_5 │ two    models           │ -360.84   │ 0.0   │<br>│ D2_20_10_5 │ one    model            │ 9040.90   │ 0.00  │<br>│ ---------- │ ----------------------  │ --------  │ ----- │<br>│ D4_7_7_3   │ Base                    │ 30430.45  │ -0.17 │<br>│ D4_7_7_3   │ Quadrant_uplift_forumla │ 28457.21  │ -0.01 │<br>│ D4_7_7_3   │ Quadrant_Simple         │ 28436.72  │ 0.0   │<br>│ D4_7_7_3   │ two    models           │ 1175.96   │ 0.0   │<br>│ D4_7_7_3   │ one    model            │ 27890.35  │ 0.00  │<br>│ ---------- │ ----------------------  │ --------  │ ----- │<br>│ D4_10_10_2 │ Base                    │ 46810.94  │ -0.15 │<br>│ D4_10_10_2 │ Quadrant_uplift_forumla │ 45492.09  │ 0.00  │<br>│ D4_10_10_2 │ Quadrant_Simple         │ 45478.67  │ 0.0   │<br>│ D4_10_10_2 │ two    models           │ 225       │ 0.0   │<br>│ D4_10_10_2 │ one    model            │ 46001.19  │ 0.00  │<br>│ ---------- │ ----------------------  │ --------  │ ----- │<br>│ D3_10_7_2  │ Base                    │ 8100.24   │ 0.17  │<br>│ D3_10_7_2  │ Quadrant_uplift_forumla │ 15195.96  │ 0.63  │<br>│ D3_10_7_2  │ Quadrant_Simple         │ 15910.22  │ 0.00  │<br>│ D3_10_7_2  │ two    models           │ 207       │ 0.0   │<br>│ D3_10_7_2  │ one    model            │ 14756.79  │ 0.00  │<br>│ ---------- │ ----------------------  │ --------  │ ----- │<br>│ I3_0_4_0   │ Base                    │ 2450.44   │ 0.55  │<br>│ I3_0_4_0   │ Quadrant_uplift_forumla │ 3976.07   │ 0.85  │<br>│ I3_0_4_0   │ Quadrant_Simple         │ 9655.33   │ 0.96  │<br>│ I3_0_4_0   │ two    models           │ -92.33    │ 1.0   │<br>│ I3_0_4_0   │ one    model            │ 9497.37   │ 0.85  │<br>│ ---------- │ ----------------------  │ --------  │ ----- │<br>│ I3_0_3_0   │ Base                    │ 8602.03   │ 0.33  │<br>│ I3_0_3_0   │ Quadrant_uplift_forumla │ 3976.07   │ 0.85  │<br>│ I3_0_3_0   │ Quadrant_Simple         │ 9655.33   │ 0.96  │<br>│ I3_0_3_0   │ two    models           │ -251.56   │ 1.0   │<br>│ I3_0_3_0   │ One    model            │ 11948.27  │ 0.69  │<br>│ ---------- │ ----------------------  │ --------  │ ----- │<br>└────────────┴─────────────────────────┴───────────┴───────┘</pre><p><strong>Summary</strong>:</p><ul><li>We can see that some strategies though have less NIR but they have higher IRR which means better targeting for the customer.</li></ul><h3>Conclusion</h3><p>In this article, we presented the uplift modeling approach as a way to study the customer&#39;s response to offers. The current promotion strategy was to send offers to all the customers, this is a wasteful approach and costly since not all customers respond equally to offers. Additionally, RFM clustering was used in the model features and to segment the customer on purchasing behavior.</p><h4>So what we have demystified at the course of the analysis?</h4><p><strong>Customer Demographics:</strong></p><ul><li>Income: Most people are in the 40k-80k income-range, 19% of the earners which is the 50k-60k income range.</li><li>Gender: <em>58% male users compared to 42% Females.</em></li><li>Age: the age group with the highest percentage in the members is 48–58 with 24%, the smaller group consists of the older generation (88–98).</li></ul><p><strong>RFM Segments and Customer Groups</strong></p><ul><li>RFM Segments Distribution: 41% of the customers are in the Low-value RFM group followed by the Mid-value RFM group, and the High RFM group with 23% of customers.</li><li>Customer Groups Distribution: 40% of the customers are in the Treatment response(TR) while the CR group had 14.9% of the customers. This can explain why the quadrant models performed worst on CN.</li><li>Gender in the RFM segments: The Males are present in the low-value and mid-value RFM while the females have a higher percentage in the high-value segment.</li></ul><p><strong>The Purchasing Behavior in RFM Clusters</strong></p><ul><li>Total spent vs RFM segment: there was a clear difference between the different segments in terms of amount spent.</li><li>Customer segments vs RFM clusters: The mid and high-value segments had higher percentages of the response compared to the low-value segment. This indicates that high and mid-value customers are responsive to targeted marketing while it did not make a difference in the Low values. So maybe a different reward schema can be tested for these customers to encourage them to buy.</li></ul><p><strong>Customer Groups vs Demographic</strong></p><ul><li>Income vs Customer Segment: The highest income customers are in TR or CR group.</li><li>Total Spent vs customer segment: The difference in the amount of money spent between the treatment and control groups is significant.</li></ul><h4>Modeling</h4><ul><li>We have higher NIR for the base strategy in most of the offers which can be explained by the higher number of Treatment groups and the amount spent is not limited to the offer amount.</li><li>The proposed promotion strategy gave a better IRR than the base strategy.</li><li>The two model uplift approach performed the worst in terms of NIR and IRR for most offers. which can be due to the indirect uplift resulting. this can be improved by tunning the uplift score cut off.</li><li>The Promotion strategies that performed better than the base strategy in terms of NIR: D2_20_10_5, D3_10_7_2 , B4_5_5_5 and D4_10_10_2(almost the same as the base NIR and much higher IRR), I3_0_3_0, I3_0_4_0.</li><li>The Discount and informational offers seem to be responsive to these promotion strategies while only the BOGO offers for shorter duration and amount to spent are modeled using this.</li></ul><p>To conclude the uplift modeling helps us improve our targeted customers and optimize the offers as have been seen in this work.</p><p>The full code can be found on the <a href="https://github.com/nesreensada/Data-Scientist-Udacity-Nanodegree-Term2/tree/capstone_project/Starbucks_Project">Github</a> repo.</p><blockquote><em>Thank you and hope this was useful.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26b2addc3e46" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[This is why an Amsterdam Airbnb Listing is Expensive]]></title>
            <link>https://medium.com/@nesreensada/this-is-why-an-amsterdam-airbnb-listing-is-expansive-593029aec0df?source=rss-debc18e6a446------2</link>
            <guid isPermaLink="false">https://medium.com/p/593029aec0df</guid>
            <category><![CDATA[amsterdam]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[airbnb]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Nesreen Sada]]></dc:creator>
            <pubDate>Tue, 25 Jun 2019 13:33:52 GMT</pubDate>
            <atom:updated>2019-06-29T18:22:59.899Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*YdOV-AxDiwTqGOr-QPelhw.jpeg" /><figcaption>Herengracht</figcaption></figure><p>A look Into Amsterdam city Airbnb listings.</p><p><strong>Introduction</strong></p><p><a href="http://airbnb.com/">Airbnb</a> is an online marketplace and hospitality providing members with short term lodging that is comparably cheaper than hotels. It offers a variety of properties such as hostels, boat, cottage or a full apartment.</p><p>In this post, I am using Data science, analysis and Python based on the CRISP-DM process to analyze the Airbnb data.</p><p><em>Why Amsterdam?</em></p><p>Amsterdam is the Netherlands capital and it is one of the top 10 travel destinations in Europe.</p><p>For the analysis in this project, I used the available data from <a href="http://insideairbnb.com/get-the-data.html">http://insideairbnb.com/get-the-data.html</a> for Amsterdam city. The data used include:</p><ul><li>Detailed listings information with 19619 listings and 106 attributes such as the listing summary, property type, room type, price, neighborhood, host related information, and the availability.</li><li>Calendar information for listings providing information about the listing availability on a certain date.</li></ul><p>After looking into the data, I was interested in looking into attributes affecting the price so I came up with the following 4 questions:</p><ol><li>Is it more expensive to book a listing during the high seasons?</li><li>Most expensive month to visit Amsterdam?</li><li>Most expensive and least expensive Neighbourhood in Amsterdam?</li><li>What are the attributes associated with the price of a listing?</li></ol><h3>Question 1: Is it more expensive to book a listing during the high seasons?</h3><p>Using the information in the calendar for Amsterdam Airbnb listings we can compare the availability of the listing to the average listing price for a given data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*36NP4wdhHQ5VTVt1qgUrKA.png" /><figcaption>Average Daily Price Compared to the Availability in Airbnb Listing</figcaption></figure><p>From the above figure we can observe the following:</p><ul><li>The inverse relationship between the number of available listings in given date which is depicted by the red line compared to the average listing of a price.</li><li>The availability in listings stabilizes from January 2020 -May 2020.</li><li>A peak in the availability of listings leading to lower average prices.</li></ul><h3>2) Most expensive months to visit Amsterdam in?</h3><p>Now if we compare the monthly availability of a listing compared to the average monthly prices we can find the most and cheapest months to visit Amsterdam.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*hiNk2YmR9DSurpJ45iuQjw.png" /><figcaption>Average Monthly Listing Price Compared to the Monthly Availability of Airbnb Listing</figcaption></figure><p>Conclusions from observing the previous image:</p><ul><li>The inverse relationship between the listing availability and the monthly price.</li><li>The cheapest months to visit are in the period between February and April.</li><li>The highest average prices are found during May and June months.</li></ul><p><strong>3) Most expensive and least expensive Neighbourhood in Amsterdam?</strong></p><p>The next question that I was trying to answer is to find the neighborhood average price distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*RavGvMycf4s3lg6Evp4rqQ.png" /></figure><p>Insights that can be derived from the above figure:</p><ul><li>The Most Expensive neighborhood is Centrum-Oost followed by Centrum-West. This is expected since this neighborhood is in the city center of Amsterdam city.</li><li>The cheapest listings are in Bijlmer-Centrum and Bijlmer-Oost were these neighborhood lay in the Southeast area of Amsterdam.</li><li>The prices in the center are around double the prices in the southeast and westernmost neighborhoods of Amsterdam.</li></ul><h3>4) What are the attributes associated with the price of a listing?</h3><p>In order to find the attributes associated with the price of a listing. I used the K-means clustering method to segment the available listings into 10 clusterings. Each cluster will have attributes differentiating it from the rest of the clusters.</p><p>First, let&#39;s look at the average listings price per cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*YjCiyONp1KT7LbSPnFk2Ng.png" /></figure><p>Cluster 5 had the highest average price for listings and cluster 1 had the lowest average price compared to the rest of the clusters. Thus I will look into 3 clusters and discuss the most distinguishing attributes in order to understand the pricing of a listing.</p><p><strong>Cluster 5</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*bvr28sasoF9LiJxvMgTMIQ.png" /></figure><p>Before discussing the results of the visualization, I want to clarify that the y-axis value can be ignored and it was only used to normalize the values for the attributes to ease the comparison.</p><p>The graph above shows the attributes differentiating cluster 5. this cluster contains mostly:</p><ul><li>the highest difference is for super strict cancellation policy</li><li>property type: villa, cottage, house, boat, townhouse</li><li>detailed fees are listed such as extra beds, guests,</li><li>neighborhoods: Zeeburgereiland, Oud-Noord, Zuid, Noord-Oost, Zuidas</li></ul><p><strong>Cluster 1</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*8ZSbPeFsT7R6lbzwjfrVcA.png" /></figure><p>Cluster 1 included:</p><ul><li>Property type such as hostels, Tiny house, hotels, Guest suite, Boutique hotel.</li><li>strict cancellation policy.</li><li>neighborhoods such as De Aker — Nieuw Sloten, Driemond</li></ul><p>Overall, the property type, neighborhood, and booking policy affected the listing price.</p><p><strong>Conclusion</strong></p><p>In this article, I looked into 2019 Amsterdam Airbnb listings data and answered questions related to the listings prices.</p><ol><li>We compared the availability of listings to the average listings price to determine the relationship between the two attributes which helped us identify the high season and the most expensive and cheapest month to visit. <strong>This showed that high season is during May and June.</strong></li><li>We then identify the cheapest and expensive neighborhood to stay in Amsterdam.<strong> The neighborhoods closest to the Amsterdam city center such Centrum-Oost followed by Centrum-West were more expensive compared to the cheapest listings in the southeast and westernmost neighborhoods such as Bijlmer-Centrum and Bijlmer-Oost.</strong></li><li><strong>Identified the price attributes using clustering methods:</strong></li></ol><ul><li>Property Type</li><li>Neighborhood</li><li>Room type</li></ul><p>For the code and detailed analysis, please refer to the Github link: <a href="https://github.com/nesreensada/Data-Scientist-Udacity-Nanodegree-Term2/tree/master/Write_BlogPost">https://github.com/nesreensada/Data-Scientist-Udacity-Nanodegree-Term2/tree/master/Write_BlogPost</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=593029aec0df" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>