Imagine 10000 receipts sitting on your table. Each receipt represents a transaction with items that were purchased. The receipt is a representation of stuff that went into a customer’s basket - and therefore ‘Market Basket Analysis’.
That is exactly what the Groceries Data Set contains: a collection of receipts with each line representing 1 receipt and the items purchased. Each line is called a transaction and each column in a row represents an item. The data set is attached.
Your assignment is to use R to mine the data for association rules. You should report support, confidence and lift and your top 10 rules by lift.
Extra credit: do a simple cluster analysis on the data as well. Use whichever packages you like.
Each line of the file is one receipt, with the items separated by
commas and the unused columns left empty.
read.transactions() in the arules package
reads this “basket” layout directly into a sparse transactions object,
which is what the Apriori algorithm needs.
rm.duplicates = TRUE drops an item that appears twice on
the same receipt, since association rules only ask whether an item was
bought, not how many.
grocery_baskets <- read.transactions("GroceryDataSet.csv", format = "basket",
sep = ",", rm.duplicates = TRUE)
summary(grocery_baskets)
## transactions as itemMatrix in sparse format with
## 9835 rows (elements/itemsets/transactions) and
## 169 columns (items) and a density of 0.02609146
##
## most frequent items:
## whole milk other vegetables rolls/buns soda
## 2513 1903 1809 1715
## yogurt (Other)
## 1372 34055
##
## element (itemset/transaction) length distribution:
## sizes
## 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
## 2159 1643 1299 1005 855 645 545 438 350 246 182 117 78 77 55 46
## 17 18 19 20 21 22 23 24 26 27 28 29 32
## 29 14 14 9 11 4 6 1 1 1 1 3 1
##
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 1.000 2.000 3.000 4.409 6.000 32.000
##
## includes extended item information - examples:
## labels
## 1 abrasive cleaner
## 2 artif. sweetener
## 3 baby cosmetics
There are 9,835 receipts and 169 distinct items. The density of 0.026 means a typical receipt holds about 2.6% of the items the store sells: the median basket has 3 items, the mean 4.4, and 2,159 receipts (22%) have a single item. A single-item receipt cannot contain all the items of a rule (a rule needs at least one item on each side), but it stays in the data and counts toward \(N\) and the item frequencies used in every rule’s support, confidence and lift. The largest basket has 32 items.
itemFrequencyPlot(grocery_baskets, topN = 20, type = "relative",
col = "steelblue", main = "Share of receipts containing each item (top 20)")
Whole milk is on 25.6% of receipts, other vegetables on 19.3%, rolls/buns on 18.4%, soda on 17.4% and yogurt on 14.0%. This matters for the rest of the analysis. A rule that ends in whole milk can reach a fair confidence from that base rate alone, because a quarter of all baskets contain milk anyway, and its lift can be at most \(1 / 0.256 = 3.9\). This is the reason to rank rules by lift rather than confidence.
For a rule \(A \Rightarrow B\) (if a basket contains the items in \(A\), it also contains the items in \(B\)), with \(N\) receipts and \(n(\cdot)\) the number of receipts containing a set of items:
These definitions and the Apriori algorithm follow Szymkowiak,
Klimanek and Józefowski (2018), who also use the arules
package; removing redundant rules (below) follows Raeder and Chawla’s
(2011) point that many mined rules are redundant, and uses arules’
is.redundant().
The Apriori algorithm first finds every itemset that reaches the minimum support, then builds rules from those itemsets and keeps the ones that reach the minimum confidence. Both thresholds are choices, so before picking them the next chunk counts how many rules each combination produces.
support_levels <- c(0.01, 0.005, 0.002, 0.001)
confidence_levels <- c(0.5, 0.25, 0.1)
rule_counts <- sapply(confidence_levels, function(conf) {
sapply(support_levels, function(supp) {
length(apriori(grocery_baskets,
parameter = list(supp = supp, conf = conf, minlen = 2),
control = list(verbose = FALSE)))
})
})
dimnames(rule_counts) <- list(
paste0("support ", support_levels, " (at least ",
ceiling(support_levels * length(grocery_baskets)), " receipts)"),
paste("confidence", confidence_levels))
kable(rule_counts, caption = "Number of rules found at each support and confidence threshold")
| confidence 0.5 | confidence 0.25 | confidence 0.1 | |
|---|---|---|---|
| support 0.01 (at least 99 receipts) | 15 | 170 | 427 |
| support 0.005 (at least 50 receipts) | 120 | 662 | 1574 |
| support 0.002 (at least 20 receipts) | 1098 | 4024 | 8332 |
| support 0.001 (at least 10 receipts) | 5668 | 17391 | 32783 |
The rule count is very sensitive to support: at a confidence of 0.25 it goes from 170 rules at 1% support to 17,391 at 0.1%. A support of 1% keeps only patterns that involve the most popular items, while 0.1% means a rule can rest on as few as 10 receipts.
Thresholds used: support 0.002 and confidence 0.25.
A support of 0.002 means each rule appears on at least 20 receipts.
Below that, rules seen on only 10 to 12 receipts start to appear near
the top of a lift ranking, and one or two extra receipts would change
their lift a lot (the comparison at the end of this section shows this).
The confidence of 0.25 is deliberately moderate: a high confidence floor
is easiest to pass for rules that end in very common items such as whole
milk, whose lift is capped at about 3.9, while it drops rules with a
rarer consequent whose confidence is moderate but far above that item’s
base rate. minlen = 2 stops Apriori from returning rules
with an empty left-hand side, such as
{} => {whole milk}.
grocery_rules <- apriori(grocery_baskets,
parameter = list(supp = 0.002, conf = 0.25, minlen = 2),
control = list(verbose = FALSE))
length(grocery_rules)
## [1] 4024
# a rule is redundant when a more general rule with the same right-hand side
# (a subset of its left-hand side) has the same or higher confidence
grocery_rules <- grocery_rules[!is.redundant(grocery_rules)]
length(grocery_rules)
## [1] 3691
Apriori finds 4,024 rules. 333 of them are redundant: they add an item to the left-hand side of a simpler rule without raising its confidence, so they say nothing the simpler rule does not. That leaves 3,691 rules.
summary(quality(grocery_rules)[, c("support", "confidence", "lift", "count")])
## support confidence lift count
## Min. :0.002034 Min. :0.2500 Min. : 0.9892 Min. : 20.00
## 1st Qu.:0.002339 1st Qu.:0.3072 1st Qu.: 1.9486 1st Qu.: 23.00
## Median :0.002847 Median :0.3933 Median : 2.3895 Median : 28.00
## Mean :0.004061 Mean :0.4179 Mean : 2.5306 Mean : 39.94
## 3rd Qu.:0.004067 3rd Qu.:0.5116 3rd Qu.: 2.9355 3rd Qu.: 40.00
## Max. :0.074835 Max. :0.8857 Max. :11.4214 Max. :736.00
# the rule seen on the most receipts, with its lift
highest_support <- DATAFRAME(head(sort(grocery_rules, by = "support"), 1), separate = TRUE)
kable(highest_support[, c("LHS", "RHS", "support", "confidence", "lift", "count")],
digits = 3, row.names = FALSE, caption = "Rule with the highest support")
| LHS | RHS | support | confidence | lift | count |
|---|---|---|---|---|---|
| {other vegetables} | {whole milk} | 0.075 | 0.387 | 1.514 | 736 |
rule_quality <- quality(grocery_rules)
ggplot(rule_quality, aes(x = support, y = confidence, colour = lift)) +
geom_point(alpha = 0.6, size = 1.4) +
scale_colour_gradient(low = "lightgrey", high = "darkred") +
labs(title = "3,691 rules: support against confidence, colored by lift",
x = "Support (share of all receipts)", y = "Confidence")
Most rules sit at low support: half are seen on 28 receipts or fewer
(median support 0.0028), and only a quarter reach 0.4% of receipts.
Confidence runs from the 0.25 floor to 0.89, with a median of 0.39. Lift
ranges from 0.99 to 11.4, with a median of 2.4, so the typical rule
describes items bought together about two and a half times as often as
chance would give. The rule with the highest support,
{other vegetables} => {whole milk} on 736 receipts, has
a lift of only 1.5. The plot also shows the trade-off between the
measures: the darkest points (highest lift) are all at very low support,
while the rules with the highest support (mostly pairs of the very
common items) have lift close to 1 or 2.
top10_by_lift <- head(sort(grocery_rules, by = "lift"), 10)
top10_table <- DATAFRAME(top10_by_lift, separate = TRUE)
top10_table$support <- round(top10_table$support, 4)
top10_table$confidence <- round(top10_table$confidence, 3)
top10_table$lift <- round(top10_table$lift, 2)
kable(top10_table[, c("LHS", "RHS", "support", "confidence", "lift", "count")],
row.names = FALSE,
caption = "Top 10 non-redundant rules by lift (support 0.002, confidence 0.25)")
| LHS | RHS | support | confidence | lift | count |
|---|---|---|---|---|---|
| {Instant food products} | {hamburger meat} | 0.0031 | 0.380 | 11.42 | 30 |
| {flour,whole milk} | {sugar} | 0.0028 | 0.337 | 9.96 | 28 |
| {flour} | {sugar} | 0.0050 | 0.287 | 8.46 | 49 |
| {hard cheese,whipped/sour cream} | {butter} | 0.0020 | 0.455 | 8.20 | 20 |
| {popcorn} | {salty snack} | 0.0022 | 0.310 | 8.19 | 22 |
| {processed cheese,whole milk} | {white bread} | 0.0021 | 0.304 | 7.23 | 21 |
| {butter,hard cheese} | {whipped/sour cream} | 0.0020 | 0.513 | 7.15 | 20 |
| {bottled water,root vegetables,whole milk} | {butter} | 0.0024 | 0.333 | 6.02 | 24 |
| {processed cheese} | {white bread} | 0.0042 | 0.252 | 5.98 | 41 |
| {butter,other vegetables,tropical fruit} | {whipped/sour cream} | 0.0023 | 0.426 | 5.94 | 23 |
# receipts containing the items of the top rule, and the most frequent consequents
item_counts <- itemFrequency(grocery_baskets, type = "absolute")
item_shares <- itemFrequency(grocery_baskets)
featured_items <- c("Instant food products", "hamburger meat", "whole milk", "rolls/buns")
kable(data.frame(item = featured_items,
receipts = as.vector(item_counts[featured_items]),
share = round(as.vector(item_shares[featured_items]), 4),
max_lift_as_consequent = round(1 / as.vector(item_shares[featured_items]), 2)),
caption = "Item counts, shares and the largest lift a rule ending in each item can reach")
| item | receipts | share | max_lift_as_consequent |
|---|---|---|---|
| Instant food products | 79 | 0.0080 | 124.49 |
| hamburger meat | 327 | 0.0332 | 30.08 |
| whole milk | 2513 | 0.2555 | 3.91 |
| rolls/buns | 1809 | 0.1839 | 5.44 |
The ten rules group into a few shopping missions:
{Instant food products} => {hamburger meat} has the
highest lift, 11.4: 38% of the 79 baskets with instant food also hold
hamburger meat, against 3.3% of all baskets. It reads like a
boxed-dinner purchase (a “helper”-style mix plus the meat it calls for).
Flour leads to sugar (lift 8.5 alone, 10.0 when whole milk is also in
the basket), which is a baking trip.{popcorn} => {salty snack},
lift 8.2.The rules support different actions. A high-lift, low-support rule like instant food to hamburger meat is a good target for a cross-promotion or shelf placement (put the mixes near the meat counter, or a coupon for one on the other), because buying one item makes the other much more likely. It is a small audience, though: the rule covers 30 receipts out of 9,835. None of the top 10 has whole milk or rolls/buns on the right-hand side, even though they are among the most frequent items: since lift is confidence divided by the consequent’s share, a rule ending in whole milk can reach a lift of at most 3.91 and one ending in rolls/buns at most 5.44, below every lift in this top 10 (the item table above). Lift also says nothing about direction: the lift of \(A \Rightarrow B\) equals the lift of \(B \Rightarrow A\), and none of these rules shows that one purchase causes the other.
To see what the 20-receipt floor does, the next chunk halves the
support to 0.001 (at least 10 receipts) and keeps everything else the
same: confidence 0.25, minlen = 2 and redundant rules
removed.
low_support_rules <- apriori(grocery_baskets,
parameter = list(supp = 0.001, conf = 0.25, minlen = 2),
control = list(verbose = FALSE))
low_support_rules <- low_support_rules[!is.redundant(low_support_rules)]
length(low_support_rules)
## [1] 15118
low_support_top10 <- DATAFRAME(head(sort(low_support_rules, by = "lift"), 10), separate = TRUE)
low_support_top10$support <- round(low_support_top10$support, 4)
low_support_top10$confidence <- round(low_support_top10$confidence, 3)
low_support_top10$lift <- round(low_support_top10$lift, 2)
kable(low_support_top10[, c("LHS", "RHS", "support", "confidence", "lift", "count")],
row.names = FALSE,
caption = "Top 10 non-redundant rules by lift (support 0.001, confidence 0.25)")
| LHS | RHS | support | confidence | lift | count |
|---|---|---|---|---|---|
| {bottled beer,red/blush wine} | {liquor} | 0.0019 | 0.396 | 35.72 | 19 |
| {ham,white bread} | {processed cheese} | 0.0019 | 0.380 | 22.93 | 19 |
| {bottled beer,liquor} | {red/blush wine} | 0.0019 | 0.413 | 21.49 | 19 |
| {Instant food products,soda} | {hamburger meat} | 0.0012 | 0.632 | 19.00 | 12 |
| {curd,sugar} | {flour} | 0.0011 | 0.324 | 18.61 | 11 |
| {baking powder,sugar} | {flour} | 0.0010 | 0.312 | 17.97 | 10 |
| {processed cheese,white bread} | {ham} | 0.0019 | 0.463 | 17.80 | 19 |
| {fruit/vegetable juice,ham} | {processed cheese} | 0.0011 | 0.289 | 17.47 | 11 |
| {margarine,sugar} | {flour} | 0.0016 | 0.296 | 17.04 | 16 |
| {root vegetables,sugar,whole milk} | {flour} | 0.0010 | 0.294 | 16.92 | 10 |
Halving the support changes the ranking a lot. The highest lift rises
from 11.4 to 35.7, for
{bottled beer, red/blush wine} => {liquor}, and every
rule in this top 10 has a lift above 16. Five of the ten rest on 10 to
12 receipts, where a single receipt moves the lift noticeably. The other
five are on 16 to 19 receipts, just under the 20-receipt floor, and they
add one new theme: bottled beer, red/blush wine and liquor bought
together (19 receipts). The rest repeat the main analysis in sharper
form: ham, white bread and processed cheese (the sandwich theme),
instant food with hamburger meat, and flour with sugar and other baking
items. So the floor costs something: it drops the beer, wine and liquor
pattern because it sits on 19 receipts instead of 20. In exchange, it
excludes the five top-10 rules that rest on only 10 to 12 receipts; the
main analysis keeps the floor because those five rules are too thin to
rank reliably. The comparison also shows a general weakness of ranking
rules: change the thresholds and the “top 10” changes, so the list is a
starting point for investigation rather than a fixed answer.
The rules above link a few items at a time. Clustering the items
gives a broader view: groups of products that tend to be bought together
across all receipts, the same idea as the product communities in Raeder
and Chawla (2011). The groups are built with Ward’s linkage (Ward 1963)
and checked with the average silhouette width (Rousseeuw 1987), both
standard options in R’s hclust and
cluster::silhouette. The analysis uses the 40 most frequent
items, each on at least 3.3% of receipts (printed below), because the
rarer items appear on too few receipts to place reliably.
Each item becomes a 0/1 column over the 9,835 receipts. The columns
are centered and scaled, so that popular items such as whole milk do not
dominate just because they appear on more receipts. For two standardized
0/1 columns, the squared Euclidean distance is proportional to \(1 - r\), where \(r\) is the correlation between the two
items’ purchase indicators, so items bought together more often than
their popularity would predict end up close together. The items are then
clustered with hierarchical clustering (hclust) and Ward’s
linkage, which merges at each step the two groups that add the least
within-group variation.
top40_items <- names(sort(itemFrequency(grocery_baskets), decreasing = TRUE))[1:40]
item_matrix <- as(grocery_baskets[, top40_items], "matrix") * 1 # receipts x items, 0/1
# least frequent of the 40 items, and the range of the correlations between items
round(min(item_shares[top40_items]), 4)
## [1] 0.0332
item_correlations <- cor(item_matrix)
round(range(item_correlations[upper.tri(item_correlations)]), 3)
## [1] -0.094 0.214
item_distance <- dist(t(scale(item_matrix))) # one row per item
item_tree <- hclust(item_distance, method = "ward.D2")
plot(item_tree, main = "Hierarchical clustering of the 40 most frequent items",
xlab = "", sub = "Ward linkage, Euclidean distance on standardized purchase indicators",
cex = 0.8)
rect.hclust(item_tree, k = 7, border = "darkred")
# average silhouette width for 2 to 10 clusters (1 = well separated, 0 = on the boundary)
silhouette_by_k <- sapply(2:10, function(k) {
summary(silhouette(cutree(item_tree, k), item_distance))$avg.width
})
round(setNames(silhouette_by_k, 2:10), 3)
## 2 3 4 5 6 7 8 9 10
## 0.010 0.011 0.005 0.007 0.009 0.010 0.011 0.012 0.012
item_groups <- cutree(item_tree, k = 7)
cluster_table <- data.frame(
cluster = 1:7,
items = sapply(1:7, function(g) paste(names(item_groups)[item_groups == g], collapse = ", ")))
kable(cluster_table, caption = "Item clusters (k = 7)")
| cluster | items |
|---|---|
| 1 | whole milk, yogurt, tropical fruit, citrus fruit, pip fruit, whipped/sour cream, domestic eggs, butter, curd, cream cheese, berries |
| 2 | other vegetables, root vegetables, pork, beef, frozen vegetables, chicken |
| 3 | rolls/buns, sausage, pastry, newspapers, brown bread, frankfurter |
| 4 | soda, bottled water, bottled beer |
| 5 | shopping bags, canned beer |
| 6 | fruit/vegetable juice, napkins, chocolate, white bread, waffles, salty snack, long life bakery product, dessert |
| 7 | margarine, coffee, sugar, UHT-milk |
The silhouette widths are all close to zero (0.005 to 0.012), so none of the tested cuts of this tree (k = 2 to 10) separates the items cleanly. That is expected for grocery data: most products are bought alongside the same few staples, and the correlations between the 40 items are small (from -0.094 to 0.214, printed above the dendrogram). The number of clusters was therefore chosen by reading the dendrogram, and seven groups each describe a recognizable kind of purchase:
These groups agree with the rules where they overlap: butter and whipped/sour cream, which end four of the top 10 rules, sit in the same dairy group as cream cheese, and salty snacks are with the other snack items. The clusters add a store-wide picture that the rules do not give, such as the drinks group and the meal-cooking group, which could guide store layout or which categories to promote together. Because the separation is weak, the boundaries are soft: an item near the edge of a group (fruit/vegetable juice and napkins in the snack group, for example) could move with a different linkage or a different set of items, so the groups are a description of these receipts rather than fixed categories.
With support of at least 0.002 (20 receipts) and confidence of at least 0.25, Apriori finds 3,691 non-redundant rules. The strongest by lift link instant food products to hamburger meat (lift 11.4), flour to sugar, popcorn to salty snacks, hard cheese to butter and whipped/sour cream, and processed cheese to white bread. These are specific shopping missions involving fairly uncommon items; rules ending in the most popular items, such as whole milk, cannot reach these lifts because those items are in so many baskets anyway. Halving the support to 0.001 with the same confidence triples the top lift and adds a beer, wine and liquor pattern on 19 receipts, but half of that top 10 rests on only 10 to 12 receipts, so the exact ranking depends on the thresholds. The cluster analysis of the 40 most frequent items finds seven loose groups (fresh dairy and fruit, meal cooking, bakery, drinks, snacks, pantry staples, and bags with canned beer), consistent with the rules but with weak separation between groups.
Raeder, T., & Chawla, N. V. (2011). Market basket analysis with networks. Social Network Analysis and Mining, 1(2), 97–113. https://doi.org/10.1007/s13278-010-0003-7
Rousseeuw, P. J. (1987). Silhouettes: A graphical aid to the interpretation and validation of cluster analysis. Journal of Computational and Applied Mathematics, 20, 53–65. https://doi.org/10.1016/0377-0427(87)90125-7
Szymkowiak, M., Klimanek, T., & Józefowski, T. (2018). Applying market basket analysis to official statistical data. Econometrics. Advances in Applied Data Analysis, 22(1), 39–57. https://doi.org/10.15611/eada.2018.1.03
Ward, J. H., Jr. (1963). Hierarchical grouping to optimize an objective function. Journal of the American Statistical Association, 58(301), 236–244. https://doi.org/10.1080/01621459.1963.10500845