<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/a-gentle-introduction-on-market-basket-analysis%e2%80%8a-%e2%80%8aassociation-rules/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://datascienceplus.com/a-gentle-introduction-on-market-basket-analysis%E2%80%8A-%E2%80%8Aassociation-rules/"> R Programming – DataScience+</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>Market Basket Analysis is one of the key techniques used by large retailers to uncover associations between items. It works by looking for combinations of items that occur together frequently in transactions. To put it another way, it allows retailers to identify relationships between the items that people buy.</p>
<p>Association Rules are widely used to analyze retail basket or transaction data, and are intended to identify strong rules discovered in transaction data using measures of interestingness, based on the concept of strong rules.</p>
<h3>An example of Association Rules</h3>
<ul>
* Assume there are 100 customers<br>
* 10 of them bought milk, 8 bought butter and 6 bought both of them<br>
* bought milk => bought butter<br>
* support = P(Milk &amp; Butter) = 6/100 = 0.06<br>
* confidence = support/P(Butter) = 0.06/0.08 = 0.75<br>
* lift = confidence/P(Milk) = 0.75/0.10 = 7.5</ul>
<p>Note: this example is extremely small. In practice, a rule needs the support of several hundred transactions, before it can be considered statistically significant, and datasets often contain thousands or millions of transactions.</p>
<p>Ok, enough for the theory, let’s get to the code.</p>
<p>The dataset we are using today comes from <a rel="nofollow" href="http://archive.ics.uci.edu/ml/index.php" target="_blank">UCI Machine Learning repository</a>. The dataset is called “Online Retail” and can be found <a rel="nofollow" href="http://archive.ics.uci.edu/ml/datasets/online+retail" target="_blank">here</a>. It contains all the transactions occurring between 01/12/2010 and 09/12/2011 for a UK-based and registered online retailer.</p>
<h2>Load the packages</h2>
<pre>
library(tidyverse)
library(readxl)
library(knitr)
library(ggplot2)
library(lubridate)
library(arules)
library(arulesViz)
library(plyr)
</pre>
<h2>Data preprocessing and exploring</h2>
<pre>
retail &lt;- read_excel('Online_retail.xlsx')
retail &lt;- retail[complete.cases(retail), ]
retail % mutate(Description = as.factor(Description))
retail % mutate(Country = as.factor(Country))
retail$Date &lt;- as.Date(retail$InvoiceDate)
retail$Time &lt;- format(retail$InvoiceDate,&quot;%H:%M:%S&quot;)
retail$InvoiceNo &lt;- as.numeric(as.character(retail$InvoiceNo))
glimpse(retail)
<em>Observations: 406,829
Variables: 10
$ InvoiceNo 536365, 536365, 536365, 536365, 536365, 536365, 536365, 53...
$ StockCode &quot;85123A&quot;, &quot;71053&quot;, &quot;84406B&quot;, &quot;84029G&quot;, &quot;84029E&quot;, &quot;22752&quot;, ...
$ Description WHITE HANGING HEART T-LIGHT HOLDER, WHITE METAL LANTERN, ...
$ Quantity 6, 6, 8, 6, 6, 2, 6, 6, 6, 32, 6, 6, 8, 6, 6, 3, 2, 3, 3, ...
$ InvoiceDate 2010-12-01 08:26:00, 2010-12-01 08:26:00, 2010-12-01 08:2...
$ UnitPrice 2.55, 3.39, 2.75, 3.39, 3.39, 7.65, 4.25, 1.85, 1.85, 1.69...
$ CustomerID 17850, 17850, 17850, 17850, 17850, 17850, 17850, 17850, 17...
$ Country United Kingdom, United Kingdom, United Kingdom, United Ki...
$ Date 2010-12-01, 2010-12-01, 2010-12-01, 2010-12-01, 2010-12-0...
$ Time &quot;08:26:00&quot;, &quot;08:26:00&quot;, &quot;08:26:00&quot;, &quot;08:26:00&quot;, &quot;08:26:00&quot;...
</em>
</pre>
<p>After preprocessing, the dataset includes 406,829 records and 10 fields: InvoiceNo, StockCode, Description, Quantity, InvoiceDate, UnitPrice, CustomerID, Country, Date, Time.</p>
<h3>What time do people often purchase online?</h3>
<p>In order to find the answer to this question, we need to extract “hour” from the time column.</p>
<pre>
retail$Time &lt;- as.factor(retail$Time)
a % 
  ggplot(aes(x=Time)) + 
  geom_histogram(stat=&quot;count&quot;,fill=&quot;indianred&quot;)
