Skip to content

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.

Applied ~11 min10 steps

What runs in CodeSplash

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
01

Baskets into rules

Read

An 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=P(A and B)confidence=P(B∣A)lift=P(B∣A)P(B)\text{support} = P(A \text{ and } B) \qquad \text{confidence} = P(B \mid A) \qquad \text{lift} = \frac{P(B \mid A)}{P(B)}
  • 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.
02

Work one out

Checkpoint

Check 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.

03

Make a guess

Predict

Predict first

Bananas are in most baskets, whether or not butter is. Confidence of butter → bananas will be high. What about the lift?

Well above 1Close to 1Well below 1
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.

04

Trap the rule

Explore

CExplorable · 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?

1.50
How sure?
0.70
0.03
0.30

Rank rules by

1000
RuleSupportConfidenceLift
beer → diapers0.0760.533.82
diapers → beer0.0760.553.82
beer + bananas → diapers0.0520.533.81
diapers + bananas → beer0.0520.533.68
butter + coffee → bread0.0320.863.08
butter + bananas → bread0.1290.853.02
bread → butter0.1730.622.95
butter → bread0.1730.832.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 first; the figure appears when you commit.

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.

05

Read the card

Read
Association rulesRecorded · Python and R agreeRecorded 2026-11-25 · 81 values compared
R

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

Plots

Rules: support × confidence (color = lift)Which item combinations co-occur often and reliably, beyond chance?
View data
ConfidenceRuleLiftSupport
0.8511{Age=Adult, Class=2nd, Survived=Yes} => {Sex=Female}3.9860.0363
1{Age=Child, Survived=No} => {Class=3rd}3.1180.0236
1{Age=Child, Sex=Male, Survived=No} => {Class=3rd}3.1180.0159
1{Age=Child, Sex=Female, Survived=No} => {Class=3rd}3.1180.0077
1{Age=Child, Class=2nd} => {Survived=Yes}3.0960.0109
1{Age=Child, Class=2nd, Sex=Female} => {Survived=Yes}3.0960.0059
0.9724{Class=1st, Sex=Female} => {Survived=Yes}3.0100.0641
0.9722{Age=Adult, Class=1st, Sex=Female} => {Survived=Yes}3.0100.0636
0.8774{Class=2nd, Sex=Female} => {Survived=Yes}2.7160.0423
0.8696{Age=Adult, Class=Crew, Sex=Female} => {Survived=Yes}2.6920.0091
0.8696{Class=Crew, Sex=Female} => {Survived=Yes}2.6920.0091
0.8602{Age=Adult, Class=2nd, Sex=Female} => {Survived=Yes}2.6630.0363
0.8413{Sex=Female, Survived=No} => {Class=3rd}2.6230.0482
0.8165{Age=Adult, Sex=Female, Survived=No} => {Class=3rd}2.5460.0404
0.9167{Age=Adult, Class=2nd, Sex=Male} => {Survived=No}1.3540.0700
0.8603{Class=2nd, Sex=Male} => {Survived=No}1.2710.0700
0.9955{Age=Adult, Class=Crew, Survived=No} => {Sex=Male}1.2660.3044
0.9955{Class=Crew, Survived=No} => {Sex=Male}1.2660.3044
0.9740{Age=Adult, Class=Crew} => {Sex=Male}1.2380.3916
0.9740{Class=Crew} => {Sex=Male}1.2380.3916
0.8377{Age=Adult, Class=3rd, Sex=Male} => {Survived=No}1.2370.1758
0.9672{Age=Adult, Class=1st, Survived=No} => {Sex=Male}1.2300.0536
0.9672{Class=1st, Survived=No} => {Sex=Male}1.2300.0536
0.8275{Class=3rd, Sex=Male} => {Survived=No}1.2220.1917

Association rules

