<?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 Busra Y. on Medium]]></title>
        <description><![CDATA[Stories by Busra Y. on Medium]]></description>
        <link>https://medium.com/@yamanbsr?source=rss-83d3c80f5f1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*MBk61ZKs_Crun9Li</url>
            <title>Stories by Busra Y. on Medium</title>
            <link>https://medium.com/@yamanbsr?source=rss-83d3c80f5f1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 04:10:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yamanbsr/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[A/B Test Application on Real Data]]></title>
            <link>https://medium.com/swlh/a-b-test-application-on-real-data-8ec58f8280f9?source=rss-83d3c80f5f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ec58f8280f9</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[a-b-testing]]></category>
            <category><![CDATA[hypothesis-testing]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Busra Y.]]></dc:creator>
            <pubDate>Tue, 01 Sep 2020 10:12:53 GMT</pubDate>
            <atom:updated>2020-09-03T22:19:07.259Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Conducting A/B Test to compare Advertising Campaigns</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*J0dYt7zNiuyQTKJa.jpg" /><figcaption>Picture Source: <a href="https://www.crazyegg.com/blog/ab-testing/">https://www.crazyegg.com/blog/ab-testing/</a></figcaption></figure><p>Hello Everyone!</p><p>I am back with another article about Data Science. In this article, I will write about what is A-B testing and how to use it on real life data-set to compare two advertisement methods.</p><p><strong>What is A-B Testing and where do we use it?</strong></p><p>A/B testing is a method used to compare two versions or methods of something. It is a very popular method used by from big companies like Facebook, Google, Amazon, Ali Express etc. to many other companies. With this method, we can decide on, for example, the following:</p><ul><li>Button shape, size or color,</li><li>Which advertisement strategy is better,</li><li>Which email format is better,</li><li>Which website design is better,</li><li>Which headline is better etc.</li></ul><p>So let us apply this testing method on a real life situation.</p><h3>Case Study:</h3><p>A big social platform recently introduced an advertisement method with a new bidding type “average bidding”, as an alternative to its existing advertisement method with bidding type called “maximum bidding”. One of their clients has decided to test this new feature and wants to conduct an A/B test to understand if average bidding brings more conversions than maximum bidding.</p><p>In this A/B test, the client randomly splits its audience into two equally sized groups, e.g. the test and the control group. The existing ad campaign with “maximum bidding” is served to “control group” and the new campaign with “average bidding” is served to the “test group”. The A/B test has run for 1 month and now the client wants to analyze and present the results of this A/B test.</p><p>To understand the data variables better, we need to understand the customer journey for the campaign. The customer journey for this campaign is as in the order below:</p><p>1. User sees an ad (Impression)</p><p>2. User clicks on the website link on the ad (Website Click)</p><p>3. User makes a search on the website (Search)</p><p>4. User views details of a product (View Content)</p><p>5. User adds the product to the cart (Add to Cart)</p><p>6. User purchases the product (Purchase)</p><h4><strong>Data Understanding</strong></h4><p>The variables are the same in both groups. There are totally 10 variables (10 columns): “Campaign Name”, “Date”, “Spend[USD]”, “# of Impressions (the number of times an ad is displayed)”, “Reach (the number of unique people who saw an ad)”, “# of Website Clicks (the number of clicks on ad links directed to Advertiser’s website)”, “# of Searches”, “# of View Content”, “# of Add to Cart”, “# of Purchase”. There are equal number of observations in both groups (30 rows each).</p><p>The most important metric for analyzing success for the customer is “# of Purchases”.</p><p>Other metrics that are widely used and compared are CTR (Click Through rate), CPA (Cost per Action), CR (Conversion rate):</p><p><strong>Click Through Rate: </strong>Number of Website Clicks / Number of Impressions</p><p><strong>Cost per Action: </strong>Spend / Number of Actions</p><p><strong>Conversion Rate: </strong>Number of Actions / Number of Website Clicks</p><p><strong>Action: </strong>Can be any conversion event, such as Search, View Content, Add to Cart and Purchase.</p><h4><strong>Data Pre-processing</strong></h4><p>When analyzing the data-set, it is found that:</p><p>Control group has one NA row. This row has only Date and Spend values, other values are missing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*zasKX4PstmPLt7UdMi8oAA.png" /></figure><p>The mean values of these variables are assigned to their own NA values respectively:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*bY8XHh1-B3gTR5pDLfxVXA.png" /></figure><p>It is found that there is no outlier in the “# of Purchase” variable of the control group. Test group does not have any missing values. However, it has one outlier in # of Purchases:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*BLAxwJY9mFYouf6zI36-9A.png" /><figcaption>Figure-1: Box-plot of “# of Purchase” variable of the test group</figcaption></figure><p>This value is repressed by assigning the upper bound value to it. Upper bound value is found by Box-plot method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dN2QEQkEUWmnFDZvIF5JMA.png" /></figure><p>Now we have no outliers in test group as well. The data-set is ready for hypothesis testing.</p><p>· Group A: Existing method: Maximum Bidding — Control Group</p><p>· Group B: New method: Average Bidding — Test Group</p><h4><strong>Hypothesis Testing</strong></h4><p>Control Group has 507 purchases in average and test group has 481 purchases in average, meaning Control group has more purchases in average. However, we need to check if this is a significant difference. For this, we need to make hypothesis test. As we have independent and paired sample groups, we can use T-testing for Hypothesis test. A t-test is a statistic method used to determine if there is a significant difference between the means of two groups based on a sample of data. The common assumptions made when doing a t-test include normality of data distribution and equality of variance in standard deviation.</p><p>1. Normality of data distribution</p><p>2. Equality of variances</p><p><strong>1) Controlling 1st Assumption:</strong></p><p>Shapiro test is applied for checking the first assumption. The hypothesis is constructed as follows:</p><p>H0: The data is normally distributed</p><p>H1: The data is not normally distributed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*7sls8sFhjhyr_PzyRiHViA.png" /></figure><p>The results of the test are found as follows:</p><p>· p-value of group A is 0.979 which is &gt;0.05 so we fail to reject H0 meaning that group A is normally distributed.</p><p>· p value of group B is 0.776 which is &lt;0.05 so we fail to reject H0 meaning that group B data is normally distributed.</p><p>As a result of Shapiro test, it is seen that the normality assumption has been satisfied.</p><p><strong>2) Controlling 2nd Assumption:</strong></p><p>Levene test is applied for checking the first assumption. The hypothesis is constructed as follows:</p><p>H0: The variances are equal(homogeneous)</p><p>H1: The variances are unequal(non-homogeneous)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*wEmB6eobaxlX6b1dXTqHhQ.png" /></figure><p>As the p-value has been found as 0.11 which is &gt;0.05, we fail to reject H0 meaning that the variances of both groups are equal variances.</p><p>As the normality and equal variance of distributions assumptions are satisfied, we can use Independent Two-Sample T-Test for testing the hypothesis:</p><h4><strong>For 2-T test, the hypothesis is as follows:</strong></h4><p><strong>H0: </strong>There is no statistically significant difference between control and test groups with respect to the average of Number of Purchases ( μ1=μ2 )</p><p><strong>H1: </strong>There is statistically significant differences between control and test groups with respect to the average of Number of Purchases (μ1 ≠ μ2 )</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*-x3kGOTS-T2UiRJux2-trQ.png" /></figure><p>After tests are applied, the p value resulted in more than 0.05 significance level. Therefore, the result is “fail to reject H0” that is there is no statistically significant difference between control and experiment groups with respect to the average of Number of Purchases (μ1=μ2).</p><h4><strong>Analyzing Other Metrics by Hypothesis Testing:</strong></h4><p>More metrics have been tested to see if the new method is better or not. The metrics that were analyzed are Click through rate (CTR), CPA (Cost per Action) and Conversion Rate (CR). When comparing rates in two independent groups, independent 2-sample proportion test is used.</p><p><strong>1)</strong> <strong>CTR:</strong></p><p>CTR= Number of Website Clicks / Number of Impressions</p><p>The proportions are calculated for both groups. Control group’s CTR is found as 0.045 and Test group’s CTR is found as 0.044. There is slight difference between two groups’ CTR values and the control group has bigger rate. Let’s see if this difference is statistically significant. The hypothesis is constructed as follows:</p><p><strong>H0:</strong> There is no statistically significant difference between control and test group CTR rates.</p><p><strong>H1</strong>: There is a statistically significant difference between control and test group CTR rates<strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*bpCkqUhkXdIl0zHw2th99Q.png" /></figure><p>As a result, the p-value found smaller than 0.05 meaning that we reject the null hypothesis. When bidding methods are examined, there is a statistically significant difference between CTR rates. And this difference is in favor of the control group (current existing “max bidding” method).</p><p><strong>2)</strong> <strong>CPA:</strong></p><p>CAP= Spend / Number of Actions = Spend/Number of Purchases</p><p>Number of actions is taken as the number of the purchases in this calculation.</p><p>The proportions are calculated for both groups and found as follows:</p><p>Control group’s CPA is found as 5, it means that a customer’s one purchase costed us 5 USD in average. Test group’s CPA is found as 5.23, it means that a customer’s one purchase costed us 5.23 USD in average.</p><p>The hypothesis is constructed as follows:</p><p><strong>H0:</strong> There is no statistically significant difference between control and test group CPA rates.</p><p><strong>H1</strong>: There is a statistically significant difference between control and test group CPA rates<strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*Nhb80iMtpynSlMvhKhy5VQ.png" /></figure><p>The p-value has been found smaller than 0.05. We reject H0 meaning that there is statistically meaningful difference between two groups CPA values.</p><p>We can say that the existing method: max bidding is better than the new one as it has cheaper cost per purchase. So still, we cannot say that the new method is better than the existing one. Lastly, CR has been tested.</p><p><strong>3)</strong> <strong>CR:</strong></p><p>Conversion Rate: Number of Actions / Number of Website Clicks</p><p>For number of actions, 3 different metrics have been analyzed:</p><p><strong>Firstly,</strong> the proportions (“# of Purchase”/”# of Website Clicks”) are found as follows:</p><p>Control CR= 0.098</p><p>Test CR= 0.099</p><p>The hypothesis is constructed as follows:</p><p><strong>H0: </strong>There is no statistically significant difference between control and test group CR values.</p><p><strong>H1</strong>: There is a statistically significant difference between control and test group CR values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*nmbEDAwrrnepcI7gfZ7qng.png" /></figure><p>As a result, we fail to reject the null hypothesis meaning that there is no statistically significant difference between control and test groups with respect to the first CR.</p><p><strong>Secondly, </strong>the proportions (“# of Purchase”/”# of Add to Cart”) are found as follows:</p><p>Control CR2= 0.512</p><p>Test CR2= 0.588</p><p>This result shows that the occurrence number of buying items after they are added into cart is more in test group. Let’s see if this is significant difference.</p><p>The hypothesis is constructed as follows:</p><p><strong>H0: </strong>There is no statistically significant difference between control and test group CR2 values.</p><p><strong>H1</strong>: There is a statistically significant difference between control and test group CR2 values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*cLbosiUzpXefFEv6RtKfrQ.png" /></figure><p>As a result, p-value has been found lower than&lt; 0.05. We reject H0 meaning that there is statistically meaningful difference between two groups CPA values and the difference is in favor of the new method.</p><p>It is the first result that has ever favored the new method.</p><p>Let’s check the final CR:</p><p><strong>Lastly, </strong>the proportions (“# of Purchase”/”# of View Content”) are found as: Control CR3= 0.334 and Test CR3= 0.345</p><p>Test group has better rate but let’s see if this is significant by applying Hypothesis testing:</p><p><strong>H0: </strong>There is no statistically significant difference between control and test group CR3 values.</p><p><strong>H1</strong>: There is a statistically significant difference between control and test group CR3 values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*0r54tEBvJQp48JC6791qGA.png" /></figure><p>As a result, the p-value (0.567) has been found bigger than 0.05. We fail to Reject H0 meaning that there is not statistically meaningful difference between two groups. We cannot conclude anything in here.</p><h3><strong>Results</strong></h3><p>Based on my analysis, I would recommend to client to collect more data for few more months before drawing any conclusions. If there is no chance (no time, no budget etc.), it is not suggested to use the new bidding type (average bidding). Because:</p><ul><li>Average spend value of new method is more that the existing one. No need to spend more while there is no significant difference between two models:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*PHbXeDJboKgAKQAbXhE9Vw.png" /><figcaption>Figure-2: Avg. Spend values of both groups</figcaption></figure><ul><li># of purchase is decreasing when using the new method:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*-BxTWQy08QB5GGCEf3Hs1w.png" /><figcaption>Figure-3: Avg. # of purchase values of both groups</figcaption></figure><ul><li># of clicks is decreasing when using the new method:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*jSa_aPv_izsyJ7IIzDTFJw.png" /><figcaption>Figure-4: Avg. # of clicks of both groups</figcaption></figure><p>As a result, it doesn’t bring more conversions than existing bidding type (max bidding). I recommend to the client to continue with existing bidding type if a decision must be made now.</p><p>In this article, I have given brief information about A/B Testing and where it is used in real life. I have also applied it on a real data-set to compare two advertisement methods. I hope this article will be helpful for you to understand A/B Testing and its applications. You can reach to the full code from my GitHub account:</p><p><a href="https://github.com/bsrymn/AB-Test/blob/master/CaseStudyAB-Test_BusraYaman.ipynb">https://github.com/bsrymn/AB-Test/blob/master/CaseStudyAB-Test_BusraYaman.ipynb</a></p><p>See you in my next articles!!</p><h3>REFERENCES</h3><ul><li><a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.ttest_ind.html">https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.ttest_ind.html</a></li><li>Veri Bilimi Okulu (Data Science School) Class Notes</li><li><a href="https://hbr.org/2017/06/a-refresher-on-ab-testing">https://hbr.org/2017/06/a-refresher-on-ab-testing</a></li><li><a href="https://medium.com/@ng.dasci/ger%C3%A7ek-verilerle-ab-testi-uygulamas%C4%B1-yeni-reklam-teklif-y%C3%B6ntemi-sat%C4%B1n-alma-say%C4%B1s%C4%B1n%C4%B1-artt%C4%B1rd%C4%B1-m%C4%B1-f9cdd45cdb21">https://medium.com/@ng.dasci/ger%C3%A7ek-verilerle-ab-testi-uygulamas%C4%B1-yeni-reklam-teklif-y%C3%B6ntemi-sat%C4%B1n-alma-say%C4%B1s%C4%B1n%C4%B1-artt%C4%B1rd%C4%B1-m%C4%B1-f9cdd45cdb21</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ec58f8280f9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/a-b-test-application-on-real-data-8ec58f8280f9">A/B Test Application on Real Data</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RFM Analysis for Customer Segmentation]]></title>
            <link>https://medium.com/@yamanbsr/rfm-analysis-for-customer-segmentation-29c8c7e04f5c?source=rss-83d3c80f5f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/29c8c7e04f5c</guid>
            <category><![CDATA[rfm-analysis]]></category>
            <category><![CDATA[customer-segmentation]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Busra Y.]]></dc:creator>
            <pubDate>Mon, 06 Jul 2020 12:56:53 GMT</pubDate>
            <atom:updated>2023-08-06T10:54:36.904Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*tgQygtN_7XM682eR.jpg" /></figure><p>Hello data enthusiasts!</p><p>I am back with another article. In this post, I will describe RFM analysis and show how to use it for customer segmentation by analyzing a online retail shop’s data set on python. Based on the results of RFM analysis, I will exemplify what kind of actions can be taken for different kinds of customers. <br>Let’s start with background information!</p><h3>What is RFM?</h3><p>RFM is abbreviation for Recency, Frequency and Monetary. It is a technique that helps determine marketing and sales strategies based on customers’ buying habits.</p><p><strong>Recency: </strong>Time passed since the customer’s last purchase. In other words, it is the “time passed since the last contact of the customer”.</p><p>It is found from the formula:</p><p>Recency= RFM analysis date — Last purchase date</p><p>For example, if we are doing this analysis today, then the analysis date is today’s date.</p><p><strong>Frequency:</strong> Total number of purchases. It shows how frequently the customer does shopping. It can be found from the number of the invoices that one customer has.</p><p><strong>Monetary (Monetary Value):</strong> Total spending by the customer.</p><p>Customer segmentation is the process of separating these values into groups by scoring between 1 and 5. Depending on these scores, the customers are segmented into different groups. These groups can be shown on the Recency and Frequency Grid as the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/0*JJBP4ToZiaw0HVPN.png" /></figure><p>A low recency and frequency score (bottom left) shows the hibernating customers who haven’t been purchased anything recently or frequently. A high recency and frequency score (top right) shows the champions who have been recently and frequently purchasing.</p><p>Users are ranked by a score of 1 through 5, based on their percentile, with 5 being the highest and 1 being the lowest:</p><ul><li>Champions [R(4–5), F(4–5)]</li><li>Loyal Customers [R(3–4), F(4–5)]</li><li>Potential Loyalists [R(4–5), F(2–3)]</li><li>Promising [R(3–4), F(0–1)]</li><li>Can’t Lose Them [R(1–2), F(4–5)]</li><li>At Risk [R(1–2), F(3–4)]</li><li>About to Sleep [R(2–3), F(1–2)]</li><li>Hibernating [R(1–2), F(1–2)]</li><li>New Customers R [(4–5), F(0–1)]</li><li>Need Attention R [(2–3), F(2–3)]</li></ul><p>After deciding which customers belong to which group, customer-specific sales and marketing techniques are developed.</p><p>Now, I will apply RFM analysis an online retail shop’s data set and I will suggest few marketing strategies based on different customer segments. This analysis is done by using Python. You can find my code in Kaggle:</p><p><a href="https://www.kaggle.com/busrayaman/customer-segmentation-with-rfm-analysis">https://www.kaggle.com/busrayaman/customer-segmentation-with-rfm-analysis</a></p><h3>Business Case: RFM Analysis on an Online Retail data set</h3><p>An e-commerce company which sells souvenirs wants to segment its customers and determine marketing strategies according to these segments.</p><p>For this purpose, we will define the behavior of customers and we will put the customers into same groups who exhibit common behaviors and then we will try to develop sales and marketing techniques specific to these groups.</p><p>The data set “online_retail_II” includes the sales of this online shop between 01/12/2009 – 09/12/2011. For this study, the data of the year 2010–2011 is chosen.</p><p><strong>Variables:</strong><br><strong>InvoiceNo: </strong>Invoice number. It is a unique value. If this code starts with C, it means refund.<br><strong>StockCode:</strong> Product code. Unique number for each product<br><strong>Description:</strong> Product name<br><strong>Quantity:</strong> Number of products. It means how many of the products in the invoices are sold. Those who start with C get negative value<br><strong>InvoiceDate:</strong> Invoice date and time<br><strong>UnitPrice:</strong> Product price (in pounds)<br><strong>CustomerID:</strong> Customer number. Unique number for each customer<br><strong>Country:</strong> Country name. Refers to the country where the customer lives</p><h4>Data Understanding</h4><p>First we need to import required libraries:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*a1cFiQHzHtbWv32VCLPmlg.png" /></figure><p>Reading the input excel file’s sheet ‘Year 2010–2011’ and saving it as data frame ‘df_2010_2011’:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zA88B1oznE2nqTdpY0Mc8g.png" /></figure><p>Then this data frame’s copy is assigned to a data frame called ‘df’ so that we can keep the initial original data frame just in case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iZSQE05U-Kg1kP3KvyonDw.png" /></figure><p>We try to understand the data by using the functions that can be used as a first look at the data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*X5VpMk5VHkDDLuk_rYnY5A.png" /></figure><p>The customer ID type is float so we have converted it to integer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5genvkfmecJPi4o0JNp_Dg.png" /></figure><p>Let’s check how many products we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*ASwNw_kNoHqXIYkbdRyPOQ.png" /></figure><p>Let’s check if we have null values and if we have, we will drop them as we cannot analyze them in the RFM analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*aIsYYpTrcPXbw0g98INJIA.png" /></figure><p>Let’s find out how many invoices are there:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*mS5rFReKO0vdyWWj4pRZtA.png" /></figure><p>How much money has been earned per invoice? It is necessary to create a new variable by multiplying two variables ‘Quantity’ and ‘Price’:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sXprGkYdB73H9xA-XoVKhQ.png" /></figure><h4>Data Preparation</h4><p>In the previous section, we tried to understand the data set. In this section, we will prepare the data set for RFM analysis.</p><p>First, we have removed the rows with refund invoices that starts with ‘C’ and assign it to a new data frame:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NQNQ62haTdS9jh_T5KrKJg.png" /></figure><p>Then we have checked its shape, info and its statistical information:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p021EaDqxpTRx4W3IibyZw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*VEgBSDNOczseKNGOr4OX6g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kSEG---l6kytvhjIV1kMlg.png" /></figure><h4>Customer Segmentation with RFM Scores</h4><ol><li><strong>Finding the Recency values:</strong></li></ol><p>Let’s see the earliest and the latest purchase dates of our data set:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*VQNVohwT2B6j5ZkR_GkSAQ.png" /></figure><p>Now if we take today’s date as the analyse date, then there will be a very serious difference. For this reason, we have set the next day of the maximum day of the data set as the analyse date (today’s date). Now, we can find the recency scores according to the day of the last recording:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*sFpPemY9dCc5ZO59JoaFLA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*qaIRbTANm4oovniPvCKlcw.png" /></figure><p>For each customer, we need to subtract the customers’ last purchase date from today’s date and we will keep this as a temporary data frame:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*zzHWtB_UQjvLZimGIxqWhA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*Fs4Wai8o10UjHSRwTOG3Yg.png" /></figure><p>We have changed the name of column ‘InvoiceDate’ to ‘Recency’:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*-zI7xzFKrz90Hdpret3kMg.png" /></figure><p>We will capture every row and take the days. Since it is a variable in time type, it takes days when you say x.days, months when you say x.months, and years when you say x.years</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*KyU6bqFOisWwEWGRKVAL9g.png" /></figure><p><strong>2) Finding the Frequency values</strong></p><p>If we find the different number of invoices issued to each customer, we will find the total number of purchases of the customer. This is our frequency value.<br>Firstly, by grouping on the basis of Customer ID and Invoice Number, we observe how many times each invoice is multiplied on the basis of Customer. Let’s look at the random 5 observations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*7spqazG_IxMiWdy6Z8VC-Q.png" /></figure><p>Let’s find how many times the customer did shopping:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*DtLN6m2iO7RcXn1buYBB5w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*TsBdHLeK5nZFUg4PqAYXiA.png" /></figure><p>We assigned this to a new data frame called ‘freq_df’ and changed the ‘Invoice’ column name to ‘Frequency’:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*bKXYwSvw6O5B75XRj3w7Zw.png" /></figure><p><strong>3) Finding the Monetary values:</strong></p><p>Monetary is the total spend of the customer. The sum of the ‘TotalPrice’ values, which we have calculated for each customer and added as a new column before, is that customer’s monetary value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*6nyfLpaNazILAluRaqlPGA.png" /></figure><p>We have changed the ‘TotalPrice’ column name to ‘Monetary’:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*FshP3bYJ7TUnG3grq1ettg.png" /></figure><p><strong>4) Defining the score values:</strong></p><p>Lets bring all the values together under a new data frame called ‘rfm’:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*tf7jowPqQDOVfDRt21t7rA.png" /></figure><p>Normally the smallest of the recency scoring, which is 1, is the best recency score. However, we will define this in reverse and put the value 5 as the best recency value so that it will be in the same order as the others:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*r86rLoRyrA_WClyO8hXxrA.png" /></figure><p>For frequency, using ‘qcut’ method gave out an error, so I have used ‘cut’ method and manually defined the cut values. I have checked the statistical information of frequency values to cut the data frame as equal as possible. I got the values of 0, ‘min’, 50%, 60%, 90% and ‘max’ as the cut values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*0ZuMDJx7LPey94QE5Ks8XA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*rBjjDmvV2GPV7iChVZT_6w.png" /></figure><p>The monetary values are scored from 5 as the best to 1 as the worst:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*aewM--8lOlK6Sz-a6L-s1A.png" /></figure><p>A new column for rfm scores are added to the data frame as a new column:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tkZxyutbh77zxogWxAXN2A.png" /></figure><p>Let’s see the best and the worst customers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*6hUeTeikJSFZJRe5mp23nQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*hCW4rGLMh6Gy-6FUsnGVJw.png" /></figure><p>To segment the customers using “Recency” and “Frequency” values, we have set up regular expression (regex) structure by using dictionaries to name customer segments according to their Recency and Frequency Scores:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*oBgnSoeengmQK6Pjw3I1Ng.png" /></figure><p>As the monetary is a similar value to frequency, it is not considered in scoring. Recency and frequency points are obtained with the following code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*cmeA8tLaVBxDCG28GVxi-g.png" /></figure><p>Pull the value corresponding to the ranges of the score in the dictionary defined in ‘seg_map’, and add it as a new column named “Segment”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*HxKDma6rafFKBouTpZvzhg.png" /></figure><p>Now our data frame is ready and all the customers are grouped. We can retrieve data of all the groups one by one and save them as new data frames. For example, let us do this for the ‘Need Attention’ segment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*cqOW9aa7_44Jt0G65Csedw.png" /></figure><p>We will save this group as a new data frame named ‘need_attention_df’:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*t-MGu6Y7sV557hI3b_7uyA.png" /></figure><p>We can convert this data frame to an excel file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*ljsOeh7tFNf101Uo3wtoxw.png" /></figure><p>Same process can be done for the all the segments. We can send this excel files to Sales and Marketing Department so that they can take further actions.</p><h4>Comments and Actions</h4><p>Let’s retrieve statistical values of recency, frequency and monetary values according to the customer segments:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*TI663EigPiRlkh3ZFgte6Q.png" /></figure><p>To exemplify, we can choose the 3 groups to suggest actions for them.</p><ol><li><strong>Can’t Lose Segment [R(1–2), F(4–5)]:</strong></li></ol><ul><li>There are 12 customers in this group.</li><li>They have not been shopping for an average of 136.83 days.</li><li>They shopped an average of 14.92 times.</li><li>We have gained an average of 4150.68 pounds from them.</li></ul><p>This is a group we need to re-gain no matter because they are the customers which frequently shopped for big amounts but long time ago. We need to remind ourselves to them. We can send them campaign mails where we offer discounts on the products similar to what they have bought before. We can also send small surveys to get feedback about their shopping experience. We can make corrections based on the survey results. We can offer them renewals or newer products as well.</p><p><strong>2. Need Attention Segment R [(2–3), F(2–3)]:</strong></p><ul><li>There are 121 customers in this group.</li><li>They have not been shopping for an average of 50.29 days.</li><li>They shopped an average of 3 times.</li><li>We have gained an average of 1167.57 pounds from them.</li></ul><p>These customers have average recency and frequency scores. We can win them with small effort because they have spent good amount of money per transaction and this means the product prices is not a big issue for them. They just stopped shopping for some reason so we need to find out the reason for it and we can remind ourselves to them by offering them special discounts and free fast deliveries for limited time. This way, we can increase their shopping frequencies. We can also let them know that they are only few steps away from becoming a loyal customer where we can offer more discounts. This can encourage them to buy more frequently.</p><p><strong>3. At Risk Segment [R(1–2), F(3–4)]:</strong></p><ul><li>There are 380 customers at risk.</li><li>They have not been shopping for an average of 135.37 days.</li><li>They shopped an average of 4 times.</li><li>We have gained an average of 1603.31 pounds from them.</li></ul><p>These are the customers who have not shopped for a long time. They are the most important group to pay attention after the ‘can’t lose’ group because this group also shopped frequently but long time ago. Now, they are about to leave us. We can contact them by email or by phone to find out the reason why they have stopped buying from us. Seeing the average amount of their purchases, it seems the money is not the main problem for them. It could be the delivery problems or offers from the competitors. We can offer them better and more convenient delivery terms (cheaper and faster). We can offer them big discounts for their purchases over a certain amount. They might have problems with the products they have purchased so we can offer them renewals or provide them helpful manuals.</p><h3>Conclusion</h3><p>RFM analysis, which is based on customers’ past behavior, is a powerful and frequently used method for companies. Understanding it and knowing how to use it is very important for increasing the sales because it helps to understand your customers and develop personalized marketing strategies for them.</p><p>I hope I could explain clearly how to make RFM analysis on a data set by using python in this article. See you in my following articles!</p><h3>References:</h3><ol><li>Veri Bilimi Okulu (Data Science School) Class Notes:</li></ol><p><a href="https://www.veribilimiokulu.com/vbo-ekibi/">https://www.linkedin.com/in/veribilimiokulu/</a></p><p><a href="https://clevertap.com/blog/automate-user-segmentation-with-rfm-analysis/">2. https://clevertap.com/blog/automate-user-segmentation-with-rfm-analysis/</a></p><p><a href="https://www.blastanalytics.com/blog/rfm-analysis-boosts-sales">3. https://www.blastanalytics.com/blog/rfm-analysis-boosts-sales</a></p><p>4. The online retail data set is retrieved from the following page:</p><p><a href="https://www.kaggle.com/hikne707/online-retail">https://www.kaggle.com/hikne707/online-retail</a></p><p>5. My data set:</p><p><a href="https://www.kaggle.com/busrayaman/customer-segmentation-with-rfm-analysis">https://www.kaggle.com/busrayaman/customer-segmentation-with-rfm-analysis</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29c8c7e04f5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developing a marketing strategy by using Apriori Algorithm]]></title>
            <link>https://medium.com/@yamanbsr/developing-a-marketing-strategy-by-using-apriori-algorithm-5e50cac0982c?source=rss-83d3c80f5f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e50cac0982c</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[market-basket-analysis]]></category>
            <category><![CDATA[apriori-algorithm]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[marketing-strategies]]></category>
            <dc:creator><![CDATA[Busra Y.]]></dc:creator>
            <pubDate>Fri, 26 Jun 2020 10:35:51 GMT</pubDate>
            <atom:updated>2020-06-26T10:40:16.071Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VienU-NILjOkvBTt.jpg" /></figure><p>Hello again data enthusiasts!</p><p>In my first post, I have tried to explain the logic of association rules and the Apriori Algorithm by doing a small market basket analysis on excel. I highly recommend you to read it to understand the theory. You can reach to my first post from the link below:</p><p><a href="https://medium.com/biztech/developing-a-marketing-strategy-by-using-apriori-algorithm-and-association-rules-on-datasets-675630eed4f5">https://medium.com/biztech/developing-a-marketing-strategy-by-using-apriori-algorithm-and-association-rules-on-datasets-675630eed4f5</a></p><p>Now I will apply Apriori Algorithm on a grocery shop’s data set by using Python in this post. So let’s start it!</p><h3>Business Problem:</h3><p>A grocery shop wants to develop a marketing strategy to increase the product sales. They have the record of the shopping transactions. What can we recommend to them based on their transaction data set?</p><ol><li><strong>Data Understanding and Pre-processing:</strong></li></ol><p>First, we import the necessary libraries into the code to be able to use their methods and functions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*6wS6XNafjtr0ZOi0BTNBiw.png" /></figure><p>Then the data set is put to the code as the input:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*764e5j1LijMZvtyHYlBXlg.png" /></figure><p>To see what we have read from the file, we write ‘df.values’ method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*l44HCW6dgyKVRDqwFn8O6Q.png" /></figure><p>The apriori method of the mlxtend library accepts the data sets as a True-False data frames. Therefore, we need to convert the raw data set to a format that this method can process. We separate all the items with ‘,’ so that each item can be recognized separately. The code for this is as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*AFTQlnEVpDOSuWRF7k41Zg.png" /></figure><p>The data frame that we have now is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*yEzjVLtL4Pwz3OvAe8Gp0A.png" /></figure><p>Each row in this data frame is a shopping transaction. For example, in the first row, there are milk, bread and biscuit which means that in the first transaction, milk, bread and biscuit are bought.</p><p>We will now create the ‘True’ and ‘False’ data frame. ‘True’ values will be assigned to the items which are bought in the corresponding shopping transaction; ‘false’ will be assigned to the rest of the items which are not bought in that transaction. To do this and to assign each product as the column variables uniquely, we need to import ‘Transaction Encoder’ method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*lOZsYZFxEWL0TdCL1rW7eQ.png" /></figure><p>Then we defined the TransactionEncoder method as a shorter name: te. And then we converted our data frame into a True-False date frame with the following code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*hVkj3XN7Jwv95amkXseJww.png" /></figure><p>The True-False data frame we have obtained is as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*P8tFUcE2ysJZsNbfiGvxsw.png" /></figure><p><strong>2. Applying Apriori Method:</strong></p><p>We will apply the Apriori method to our data set. We have defined the minimum support value as 0.15 meaning that all the combinations which has support value below 0.15 will be eliminated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*jiIc1ug8kcvBgHGxSu-Ivg.png" /></figure><p>In the output of the Apriori method, we get the support values of each combination in the whole data set. For example, in the output below, only the support of “BISCUIT” in the whole data set is 0.35, while the support value of “BISCUIT and BREAD” in the whole data set is 0.20.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*bSEH4urifR1UQX4kL8TbWg.png" /></figure><p>We can sort the data frame from the item with the highest support value to the one with the lowest support value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*VWeoOefkCMq-AnENu2dXqg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*JYhTAYTwYUXL0xcNXt7bfA.png" /></figure><p>We can see from the above table that most frequently bought product is Bread with its support value of 0.65. This means 65% of all the shopping transactions includes Bread. Bread is followed by coffee which has support value of 0.4 meaning that 40% of all the shopping transactions includes coffee.</p><p><strong>3. Application of Association Rule:</strong></p><p>Association_rules method of the mlxtend library will be applied to our recent data frame (df3) and we will assign it as a new data frame named ‘AR’. The minimum confidence value is defined as 0.6 in the function. This will bring us the combinations which has confidence level larger than or equal to 0.6:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*1fxvDtP35h-f_88mkXzFIw.png" /></figure><p>With Association rule method, we have obtained the following table which shows the support, confidence and lift values of all combinations which satisfy the minimum confidence and support values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*WQG4zz4j618v0eWy_ENuRA.png" /></figure><p>To filter our table further, we can eliminate some more combinations. Let’s filter our data to bring the combinations which has support value of 0.15 or more and confidence value of 0.75 or more:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*tB7FKIVbefB0RDEp22IMlw.png" /></figure><p>After this filtering, as a final table, we have obtained the following 3 combinations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*TobCL4u98W6lKQhWTR8MJA.png" /></figure><h3>Conclusion</h3><h4>Comments:</h4><p>From the final table, we can make the following comments:</p><p><strong><em>For MILK-BREAD pair:</em></strong></p><p>antecedent support=0.25: Milk is observed in 25% of all the purchases.</p><p>consequent support=0.65: Bread is observed 65% of all the purchases.</p><p>support=0.20 : Milk and Bread are observed together in 20% of all purchases.</p><p>confidence=0.8: If Milk is bought, Bread is 80% likely to be bought as well.</p><p>Lift=1.23: That means Milk and Bread affects each other’s sales positively. Sales of Bread increase by 1.23 times in transactions which contains Milk or visa versa.</p><p><strong><em>For COKE-COFFEE pair:</em></strong></p><p>antecedent support=0.15: Coke is observed in 15% of all the purchases.</p><p>consequent support=0.40: Coffee is observed 40% of all the purchases.</p><p>support=0.15: Coke and Coffee are observed together in 15% of all purchases.</p><p>confidence=1: If Coke is bought, Coffee is 100% likely to be bought as well.</p><p>Lift=2.5: That means Coffee and Coke affects each other’s sales positively. Sales of Coke increase by 2.5 times in transactions which contains Coffee or visa versa.</p><p><strong><em>For MAGGI-TEA pair:</em></strong></p><p>antecedent support=0.25: Maggi is observed in 25% of all the purchases.</p><p>consequent support=0.35: Tea is observed 35% of all the purchases.</p><p>support=0.20 : Maggi and Tea are observed together in 20% of all purchases.</p><p>confidence=0.8: If Maggi is bought, Tea is 80% likely to be bought as well.</p><p>Lift=2.286: That means Maggi and Tea affects each other’s sales positively. Sales of Maggi increase by 2.286 times in transactions which contains Tea or visa versa.</p><h4>Suggestions:</h4><p>It can be concluded from these results that ‘Milk and Bread’, ‘Coke and Coffee’ and ‘Maggie and Tea’ can be put in close sections of the shop as a marketing strategy to increase the sales.</p><p>If what we have is an e-shop, these 3 product pairs can be offered together in the recommendation system. For example, if you put Milk into your basket, there could appear a message “People who bought Milk also bought Bread. Do you want to add it into your basket as well?”. If you put Coke into your basket, there could appear a message “People who bought Coke also bought Coffee. Do you want to add it into your basket as well?”. If you put Maggi into your basket, there could appear a message “People who bought Maggi also bought Tea. Do you want to add it into your basket as well?”.</p><p>With a quick analysis on shopping transactions list, we came up with a marketing strategy which is to put the products that are frequently purchased together, close to each other in the shop. We also defined a recommendation system for online shopping: which is to recommend other products that are frequently purchased together with the product that the customer is viewing. These strategies can help to increase the sales. Because with this way, we can help customers find the products in an easy way or remind them what to buy while shopping.</p><p>I hope my consecutive two posts are helpful for you to understand the Apriori Algorithm and how to apply it as Association Analysis on data sets by using Python.</p><p>See you in my next posts!!!</p><p><strong>Special thanks to my Data Science and Machine Learning teacher Mustafa Vahit Keskin:</strong><br><a href="https://www.linkedin.com/in/mvahitkeskin/">https://www.linkedin.com/in/mvahitkeskin/</a></p><p><strong>Special thanks to my long-time friend Nehir Gunce Dasci who encouraged me to take data science courses and helped me along the way: </strong><a href="https://www.linkedin.com/in/nehir-gunce-dasci/">https://www.linkedin.com/in/nehir-gunce-dasci/</a></p><p><strong>You can also follow her posts about Machine Learning on her medium account: </strong><a href="https://medium.com/@ng.dasci">https://medium.com/@ng.dasci</a></p><h3>References</h3><ol><li><strong>Veri Bilimi Okulu (Data Science School) Class Notes:</strong></li></ol><p><a href="https://www.veribilimiokulu.com/vbo-ekibi/">https://www.linkedin.com/in/veribilimiokulu/</a></p><p><strong>2. Introduction to arules — A computational environment for mining association rules and frequent item sets:</strong></p><p><a href="https://mran.revolutionanalytics.com/web/packages/arules/vignettes/arules.pdf">https://mran.revolutionanalytics.com/web/packages/arules/vignettes/arules.pdf</a></p><p><strong>3. My first post:</strong></p><p><a href="https://medium.com/biztech/developing-a-marketing-strategy-by-using-apriori-algorithm-and-association-rules-on-datasets-675630eed4f5">https://medium.com/biztech/developing-a-marketing-strategy-by-using-apriori-algorithm-and-association-rules-on-datasets-675630eed4f5</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e50cac0982c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apriori Algorithm and Association Analysis on data sets]]></title>
            <link>https://medium.com/@yamanbsr/developing-a-marketing-strategy-by-using-apriori-algorithm-and-association-rules-on-datasets-675630eed4f5?source=rss-83d3c80f5f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/675630eed4f5</guid>
            <category><![CDATA[apriori-algorithm]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[association-rule]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Busra Y.]]></dc:creator>
            <pubDate>Thu, 25 Jun 2020 19:27:16 GMT</pubDate>
            <atom:updated>2020-06-26T21:58:15.637Z</atom:updated>
            <content:encoded><![CDATA[<h3>Market Basket Analysis by using Apriori Algorithm</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Us0Eei9L-LmiCa1W.jpg" /></figure><p>Hello data enthusiasts!</p><p>In this post, I will explain the Association Analysis and Apriori Algorithm. To exemplify this, I will apply analyze a set of products by using Apriori Algorithm. Then I will come up with a marketing strategy based on the results. Hopefully, I will be able to give you an idea about how Apriori Algorithm works!</p><h3>Theory:</h3><p>Association rule is a machine learning technique used to find patterns (relationships, structures) in the data. Association analysis applications are among the most common applications in data science. It is also known as recommendation systems. We, as customers, come across with the recommendation systems on the internet in the following expressions: “people bought this product too” or “the ones who bought this item also bought this item” or “those who viewed that ad also looked at these ads” or “we created a playlist for you” or “recommended video for the next video”.<br>These scenarios are the most frequently encountered scenarios within the scope of e-commerce data science and data mining studies.<br>From all the world’s largest e-commerce companies like Amazon and Aliexpress or popular platforms like YouTube, Spotify and Netflix to many other websites use recommendation systems.</p><p>Aside from using recommendation systems on the websites, we can also use them on real life cases. For example, after analyzing the shopping transactions of one shop, depending on the analysis results, we can come up with a marketing strategy for increasing the sales of that shop.</p><p>So how do we do the association analysis? Association analysis is carried out by examining some metrics according to Apriori Algorithm. Apriori Algorithm is the most important set of Association rules which helps us to do association analysis.</p><p>The frequent item sets are determined by Apriori and these can be used to determine association rules which highlight general trends in the data sets.</p><p>Let’s learn the metrics used in Apriori algorithm:</p><p>X: product 1</p><p>Y: product 2</p><p>N: total number of shopping transactions</p><p>Freq(X): Frequency of X product in all the transactions</p><p>Freq(Y): Frequency of Y product in all the transactions</p><p>Freq(X,Y): Frequency of X and Y products bought together in all the transactions</p><p><strong>Support: </strong>Probability of buying X and Y products together:</p><p>Support(X, Y) = Freq(X,Y)/N</p><p><strong>Confidence:</strong> This says how likely item Y is purchased when item X is purchased.</p><p>Confidence(X, Y) = Freq(X,Y) / Freq(X)</p><p><strong>Lift: </strong>Shows how<strong> </strong>likely item Y is purchased when item X is purchased, while controlling for how popular item Y is.</p><p>Lift = Support (X, Y) / ( Support(X) * Support(Y) )</p><p>If the lift=1, it would imply no association between items. The probability of occurrence of the X and that of Y are independent of each other. When two events are independent of each other, no rule can be drawn involving those two events.</p><p>If the lift is &gt; 1, it would let us know the degree to which those two occurrences are dependent on one another, and it would show how likely item Y is <em>likely</em> to be bought if item X is bought.</p><p>If the lift is &lt; 1, that lets us know the items are substitute to each other. This means that presence of one item has negative effect on presence of other item and vice versa. This lift number shows how Y is <em>unlikely</em> to be bought if item X is bought.</p><p>Let’s try to understand how this works with a small example:</p><p>We have the following shopping transactions list:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*LyiVpD8mo_ADuJ13o_PYiA.png" /></figure><p><strong>Step 1</strong>: Define the frequency of each item and calculate the support values of each item:</p><p>The number of transactions is 5 that means N=5.</p><p>In the list, there are 2 occurrences of Milk so its frequency is 2. Diving its frequency by N will give us Milk’s support value:</p><p>Support(Milk)=Freq(Milk)/N=2/5=0.4</p><p>After applying this calculation to each item, we have the following list:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*8m1FMFck5Yq1PexdfgMylA.png" /></figure><p><strong>Step 2: </strong>Eliminate the items under the support value that you define</p><p>Let’s define the support threshold value as 0.4. Then we are going to eliminate the items which have support values under this threshold value. In this case, the eliminated items are Juice and Bread. We are left with the following table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*6c6oHhDaJAj3OYl2EiWsDQ.png" /></figure><p><strong>Step 3: </strong>Make a new list and define the support values</p><p>We are going to make a new list from the combinations of the remaining items which are Milk, Egg, Tea and Cola. And we are going to calculate their number of occurrences in the shopping list. Then we can find the support values of each combination. The new item list is as below and I am putting the shopping transactions list next to it to remember the transactions again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*v8G7dycw8yT2bxSsTorhjw.png" /></figure><p>As we can see from the transaction list, the number of occurrences of Milk and Egg together is 1 (seen only in the 3rd transaction) so Freq(Milk, Egg)=1. The support value of this combination is obtained by dividing Freq(Milk, Egg) to the number of transactions N meaning 1/5=0.2. So the Support(Milk, Egg)=0.2.</p><p>We did this for all the combinations and obtained the following table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*w2s5UNNuemDuEDDTfQozqg.png" /></figure><p><strong>Step 4:</strong> Eliminating the combinations according to the support threshold value of 0.4:</p><p>Milk-Egg and Milk-Cola combinations have support value of 0.2 so we eliminated these 2 combinations. So these pairs are left: Milk-Tea, Egg-Tea, Egg-Cola and Tea-Cola.</p><p><strong>Step 5:</strong> Create the new list of combinations and calculate the new frequency and support values accordingly:</p><p>From the pairs that we are left with, we will make new combinations. Then we will see how many times these combinations are seen in all the shopping transactions which will be defined as their frequencies. And then we calculate the support values of each combinations. For example, we have Milk, Tea and Cola combination. These 3 items are seen only once in all 5 transactions which means their frequency is 1 and their support value is 1/5=0.2. After applying this to each combination, we have the following table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*ZRnwo-IjzPVlpVCqr0DQhw.png" /></figure><p><strong>Step 6: </strong>Eliminating the combinations which have support values under 0.4:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*kT4nzOImD9nh-ll0fmo3_g.png" /></figure><p><strong>Step 7: Creating the final table and commenting on it:</strong></p><p>We will put all the items and item combinations which have 0.4 or bigger support value together. The final table is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*nSr7lUgeRxMfKh1GRzX-2Q.png" /></figure><p>The confidence and lift values are calculated from their formulas:</p><p>Confidence(X, Y) = Freq(X,Y) / Freq(X)</p><p>Lift = Support (X, Y) / ( Support(X) * Support(Y) )</p><p>For example, Milk-Tea pair confidence value is Freq(Milk, Tea)/Freq(Milk) which is 2/2= 1. Milk-Tea pair lift value is Support(Milk-Tea)/(Support(Milk) * Support(Tea)) which is 0.4/(0.4*0.6)= 1.67.</p><p>We can make the following comments depending on this result table:</p><p><em>For Milk-Tea pair:</em></p><p>Milk and Tea are observed together in 40 percent of all purchases.</p><p>If Milk is bought, Tea is 100% likely to be bought as well.</p><p>Lift(Milk-Tea)&gt;1: That means Milk and Tea affects each other’s sales. Sales of tea products increase by 1.67 times in shopping transactions which contains Milk.</p><p><em>For Egg-Tea pair:</em></p><p>Egg and Tea are observed together in 40 percent of all purchases.</p><p>If Egg is bought, Tea is 67% likely to be bought as well or visa versa..</p><p>Lift(Egg-Tea)&gt;1: That means Egg and Tea positively affects each other’s sales. Sales of Egg products increase by 1.11 times in shopping transactions which contains Tea.</p><p><em>For Egg-Cola pair:</em></p><p>Egg and Cola are observed together in 60 percent of all purchases.</p><p>If Egg is bought, Cola is 100% likely to be bought as well or visa versa..</p><p>Lift(Egg-Cola)&gt;1: That means Egg and Cola affects each other’s sales positively. Sales of Egg products increase by 1.67 times in shopping transactions which contains Cola.</p><p><em>For Tea-Cola pair:</em></p><p>Tea and Cola are observed together in 40 percent of all purchases.</p><p>If Tea is bought, Cola is 67% likely to be bought as well or visa versa.</p><p>Lift(Tea-Cola)&gt;1: That means Tea and Cola affects each other’s sales positively. Sales of Tea products increase by 1.11 times in shopping transactions which contains Cola.</p><p><em>For Tea-Egg-Cola trio:</em></p><p>Tea-Egg-Cola are observed together in 40 percent of all purchases.</p><p>If Tea is bought, Cola and Egg are 67% likely to be bought as well or visa versa.</p><p>Lift(Tea-Egg-Cola)&gt;1: That means Tea, Egg and Cola affects each other’s sales positively. Sales of each one increase by 1.85 times in shopping transactions which contains the other two.</p><p>It can be concluded from these results that Tea, Egg and Cola can be put in close sections of the shop as a strategy to increase the sales. If it is an e-shop, these 3 products can be offered together in the recommendation system. For example, if you put Tea into your basket, there could appear a message “People who bought Tea also bought Egg and Cola. Do you want to add them into your basket as well?” and the selections of egg and cola can be shown under this message.</p><p>With this small example, I hope you understood the logic of Association Analysis and the Apriori Algorithm. In my following post, I will apply Apriori Algorithm on a data set by using Python. You can reach to my following post from the below link:</p><p><a href="https://medium.com/@yamanbsr/developing-a-marketing-strategy-by-using-apriori-algorithm-5e50cac0982c">https://medium.com/@yamanbsr/developing-a-marketing-strategy-by-using-apriori-algorithm-5e50cac0982c</a></p><p>See you there!</p><h3>References</h3><p><strong>1. Data Set used in the analysis:</strong></p><p><a href="https://www.kaggle.com/shazadudwadia/supermarket">https://www.kaggle.com/shazadudwadia/supermarket</a></p><p><strong>2. My code:</strong></p><p><a href="https://www.kaggle.com/busrayaman/kernel1046500f72?scriptVersionId=37429413">https://www.kaggle.com/busrayaman/kernel1046500f72?scriptVersionId=37429413</a></p><p><strong>3. Veri Bilimi Okulu (Data Science School) Class Notes:</strong></p><p><a href="https://www.veribilimiokulu.com/vbo-ekibi/">https://www.linkedin.com/in/veribilimiokulu/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=675630eed4f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>