Association rules, and why lift beats confidence
Which items go together? Support, confidence and lift each answer part of that, and high confidence alone can be a trap.
What runs in CodeSplash
- Association rules Verified in Python and R
You will be able to
- Calculate support, confidence and lift
- Explain how a popular item produces high confidence and no information
- Filter rules in the explorer and avoid reading them as causes
Baskets into rules
ReadAn association ruleAssociation ruleA pattern such as "rows with A also tend to have B", scored by support, confidence and lift. has the form {butter} → {bread}. For each one, three numbers ask three questions:
- Support: how common is the pair?
- Confidence: given the left side, how often does the right side follow?
- Lift: how much more often than if the two were unrelated? A lift of 1 means no association.
Work one out
CheckpointCheck yourself
Out of 100 baskets, 40 contain butter, 50 contain bread and 40 contain both. What's the lift of butter → bread?
Show the answer
Answer: 2
Confidence is 40 / 40 = 1, and bread appears in 50 / 100 = 0.5 of all baskets. So lift is 1 / 0.5 = 2.
Check yourself
In the same baskets, what's the support of butter → bread?
Show the answer
Answer: 0.4
40 of the 100 baskets contain both, so support is 0.4.
Make a guess
PredictPredict first
Bananas are in most baskets, whether or not butter is. Confidence of butter → bananas will be high. What about the lift?
Reveal
Close to 1. Butter buyers buy bananas at about the rate everyone does. High confidence here reflects that bananas are popular, not that butter leads to them. You'll see this next.
Trap the rule
ExploreCExplorable · Association rules: confidence and lift
When does 'people who buy A also buy B' mean anything?
Most baskets contain bananas, whether or not they contain butter. What will the lift of butter → bananas be?
Rank rules by
| Rule | Support | Confidence | Lift |
|---|---|---|---|
| beer → diapers | 0.076 | 0.53 | 3.82 |
| diapers → beer | 0.076 | 0.55 | 3.82 |
| beer + bananas → diapers | 0.052 | 0.53 | 3.81 |
| diapers + bananas → beer | 0.052 | 0.53 | 3.68 |
| butter + coffee → bread | 0.032 | 0.86 | 3.08 |
| butter + bananas → bread | 0.129 | 0.85 | 3.02 |
| bread → butter | 0.173 | 0.62 | 2.95 |
| butter → bread | 0.173 | 0.83 | 2.95 |
Red: butter → bananas. Orange: butter → bread. Rules with lift near 1 look strong but say little.
Commit your prediction above to see the result
Make your prediction to see the result.
Raise Share of baskets with bananas until butter → bananas has confidence of at least 0.8 with lift still under 1.1. Then rank rules by confidence, then by lift, and compare the top of the list.
Minimum support matters too. Lower it and the count of rules rises quickly, with more of them resting on a handful of baskets.
Read the card
Read24 rules from 2201 transactions over 10 items; strongest: {Age=Adult, Class=2nd, Survived=Yes} => {Sex=Female} (lift 3.99).
- Rules
- 24
- Transactions
- 2,201
Plots
View data
| Confidence | Rule | Lift | Support |
|---|---|---|---|
| 0.8511 | {Age=Adult, Class=2nd, Survived=Yes} => {Sex=Female} | 3.986 | 0.0363 |
| 1 | {Age=Child, Survived=No} => {Class=3rd} | 3.118 | 0.0236 |
| 1 | {Age=Child, Sex=Male, Survived=No} => {Class=3rd} | 3.118 | 0.0159 |
| 1 | {Age=Child, Sex=Female, Survived=No} => {Class=3rd} | 3.118 | 0.0077 |
| 1 | {Age=Child, Class=2nd} => {Survived=Yes} | 3.096 | 0.0109 |
| 1 | {Age=Child, Class=2nd, Sex=Female} => {Survived=Yes} | 3.096 | 0.0059 |
| 0.9724 | {Class=1st, Sex=Female} => {Survived=Yes} | 3.010 | 0.0641 |
| 0.9722 | {Age=Adult, Class=1st, Sex=Female} => {Survived=Yes} | 3.010 | 0.0636 |
| 0.8774 | {Class=2nd, Sex=Female} => {Survived=Yes} | 2.716 | 0.0423 |
| 0.8696 | {Age=Adult, Class=Crew, Sex=Female} => {Survived=Yes} | 2.692 | 0.0091 |
| 0.8696 | {Class=Crew, Sex=Female} => {Survived=Yes} | 2.692 | 0.0091 |
| 0.8602 | {Age=Adult, Class=2nd, Sex=Female} => {Survived=Yes} | 2.663 | 0.0363 |
| 0.8413 | {Sex=Female, Survived=No} => {Class=3rd} | 2.623 | 0.0482 |
| 0.8165 | {Age=Adult, Sex=Female, Survived=No} => {Class=3rd} | 2.546 | 0.0404 |
| 0.9167 | {Age=Adult, Class=2nd, Sex=Male} => {Survived=No} | 1.354 | 0.0700 |
| 0.8603 | {Class=2nd, Sex=Male} => {Survived=No} | 1.271 | 0.0700 |
| 0.9955 | {Age=Adult, Class=Crew, Survived=No} => {Sex=Male} | 1.266 | 0.3044 |
| 0.9955 | {Class=Crew, Survived=No} => {Sex=Male} | 1.266 | 0.3044 |
| 0.9740 | {Age=Adult, Class=Crew} => {Sex=Male} | 1.238 | 0.3916 |
| 0.9740 | {Class=Crew} => {Sex=Male} | 1.238 | 0.3916 |
| 0.8377 | {Age=Adult, Class=3rd, Sex=Male} => {Survived=No} | 1.237 | 0.1758 |
| 0.9672 | {Age=Adult, Class=1st, Survived=No} => {Sex=Male} | 1.230 | 0.0536 |
| 0.9672 | {Class=1st, Survived=No} => {Sex=Male} | 1.230 | 0.0536 |
| 0.8275 | {Class=3rd, Sex=Male} => {Survived=No} | 1.222 | 0.1917 |
Association rules
| If | Then | Support | Confidence | Lift | Leverage | Conviction | Count |
|---|---|---|---|---|---|---|---|
| {Age=Adult, Class=2nd, Survived=Yes} | {Sex=Female} | 0.0363 | 0.8511 | 3.986 | 0.0272 | 5.281 | 80 |
| {Age=Child, Survived=No} | {Class=3rd} | 0.0236 | 1 | 3.118 | 0.0160 | — | 52 |
| {Age=Child, Sex=Male, Survived=No} | {Class=3rd} | 0.0159 | 1 | 3.118 | 0.0108 | — | 35 |
| {Age=Child, Sex=Female, Survived=No} | {Class=3rd} | 0.0077 | 1 | 3.118 | 0.0052 | — | 17 |
| {Age=Child, Class=2nd} | {Survived=Yes} | 0.0109 | 1 | 3.096 | 0.0074 | — | 24 |
| {Age=Child, Class=2nd, Sex=Female} | {Survived=Yes} | 0.0059 | 1 | 3.096 | 0.0040 | — | 13 |
| {Class=1st, Sex=Female} | {Survived=Yes} | 0.0641 | 0.9724 | 3.010 | 0.0428 | 24.540 | 141 |
| {Age=Adult, Class=1st, Sex=Female} | {Survived=Yes} | 0.0636 | 0.9722 | 3.010 | 0.0425 | 24.371 | 140 |
| {Class=2nd, Sex=Female} | {Survived=Yes} | 0.0423 | 0.8774 | 2.716 | 0.0267 | 5.520 | 93 |
| {Age=Adult, Class=Crew, Sex=Female} | {Survived=Yes} | 0.0091 | 0.8696 | 2.692 | 0.0057 | 5.190 | 20 |
| {Class=Crew, Sex=Female} | {Survived=Yes} | 0.0091 | 0.8696 | 2.692 | 0.0057 | 5.190 | 20 |
| {Age=Adult, Class=2nd, Sex=Female} | {Survived=Yes} | 0.0363 | 0.8602 | 2.663 | 0.0227 | 4.843 | 80 |
| {Sex=Female, Survived=No} | {Class=3rd} | 0.0482 | 0.8413 | 2.623 | 0.0298 | 4.279 | 106 |
| {Age=Adult, Sex=Female, Survived=No} | {Class=3rd} | 0.0404 | 0.8165 | 2.546 | 0.0246 | 3.702 | 89 |
| {Age=Adult, Class=2nd, Sex=Male} | {Survived=No} | 0.0700 | 0.9167 | 1.354 | 0.0183 | 3.876 | 154 |
| {Class=2nd, Sex=Male} | {Survived=No} | 0.0700 | 0.8603 | 1.271 | 0.0149 | 2.313 | 154 |
| {Age=Adult, Class=Crew, Survived=No} | {Sex=Male} | 0.3044 | 0.9955 | 1.266 | 0.0639 | 47.904 | 670 |
| {Class=Crew, Survived=No} | {Sex=Male} | 0.3044 | 0.9955 | 1.266 | 0.0639 | 47.904 | 670 |
| {Age=Adult, Class=Crew} | {Sex=Male} | 0.3916 | 0.9740 | 1.238 | 0.0754 | 8.217 | 862 |
| {Class=Crew} | {Sex=Male} | 0.3916 | 0.9740 | 1.238 | 0.0754 | 8.217 | 862 |
| {Age=Adult, Class=3rd, Sex=Male} | {Survived=No} | 0.1758 | 0.8377 | 1.237 | 0.0337 | 1.990 | 387 |
| {Age=Adult, Class=1st, Survived=No} | {Sex=Male} | 0.0536 | 0.9672 | 1.230 | 0.0100 | 6.513 | 118 |
| {Class=1st, Survived=No} | {Sex=Male} | 0.0536 | 0.9672 | 1.230 | 0.0100 | 6.513 | 118 |
| {Class=3rd, Sex=Male} | {Survived=No} | 0.1917 | 0.8275 | 1.222 | 0.0349 | 1.872 | 422 |
Conviction is blank when confidence is 1 (infinite).
The exact R script · R R version 4.5.1 (2025-06-13)
# Association rules
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.apriori 1.0.0 · spec 42b90ff2e8408e03
# Dataset: ml_titanic_tx (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
suppressPackageStartupMessages(library(arules))
# %% Transactions
TRANSACTION <- "transaction"
ITEM <- "item"
ITEMS <- c()
columns <- unique(c(TRANSACTION, ITEM, ITEMS))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_titanic_tx.parquet", col_select = columns))
basket <- if (!is.null(TRANSACTION) && !is.null(ITEM)) {
cs_ml_basket_long(df, TRANSACTION, ITEM) # transactions by first appearance, items sorted
} else if (length(ITEMS)) {
cs_ml_basket_wide(df, ITEMS)
} else stop("Choose a transaction and an item column (long format) or item columns (wide format).")
MIN_SUPPORT <- 0.005
MIN_CONFIDENCE <- 0.8
MIN_LIFT <- 1.2
# %% Frequent itemsets and rules
# arules proposes candidates with thresholds lowered by 1e-9 (Apriori for both algorithm choices:
# the frequent itemsets are the same); cs_ml_finish_rules applies the pinned thresholds on the basket.
trans <- methods::as(basket, "transactions")
found <- arules::apriori(
trans,
parameter = list(supp = max(MIN_SUPPORT - 1e-9, 1e-12), conf = max(MIN_CONFIDENCE - 1e-12, 1e-12),
minlen = 2, maxlen = 4, target = "rules", maxtime = 0),
control = list(verbose = FALSE)
)
candidates <- Map(function(a, c) list(antecedent = a, consequent = c),
methods::as(arules::lhs(found), "list"), methods::as(arules::rhs(found), "list"))
rules <- cs_ml_finish_rules(basket, candidates, MIN_SUPPORT, MIN_CONFIDENCE, MIN_LIFT)
# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.apriori/titanic_long/out-r")
nanoparquet::write_parquet(rules, file.path(out, "rules.parquet"))
# %% Result
labels <- paste(rules$antecedent, "=>", rules$consequent)
values <- list(n_transactions = nrow(basket), n_items = ncol(basket), n_rules = nrow(rules),
support_sum = sum(rules$support), confidence_sum = sum(rules$confidence), lift_sum = sum(rules$lift))
for (i in seq_len(min(25L, nrow(rules)))) {
values[[sprintf("lift[%s]", labels[i])]] <- rules$lift[i]
values[[sprintf("confidence[%s]", labels[i])]] <- rules$confidence[i]
values[[sprintf("support[%s]", labels[i])]] <- rules$support[i]
}
if (nrow(rules)) {
values$top_rule <- labels[1]
values$top_lift <- rules$lift[1]
values$top_confidence <- rules$confidence[1]
}
shown <- utils::head(rules, 200L)
table_rows <- lapply(seq_len(nrow(shown)), function(i) list(
antecedent = shown$antecedent[i], consequent = shown$consequent[i], support = shown$support[i],
confidence = shown$confidence[i], lift = shown$lift[i], leverage = shown$leverage[i],
conviction = if (is.infinite(shown$conviction[i])) NULL else shown$conviction[i], count = shown$count[i]
))
charts <- list()
if (nrow(rules)) {
top <- utils::head(rules, 1000L)
charts[[1]] <- cs_chart("rules", "rules-scatter", "Rules: support × confidence (color = lift)", list(
support = cs_col("Support", top$support, "numeric"),
confidence = cs_col("Confidence", top$confidence, "numeric"),
lift = cs_col("Lift", top$lift, "numeric"),
label = cs_col("Rule", labels[seq_len(nrow(top))], "categorical")
))
}
summary <- sprintf("%d rules from %d transactions over %d items", nrow(rules), nrow(basket), ncol(basket))
summary <- if (nrow(rules)) sprintf("%s; strongest: %s (lift %.2f).", summary, labels[1], rules$lift[1]) else paste0(summary, ".")
cs_publish(list(
title = "Association rules",
engine = cs_engine_info("arules", "nanoparquet"),
n = nrow(basket),
summary = summary,
statistics = list(list(key = "n_rules", label = "Rules", value = nrow(rules), format = "integer"),
list(key = "n_transactions", label = "Transactions", value = nrow(basket), format = "integer")),
tables = list(list(
key = "rules", title = paste0("Association rules", if (nrow(rules) > 200) " (first 200)" else ""),
columns = list(list(key = "antecedent", label = "If"), list(key = "consequent", label = "Then"),
list(key = "support", label = "Support", type = "number"),
list(key = "confidence", label = "Confidence", type = "number"),
list(key = "lift", label = "Lift", type = "number"),
list(key = "leverage", label = "Leverage", type = "number"),
list(key = "conviction", label = "Conviction", type = "number"),
list(key = "count", label = "Count", type = "integer")),
rows = table_rows,
note = "Conviction is blank when confidence is 1 (infinite)."
)),
charts = charts,
values = values,
warnings = list(),
artifacts = list(list(key = "rules", path = file.path(out, "rules.parquet"), format = "parquet"))
))
24 rules from 2201 transactions over 10 items; strongest: {Age=Adult, Class=2nd, Survived=Yes} => {Sex=Female} (lift 3.99).
- Rules
- 24
- Transactions
- 2,201
To keep this page light, the plots are shown once, under the R tab.
Association rules
| If | Then | Support | Confidence | Lift | Leverage | Conviction | Count |
|---|---|---|---|---|---|---|---|
| {Age=Adult, Class=2nd, Survived=Yes} | {Sex=Female} | 0.0363 | 0.8511 | 3.986 | 0.0272 | 5.281 | 80 |
| {Age=Child, Survived=No} | {Class=3rd} | 0.0236 | 1 | 3.118 | 0.0160 | — | 52 |
| {Age=Child, Sex=Male, Survived=No} | {Class=3rd} | 0.0159 | 1 | 3.118 | 0.0108 | — | 35 |
| {Age=Child, Sex=Female, Survived=No} | {Class=3rd} | 0.0077 | 1 | 3.118 | 0.0052 | — | 17 |
| {Age=Child, Class=2nd} | {Survived=Yes} | 0.0109 | 1 | 3.096 | 0.0074 | — | 24 |
| {Age=Child, Class=2nd, Sex=Female} | {Survived=Yes} | 0.0059 | 1 | 3.096 | 0.0040 | — | 13 |
| {Class=1st, Sex=Female} | {Survived=Yes} | 0.0641 | 0.9724 | 3.010 | 0.0428 | 24.540 | 141 |
| {Age=Adult, Class=1st, Sex=Female} | {Survived=Yes} | 0.0636 | 0.9722 | 3.010 | 0.0425 | 24.371 | 140 |
| {Class=2nd, Sex=Female} | {Survived=Yes} | 0.0423 | 0.8774 | 2.716 | 0.0267 | 5.520 | 93 |
| {Age=Adult, Class=Crew, Sex=Female} | {Survived=Yes} | 0.0091 | 0.8696 | 2.692 | 0.0057 | 5.190 | 20 |
| {Class=Crew, Sex=Female} | {Survived=Yes} | 0.0091 | 0.8696 | 2.692 | 0.0057 | 5.190 | 20 |
| {Age=Adult, Class=2nd, Sex=Female} | {Survived=Yes} | 0.0363 | 0.8602 | 2.663 | 0.0227 | 4.843 | 80 |
| {Sex=Female, Survived=No} | {Class=3rd} | 0.0482 | 0.8413 | 2.623 | 0.0298 | 4.279 | 106 |
| {Age=Adult, Sex=Female, Survived=No} | {Class=3rd} | 0.0404 | 0.8165 | 2.546 | 0.0246 | 3.702 | 89 |
| {Age=Adult, Class=2nd, Sex=Male} | {Survived=No} | 0.0700 | 0.9167 | 1.354 | 0.0183 | 3.876 | 154 |
| {Class=2nd, Sex=Male} | {Survived=No} | 0.0700 | 0.8603 | 1.271 | 0.0149 | 2.313 | 154 |
| {Age=Adult, Class=Crew, Survived=No} | {Sex=Male} | 0.3044 | 0.9955 | 1.266 | 0.0639 | 47.904 | 670 |
| {Class=Crew, Survived=No} | {Sex=Male} | 0.3044 | 0.9955 | 1.266 | 0.0639 | 47.904 | 670 |
| {Age=Adult, Class=Crew} | {Sex=Male} | 0.3916 | 0.9740 | 1.238 | 0.0754 | 8.217 | 862 |
| {Class=Crew} | {Sex=Male} | 0.3916 | 0.9740 | 1.238 | 0.0754 | 8.217 | 862 |
| {Age=Adult, Class=3rd, Sex=Male} | {Survived=No} | 0.1758 | 0.8377 | 1.237 | 0.0337 | 1.990 | 387 |
| {Age=Adult, Class=1st, Survived=No} | {Sex=Male} | 0.0536 | 0.9672 | 1.230 | 0.0100 | 6.513 | 118 |
| {Class=1st, Survived=No} | {Sex=Male} | 0.0536 | 0.9672 | 1.230 | 0.0100 | 6.513 | 118 |
| {Class=3rd, Sex=Male} | {Survived=No} | 0.1917 | 0.8275 | 1.222 | 0.0349 | 1.872 | 422 |
Conviction is blank when confidence is 1 (infinite).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Association rules
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.apriori 1.0.0 · spec 42b90ff2e8408e03
# Dataset: ml_titanic_tx (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
from mlxtend.frequent_patterns import apriori, association_rules
import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import rules as csrules
# %% Transactions
TRANSACTION = "transaction"
ITEM = "item"
ITEMS = []
columns = [c for c in (TRANSACTION, ITEM) if c] + ITEMS
df = pd.read_parquet("tests/parity/fixtures/ml_titanic_tx.parquet", columns=list(dict.fromkeys(columns)))
if TRANSACTION and ITEM:
basket = csrules.basket_long(df, TRANSACTION, ITEM) # transactions by first appearance, items sorted
elif ITEMS:
basket = csrules.basket_wide(df, ITEMS)
else:
raise ValueError("Choose a transaction and an item column (long format) or item columns (wide format).")
MIN_SUPPORT = 0.005
MIN_CONFIDENCE = 0.8
MIN_LIFT = 1.2
# %% Frequent itemsets and rules
# The library proposes candidates with thresholds lowered by 1e-9; csrules.finish applies the pinned
# thresholds on the basket itself (identical in R).
freq = apriori(basket, min_support=max(MIN_SUPPORT - 1e-9, 1e-12), use_colnames=True, max_len=4)
candidates = []
if len(freq) and (freq["itemsets"].map(len) > 1).any():
found = association_rules(freq, num_itemsets=len(basket), metric="confidence", min_threshold=max(MIN_CONFIDENCE - 1e-12, 0.0))
for ante, cons in zip(found["antecedents"], found["consequents"]):
if len(cons) == 1: # one consequent item, as arules
candidates.append((tuple(sorted(ante)), next(iter(cons))))
rules = csrules.finish(basket, candidates, MIN_SUPPORT, MIN_CONFIDENCE, MIN_LIFT)
# %% Artifacts
out = csml.out_dir("target/academy-parity/run-8142/discover.apriori/titanic_long/out-python")
rules.to_parquet(os.path.join(out, "rules.parquet"), index=False)
# %% Result
labels = (rules["antecedent"] + " => " + rules["consequent"]).tolist()
values = {
"n_transactions": len(basket),
"n_items": basket.shape[1],
"n_rules": len(rules),
"support_sum": float(rules["support"].sum()),
"confidence_sum": float(rules["confidence"].sum()),
"lift_sum": float(rules["lift"].sum()),
}
for i, lab in enumerate(labels[:25]):
values[f"lift[{lab}]"] = float(rules["lift"].iloc[i])
values[f"confidence[{lab}]"] = float(rules["confidence"].iloc[i])
values[f"support[{lab}]"] = float(rules["support"].iloc[i])
if len(rules):
values["top_rule"] = labels[0]
values["top_lift"] = float(rules["lift"].iloc[0])
values["top_confidence"] = float(rules["confidence"].iloc[0])
shown = rules.head(200)
table_rows = [
{k: (None if isinstance(v, float) and np.isinf(v) else v) for k, v in rec.items()}
for rec in shown[["antecedent", "consequent", "support", "confidence", "lift", "leverage", "conviction", "count"]].to_dict("records")
]
charts = []
if len(rules):
top = rules.head(1000)
charts.append(cs.chart("rules", "rules-scatter", "Rules: support × confidence (color = lift)", {
"support": cs.col("Support", top["support"], "numeric"),
"confidence": cs.col("Confidence", top["confidence"], "numeric"),
"lift": cs.col("Lift", top["lift"], "numeric"),
"label": cs.col("Rule", labels[: len(top)], "categorical"),
}))
summary = f"{len(rules)} rules from {len(basket)} transactions over {basket.shape[1]} items"
summary += f"; strongest: {labels[0]} (lift {values['top_lift']:.2f})." if len(rules) else "."
cs.publish({
"title": "Association rules",
"engine": cs.engine_info("mlxtend", "numpy", "pandas"),
"n": len(basket),
"summary": summary,
"statistics": [
{"key": "n_rules", "label": "Rules", "value": len(rules), "format": "integer"},
{"key": "n_transactions", "label": "Transactions", "value": len(basket), "format": "integer"},
],
"tables": [{
"key": "rules",
"title": "Association rules" + (" (first 200)" if len(rules) > 200 else ""),
"columns": [
{"key": "antecedent", "label": "If"},
{"key": "consequent", "label": "Then"},
{"key": "support", "label": "Support", "type": "number"},
{"key": "confidence", "label": "Confidence", "type": "number"},
{"key": "lift", "label": "Lift", "type": "number"},
{"key": "leverage", "label": "Leverage", "type": "number"},
{"key": "conviction", "label": "Conviction", "type": "number"},
{"key": "count", "label": "Count", "type": "integer"},
],
"rows": table_rows,
"note": "Conviction is blank when confidence is 1 (infinite).",
}],
"charts": charts,
"values": values,
"warnings": [],
"artifacts": [{"key": "rules", "path": os.path.join(out, "rules.parquet"), "format": "parquet"}],
})
Association rules work on anything you can treat as a set of items, including one person's attributes. Across 2,201 Titanic passengers, 24 rules pass the thresholds. The strongest has lift 3.99 and confidence 85%.
Note how tiny its support can be. This run allowed support as low as 0.5%, because the interesting Titanic subgroups are small.
Filter and sort
ReadOn a small basket file of 40 transactions and 10 items, the rule with the highest lift is {bananas} => {cereal} at 3.81.
The Rules explorer lets you filter by minimum support, confidence and lift, by an item and where it appears, and sort. Thresholds set in the method's options apply first, so if you can't find a rule in the explorer, lower them and rerun.
Apriori and FP-Growth find the same frequent itemsets; FP-Growth is usually faster on dense data.
Rules aren't causes
ReadMining tests thousands of combinations, so some high-lift rules will be flukes, especially with low support. Rules also don't say why: buying charcoal doesn't cause buying sausages. A shared cause, such as a sunny weekend, can explain the pair.
To act on a rule, test it. Run an experiment that moves the items closer together and see whether sales change.
Check your understanding
CheckpointCheck yourself
Rule A → B has a confidence of 0.9. B appears in 90% of all baskets. What does this tell you?
Show the answer
Answer: b
Confidence ignores how common B already is, and lift corrects that.
Check yourself
What does a lift of 0.5 mean?
Show the answer
Answer: b
Lift below 1 points to a negative association: buying one makes the other less likely. This can be useful too, for spotting substitutes.
Check yourself
You lower the minimum support from 5% to 0.1% and get 20,000 rules. What should you expect?
Show the answer
Answer: a
Lower support finds rarer patterns and many more false ones. Validate a promising rule on data held out from the mining.
Do it on your own data
In the appChoose Co-occurring items. The method takes either one row per transaction and item, or one row per transaction with true/false item columns.
import pandas as pd
from mlxtend.frequent_patterns import apriori, association_rules
df = pd.read_csv("baskets.csv").drop(columns="basket").astype(bool)
items = apriori(df, min_support=0.1, use_colnames=True)
rules = association_rules(items, metric="confidence", min_threshold=0.6)
print(rules.sort_values("lift", ascending=False)[["antecedents", "consequents", "support", "confidence", "lift"]].head())library(arules)
df <- read.csv("baskets.csv")
m <- as.matrix(df[, setdiff(names(df), "basket")]) == "true"
tx <- as(m, "transactions")
rules <- apriori(tx, parameter = list(supp = 0.1, conf = 0.6, minlen = 2), control = list(verbose = FALSE))
inspect(head(sort(rules, by = "lift"), 5))Recap
Recap- Support says how common, confidence says how often, and lift says how much more than chance.
- Confidence alone is fooled by popular items.
- Rules are leads. Check them on new data, and test before you act.
Concepts in this lesson