</pre>
<p>Gives this plot:<br>
<a rel="nofollow" href="https://i0.wp.com/datascienceplus.com/wp-content/uploads/2017/09/basket_2.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i0.wp.com/datascienceplus.com/wp-content/uploads/2017/09/basket_2-490x227.png?w=450&ssl=1" alt="" class="wp-image-8692" data-recalc-dims="1"></a></p>
<p>There is a clear bias between the hour of day and order volume. Most orders happened between 10:00–15:00.</p>
<h3>How many items each customer buy?</h3>
<pre>
detach(&quot;package:plyr&quot;, unload=TRUE)
retail %>% 
  group_by(InvoiceNo) %>% 
  summarize(n_items = mean(Quantity)) %>%
  ggplot(aes(x=n_items))+
  geom_histogram(fill=&quot;indianred&quot;, bins = 100000) + 
  geom_rug()+
  coord_cartesian(xlim=c(0,80))
</pre>
<p>Gives this plot:<br>
<a rel="nofollow" href="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2017/09/basket_3.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2017/09/basket_3-490x228.png?w=450&ssl=1" alt="" class="wp-image-8693" data-recalc-dims="1"></a></p>
<p>People mostly purchased less than 10 items (less than 10 items in each invoice).</p>
<h3>Top 10 best sellers</h3>
<pre>
tmp % 
  group_by(StockCode, Description) %>% 
  summarize(count = n()) %>% 
  arrange(desc(count))
tmp % 
  ggplot(aes(x=reorder(Description,count), y=count))+
  geom_bar(stat=&quot;identity&quot;,fill=&quot;indian red&quot;)+
  coord_flip()
<em># A tibble: 10 x 3
# Groups: StockCode [10]
StockCode Description count
1 85123A WHITE HANGING HEART T-LIGHT HOLDER 2070
2 22423 REGENCY CAKESTAND 3 TIER 1905
3 85099B JUMBO BAG RED RETROSPOT 1662
4 84879 ASSORTED COLOUR BIRD ORNAMENT 1418
5 47566 PARTY BUNTING 1416
6 20725 LUNCH BAG RED RETROSPOT 1358
7 22720 SET OF 3 CAKE TINS PANTRY DESIGN 1232
8 POST POSTAGE 1196
9 20727 LUNCH BAG BLACK SKULL. 1126
10 21212 PACK OF 72 RETROSPOT CAKE CASES 1080
</em>
</pre>
<p>Gives this plot:<br>
<a rel="nofollow" href="https://i0.wp.com/datascienceplus.com/wp-content/uploads/2017/09/basket_4.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i1.wp.com/datascienceplus.com/wp-content/uploads/2017/09/basket_4-490x228.png?w=450&ssl=1" alt="" class="wp-image-8694" data-recalc-dims="1"></a></p>
<h2>Association rules for online retailer</h2>
<p>Before using any rule mining algorithm, we need to transform the data from the data frame format, into transactions such that we have all the items bought together in one row. For example, this is the format we need:</p>
<p><a rel="nofollow" href="https://i1.wp.com/datascienceplus.com/wp-content/uploads/2017/09/basket_7.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i1.wp.com/datascienceplus.com/wp-content/uploads/2017/09/basket_7-490x174.png?w=450&ssl=1" alt="" class="wp-image-8695" data-recalc-dims="1"></a></p>
<pre>
retail_sorted &lt;- retail[order(retail$CustomerID),]
library(plyr)
itemList &lt;- ddply(retail,c(&quot;CustomerID&quot;,&quot;Date&quot;), 
                       function(df1)paste(df1$Description, 
                       collapse = &quot;,&quot;))