IfThenSupportConfidenceLiftLeverageConvictionCount
{Age=Adult, Class=2nd, Survived=Yes}{Sex=Female}0.03630.85113.9860.02725.28180
{Age=Child, Survived=No}{Class=3rd}0.023613.1180.0160—52
{Age=Child, Sex=Male, Survived=No}{Class=3rd}0.015913.1180.0108—35
{Age=Child, Sex=Female, Survived=No}{Class=3rd}0.007713.1180.0052—17
{Age=Child, Class=2nd}{Survived=Yes}0.010913.0960.0074—24
{Age=Child, Class=2nd, Sex=Female}{Survived=Yes}0.005913.0960.0040—13
{Class=1st, Sex=Female}{Survived=Yes}0.06410.97243.0100.042824.540141
{Age=Adult, Class=1st, Sex=Female}{Survived=Yes}0.06360.97223.0100.042524.371140
{Class=2nd, Sex=Female}{Survived=Yes}0.04230.87742.7160.02675.52093
{Age=Adult, Class=Crew, Sex=Female}{Survived=Yes}0.00910.86962.6920.00575.19020
{Class=Crew, Sex=Female}{Survived=Yes}0.00910.86962.6920.00575.19020
{Age=Adult, Class=2nd, Sex=Female}{Survived=Yes}0.03630.86022.6630.02274.84380
{Sex=Female, Survived=No}{Class=3rd}0.04820.84132.6230.02984.279106
{Age=Adult, Sex=Female, Survived=No}{Class=3rd}0.04040.81652.5460.02463.70289
{Age=Adult, Class=2nd, Sex=Male}{Survived=No}0.07000.91671.3540.01833.876154
{Class=2nd, Sex=Male}{Survived=No}0.07000.86031.2710.01492.313154
{Age=Adult, Class=Crew, Survived=No}{Sex=Male}0.30440.99551.2660.063947.904670
{Class=Crew, Survived=No}{Sex=Male}0.30440.99551.2660.063947.904670
{Age=Adult, Class=Crew}{Sex=Male}0.39160.97401.2380.07548.217862
{Class=Crew}{Sex=Male}0.39160.97401.2380.07548.217862
{Age=Adult, Class=3rd, Sex=Male}{Survived=No}0.17580.83771.2370.03371.990387
{Age=Adult, Class=1st, Survived=No}{Sex=Male}0.05360.96721.2300.01006.513118
{Class=1st, Survived=No}{Sex=Male}0.05360.96721.2300.01006.513118
{Class=3rd, Sex=Male}{Survived=No}0.19170.82751.2220.03491.872422

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"))
))
Python

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

IfThenSupportConfidenceLiftLeverageConvictionCount
{Age=Adult, Class=2nd, Survived=Yes}{Sex=Female}0.03630.85113.9860.02725.28180
{Age=Child, Survived=No}{Class=3rd}0.023613.1180.0160—52
{Age=Child, Sex=Male, Survived=No}{Class=3rd}0.015913.1180.0108—35
{Age=Child, Sex=Female, Survived=No}{Class=3rd}0.007713.1180.0052—17
{Age=Child, Class=2nd}{Survived=Yes}0.010913.0960.0074—24
{Age=Child, Class=2nd, Sex=Female}{Survived=Yes}0.005913.0960.0040—13
{Class=1st, Sex=Female}{Survived=Yes}0.06410.97243.0100.042824.540141
{Age=Adult, Class=1st, Sex=Female}{Survived=Yes}0.06360.97223.0100.042524.371140
{Class=2nd, Sex=Female}{Survived=Yes}0.04230.87742.7160.02675.52093
{Age=Adult, Class=Crew, Sex=Female}{Survived=Yes}0.00910.86962.6920.00575.19020
{Class=Crew, Sex=Female}{Survived=Yes}0.00910.86962.6920.00575.19020
{Age=Adult, Class=2nd, Sex=Female}{Survived=Yes}0.03630.86022.6630.02274.84380
{Sex=Female, Survived=No}{Class=3rd}0.04820.84132.6230.02984.279106
{Age=Adult, Sex=Female, Survived=No}{Class=3rd}0.04040.81652.5460.02463.70289
{Age=Adult, Class=2nd, Sex=Male}{Survived=No}0.07000.91671.3540.01833.876154
{Class=2nd, Sex=Male}{Survived=No}0.07000.86031.2710.01492.313154
{Age=Adult, Class=Crew, Survived=No}{Sex=Male}0.30440.99551.2660.063947.904670
{Class=Crew, Survived=No}{Sex=Male}0.30440.99551.2660.063947.904670
{Age=Adult, Class=Crew}{Sex=Male}0.39160.97401.2380.07548.217862
{Class=Crew}{Sex=Male}0.39160.97401.2380.07548.217862
{Age=Adult, Class=3rd, Sex=Male}{Survived=No}0.17580.83771.2370.03371.990387
{Age=Adult, Class=1st, Survived=No}{Sex=Male}0.05360.96721.2300.01006.513118
{Class=1st, Survived=No}{Sex=Male}0.05360.96721.2300.01006.513118
{Class=3rd, Sex=Male}{Survived=No}0.19170.82751.2220.03491.872422

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.

06

Filter and sort

Read

On 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.

07

Rules aren't causes

Read

Mining 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.

08

Check your understanding

Checkpoint

Check 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.

09

Do it on your own data

In the app

Choose Co-occurring items. The method takes either one row per transaction and item, or one row per transaction with true/false item columns.

Python
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())
R
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))
10

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