</pre>
<p>The function ddply() accepts a data frame, splits it into pieces based on one or more factors, computes on the pieces, and then returns the results as a data frame. We use “,” to separate different items.</p>
<p>We only need item transactions, so remove customerID and Date columns.</p>
<pre>
itemList$CustomerID &lt;- NULL
itemList$Date &lt;- NULL
colnames(itemList) &lt;- c(&quot;items&quot;)
</pre>
<p>Write the data fram to a csv file and check whether our transaction format is correct.</p>
<pre>
write.csv(itemList,&quot;market_basket.csv&quot;, quote = FALSE, row.names = TRUE)
</pre>
<p><a rel="nofollow" href="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2017/09/basket_8.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i1.wp.com/datascienceplus.com/wp-content/uploads/2017/09/basket_8-490x171.png?w=450&ssl=1" alt="" class="wp-image-8696" data-recalc-dims="1"></a></p>
<p>Perfect! Now we have our transaction dataset, and it shows the matrix of items being bought together. We don’t actually see how often they are bought together, and we don’t see rules either. But we are going to find out.</p>
<p>Let’s have a closer look at how many transactions we have and what they are.</p>
<pre>
tr &lt;- read.transactions('market_basket.csv', format = 'basket', sep=',')
tr
summary(tr)
<em>transactions in sparse format with
19296 transactions (rows) and
7881 items (columns)
transactions as itemMatrix in sparse format with
19296 rows (elements/itemsets/transactions) and
7881 columns (items) and a density of 0.002200461 most frequent items:
WHITE HANGING HEART T-LIGHT HOLDER REGENCY CAKESTAND 3 TIER 1772 1667 JUMBO BAG RED RETROSPOT PARTY BUNTING 1445 1279 ASSORTED COLOUR BIRD ORNAMENT (Other) 1239 327226 element (itemset/transaction) length distribution:
sizes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 2247 1177 848 762 724 660 614 595 584 553 574 507 490 507 503 504 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 452 415 474 420 383 309 311 271 236 253 223 204 226 218 174 146 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 139 145 130 112 116 88 104 94 91 86 94 60 68 74 68 65 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 52 50 60 51 41 53 51 36 23 40 37 30 31 23 22 24 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 17 27 32 22 17 25 17 20 18 12 13 19 14 7 9 18 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 17 11 10 8 12 10 15 7 7 9 6 7 8 5 4 5 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 5 3 3 3 5 5 5 2 3 3 8 5 6 3 3 1 113 114 115 116 117 118 119 120 121 122 123 125 126 127 131 132 2 2 1 4 6 3 1 2 1 3 3 4 2 1 1 1 133 134 139 140 141 142 143 145 146 147 149 150 154 157 161 166 4 1 1 1 1 2 1 1 2 1 2 2 2 2 1 1 168 171 177 178 180 194 198 199 202 204 205 209 229 236 249 250 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 286 321 401 420 1 1 1 1 Min. 1st Qu. Median Mean 3rd Qu. Max. 1.00 4.00 12.00 17.34 23.00 420.00 includes extended item information - examples:
labels
1 1 HANGER
2 10 COLOUR SPACEBOY PEN
3 12 COLOURED PARTY BALLOONS
</em>
</pre>
<p>We see 19,296 transactions, and this is the number of rows as well. There are 7,881 items — remember items are the product descriptions in our original dataset. Transactions here are the collections or subsets of these 7,881 items.</p>
<p>The summary gives us some useful information:</p>
<ul>
* density: The percentage of non-empty cells in the sparse matrix. In another word, the total number of items that are purchased divided by the total number of possible items in that matrix. We can calculate how many items were purchased using density like so: 19296 X 7881 X 0.0022.<br>
* The most frequent items should be the same as our results in Figure 3.<br>
* Looking at the size of the transactions: 2247 transactions were for just 1 item, 1177 transactions for 2 items, all the way up to the biggest transaction: 1 transaction for 420 items. This indicates that most customers buy a small number of items in each transaction.<br>
* The distribution of the data is right skewed.</ul>
<p>Let’s have a look at the item frequency plot, which should be in aligned with Figure 3.</p>
<pre>
itemFrequencyPlot(tr, topN=20, type='absolute')
</pre>
<p>Gives this plot:<br>
<a rel="nofollow" href="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2017/09/basket_1.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i1.wp.com/datascienceplus.com/wp-content/uploads/2017/09/basket_1-490x228.png?w=450&ssl=1" alt="" class="wp-image-8697" data-recalc-dims="1"></a></p>
<h2>Create some rules</h2>
<ul>
* We use the Apriori algorithm in Arules library to mine frequent itemsets and association rules. The algorithm employs level-wise search for frequent itemsets.<br>
* We pass supp=0.001 and conf=0.8 to return all the rules that have a support of at least 0.1% and confidence of at least 80%.<br>
* We sort the rules by decreasing confidence.</ul>
<p>Have a look at the summary of the rules:</p>
<pre>
rules &lt;- apriori(tr, parameter = list(supp=0.001, conf=0.8))
rules &lt;- sort(rules, by='confidence', decreasing = TRUE)
summary(rules)
<em>set of 89697 rules
rule length distribution (lhs + rhs):sizes
2 3 4 5 6 7 8 9 10 103 3206 9909 26451 31144 14599 3464 700 121 Min. 1st Qu. Median Mean 3rd Qu. Max. 2.000 5.000 6.000 5.641 6.000 10.000 summary of quality measures:
support confidence lift count Min. :0.001036 Min. :0.8000 Min. : 8.711 Min. : 20.00 1st Qu.:0.001088 1st Qu.:0.8333 1st Qu.: 19.052 1st Qu.: 21.00 Median :0.001192 Median :0.8750 Median : 24.495 Median : 23.00 Mean :0.001382 Mean :0.8827 Mean : 49.558 Mean : 26.67 3rd Qu.:0.001503 3rd Qu.:0.9231 3rd Qu.: 42.265 3rd Qu.: 29.00 Max. :0.018242 Max. :1.0000 Max. :622.452 Max. :352.00 mining info:
data ntransactions support confidence
tr 19296 0.001 0.8
</em>
</pre>
<p>The summary of the rules gives us some very interesting information:</p>
<ul>
* The number of rules: 89,697.<br>
* The distribution of rules by length: a length of 6 items has the most rules.<br>
* The summary of quality measures: ranges of support, confidence, and lift.<br>
* The information on data mining: total data mined, and the minimum parameters we set earlier.</ul>
<p>We have 89,697 rules. I don’t want to print them all, so let’s inspect the top 10.</p>
<pre>
inspect(rules[1:10])
<em> lhs rhs support confidence
[1] {WOBBLY CHICKEN} => {DECORATION} 0.001451078 1 [2] {WOBBLY CHICKEN} => {METAL} 0.001451078 1 [3] {DECOUPAGE} => {GREETING CARD} 0.001191957 1 [4] {BILLBOARD FONTS DESIGN} => {WRAP} 0.001502902 1 [5] {WOBBLY RABBIT} => {DECORATION} 0.001762023 1 [6] {WOBBLY RABBIT} => {METAL} 0.001762023 1 [7] {BLACK TEA} => {SUGAR JARS} 0.002332090 1 [8] {BLACK TEA} => {COFFEE} 0.002332090 1 [9] {CHOCOLATE SPOTS} => {SWISS ROLL TOWEL} 0.002176617 1 [10] {ART LIGHTS} => {FUNK MONKEY} 0.002021144 1 lift count
[1] 385.92000 28 [2] 385.92000 28 [3] 344.57143 23 [4] 622.45161 29 [5] 385.92000 34 [6] 385.92000 34 [7] 212.04396 45 [8] 61.06329 45 [9] 410.55319 42 [10] 494.76923 39
</em>
</pre>
<p>The interpretation is pretty straightforward:</p>
<ul>
* 100% customers who bought “WOBBLY CHICKEN” also bought “DECORATION”.<br>
* 100% customers who bought “BLACK TEA” also bought “SUGAR JAR”.
</ul>
<p>And plot these top 10 rules.</p>
<pre>
topRules &lt;- rules[1:10]
plot(topRules)
</pre>
<p>Gives this plot:<br>
<a rel="nofollow" href="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2017/09/basket_5.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i1.wp.com/datascienceplus.com/wp-content/uploads/2017/09/basket_5-490x228.png?w=450&ssl=1" alt="" class="wp-image-8698" data-recalc-dims="1"></a></p>
<pre>
plot(topRules, method=&quot;graph&quot;)
</pre>
<p>Gives this plot:<br>
<a rel="nofollow" href="https://i0.wp.com/datascienceplus.com/wp-content/uploads/2017/09/basket_6.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i1.wp.com/datascienceplus.com/wp-content/uploads/2017/09/basket_6-490x228.png?w=450&ssl=1" alt="" class="wp-image-8699" data-recalc-dims="1"></a></p>
<pre>
plot(topRules, method = &quot;grouped&quot;)
</pre>
<p>Gives this plot:<br>
<a rel="nofollow" href="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2017/09/basket_9.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2017/09/basket_9-490x243.png?w=450&ssl=1" alt="" class="wp-image-8700" data-recalc-dims="1"></a></p>
<h2>Summary</h2>
<p>In this post, we have learned how to perform Market Basket Analysis in R and how to interpret the results. If you want to implement them in Python, <a rel="nofollow" href="http://rasbt.github.io/mlxtend/" target="_blank">Mlxtend</a> is a Python library that has an implementation of the Apriori algorithm for this sort of application. You can find an introduction tutorial <a rel="nofollow" href="http://pbpython.com/market-basket-analysis.html" target="_blank">here</a>.</p>
<p>If you would like the R Markdown file used to make this blog post, you can find <a rel="nofollow" href="https://github.com/susanli2016/Data-Analysis-with-R/blob/master/Market_Basket_Analysis.Rmd" target="_blank">here</a>.</p>
<p><b>Reference</b></p>
<ul><a rel="nofollow" href="http://www.rdatamining.com/examples/association-rules" target="_blank">R and Data Mining</a>
<ul>
<ul></ul>
<p><strong>
<p>Related Post</p>
<p>
<ol>
<li><a rel="nofollow" href="https://datascienceplus.com/building-a-book-recommender-system-the-basics-knn-and-matrix-factorization/" title="Permanent Link toBuilding A Book Recommender System – The Basics, kNN and Matrix Factorization" target="_blank">Building A Book Recommender System – The Basics, kNN and Matrix Factorization</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/explaining-complex-machine-learning-models-with-lime/" title="Permanent Link toExplaining complex machine learning models with LIME" target="_blank">Explaining complex machine learning models with LIME</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/text-message-classification/" title="Permanent Link toText Message Classification" target="_blank">Text Message Classification</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/analyzing-google-trends-data-in-r/" title="Permanent Link toAnalyzing Google Trends Data in R" target="_blank">Analyzing Google Trends Data in R</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/gradient-boosting-in-r/" title="Permanent Link toGradient boosting in R" target="_blank">Gradient boosting in R</a></li>
</ol></strong>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://datascienceplus.com/a-gentle-introduction-on-market-basket-analysis%E2%80%8A-%E2%80%8Aassociation-rules/"> R Programming – DataScience+</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/IOWZ5jeVMeY" height="1"></a></div></ul></ul>