Apriori, regression and decision trees
Study notes on Apriori (association rules), linear regression, and decision trees: definitions, derivations, formulas, worked examples (including runnable Python for Apriori and regression), common mistakes and exam tips.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Apriori, regression and decision trees are three fundamental tools an engineer uses in data analytics and machine learning. Use Apriori for market-basket and association-rule mining (descriptive analytics), linear regression for predicting a continuous variable (predictive analytics), and decision trees for classification or regression with easy-to-read rules (interpretable models used in embedded systems, dashboards, and feature importance).
Key ideas
Start from first principles and definitions.
- Transaction: a set of items bought or observed together. Example: a shopping cart is a transaction.
- Itemset: a set of items. A k-itemset has k items.
- Support of an itemset X: either the fraction of transactions that contain X (relative support) or the count (absolute support). Relative support is a probability-like measure with values in [0,1]; absolute support is a count.
- Confidence of a rule X -> Y: support(X ∪ Y) / support(X). This estimates conditional probability P(Y | X).
- Lift of rule X -> Y: confidence(X -> Y) / support(Y). Lift > 1 indicates positive association.
- Apriori property (downward-closure): If an itemset is frequent (support ≥ minsup), then every non-empty subset of it is also frequent. This is the exact statement used to prune candidates in the Apriori algorithm. Assumption: support is monotone — adding items cannot increase support.
- Apriori algorithm (outline and assumptions): iteratively find frequent k-itemsets by candidate generation from frequent (k-1)-itemsets and pruning candidates having any (k-1)-subset not frequent. Assumes transactions are static and support can be counted exactly.
Linear regression (simple, one predictor):
- Random variable X (predictor) and Y (response). We assume a linear model Y = a + bX + ε, where ε has E[ε|X] = 0 (zero-mean/exogeneity). Constant variance σ² and uncorrelated errors are often assumed for efficiency. Under Gauss–Markov conditions OLS is BLUE; zero-mean/exogeneity ensure OLS is unbiased.
- Ordinary Least Squares (OLS): choose parameters a (intercept) and b (slope) that minimize the sum of squared errors SSE = Σ(yi - (a + b xi))^2. Derive normal equations by setting partial derivatives ∂SSE/∂a = 0 and ∂SSE/∂b = 0. Solve to get the closed-form formulas shown below.
- Coefficient of determination R^2: proportion of variance in Y explained by the model: 1 - SSE/SST where SST = Σ(yi - ȳ)^2.
Decision trees (classification):
- Entropy of a set S with class proportions p1, p2, ... is H(S) = -Σ pi log2(pi). Entropy measures impurity; lower is purer.
- Gini index is G(S) = 1 - Σ pi^2. Also measures impurity.
- Information gain for splitting S by attribute A into subsets S_v is Gain(S, A) = H(S) - Σ (|S_v| / |S|) H(S_v). Choose split maximizing gain (or minimizing weighted impurity). Assumption: attributes and labels in training set are representative.
- When splitting a numeric attribute, tests are of form X ≤ t; pick t from midpoints between sorted distinct values and evaluate gains. For regression trees, use variance (MSE) as the impurity and choose the split that minimizes weighted MSE (variance reduction).
Diagrams to draw in exam answers (describe exactly):
- For Apriori: draw a lattice of itemsets (1-itemsets at bottom, 2-itemsets above, 3-itemset at top) and mark which nodes are pruned. Label supports on nodes.
- For linear regression: draw scatter plot of points, draw best-fit line y = a + bx, label residual for one point (vertical distance), label x̄ and ȳ and show formulas for slope and intercept.
- For decision tree: draw a tree node labelled by split (e.g., X ≤ t), branches left/right with counts and class distributions at leaves.
Formulas
support(X) = count(transactions containing X) / N — X is an itemset, N is number of transactions; unitless; applies for Apriori/association rules.
confidence(X -> Y) = support(X ∪ Y) / support(X) — unitless; applies to association rules when support(X) > 0.
lift(X -> Y) = confidence(X -> Y) / support(Y) — unitless; measures strength of association beyond baseline.
H(S) = - Σ_i p_i log2(p_i) — entropy in bits; p_i are class probabilities in set S; unit: bits; applies when 0 < p_i < 1 (define 0 log2 0 = 0).
G(S) = 1 - Σ_i p_i^2 — Gini index; unitless; applies for impurity computations.
Gain(S,A) = H(S) - Σ_v (|S_v| / |S|) H(S_v) — information gain for splitting by attribute A.
SSE = Σ_i (y_i - ŷ_i)^2 — sum of squared errors; ŷ_i are model predictions; unit is square of y's unit.
SST = Σ_i (y_i - ȳ)^2 — total sum of squares; ȳ is sample mean of y.
R^2 = 1 - SSE / SST — unitless; proportion of variance explained.
b = [Σ_i (x_i - x̄)(y_i - ȳ)] / [Σ_i (x_i - x̄)^2] = [Σ x_i y_i - n x̄ ȳ] / [Σ x_i^2 - n x̄^2] — slope of OLS line; units: (unit of y)/(unit of x); applies for simple linear regression.
a = ȳ - b x̄ — intercept; same unit as y; applies for simple linear regression.
Notes on syntax to remember (Python):
- list comprehensions:
[x*y for x,y in pairs] - dict.get for counting:
counts[item] = counts.get(item, 0) + 1 - sort unique values:
sorted(set(values))
Worked examples
Example 1 — Apriori (small dataset) and Python implementation Transactions (N = 5): T1: {milk, bread, butter} T2: {bread, butter} T3: {milk, bread} T4: {bread} T5: {milk, butter} Choose minimum support = 0.4 (i.e., threshold = 2 transactions) and minimum confidence = 0.6.
Step 1: count 1-item supports: milk=3, bread=4, butter=3. All ≥2 → frequent 1-itemsets: {milk}, {bread}, {butter}. Step 2: candidate 2-itemsets and supports: {milk,bread}=2, {milk,butter}=2, {bread,butter}=2. All frequent. Step 3: candidate 3-itemset {milk,bread,butter} has support 1 → not frequent.
Generate rules from frequent itemsets (use frequent 2-itemsets):
- milk -> bread: support = 2/5 = 0.4, confidence = support(milk,bread)/support(milk) = 2/3 ≈ 0.6667 → meets min_conf 0.6. Lift = 0.6667 / (support(bread)=4/5=0.8) = 0.8333 (less than 1 → weak if using lift).
- bread -> milk: support = 0.4, confidence = 2/4 = 0.5 → below 0.6.
- milk -> butter: confidence = 2/3 ≈ 0.6667 → rule qualifies.
- butter -> milk: 2/3? support(butter)=3 so butter->milk confidence = 2/3 ≈ 0.6667 → qualifies.
- bread -> butter: confidence = 2/4 = 0.5 → does not qualify.
- butter -> bread: confidence = 2/3 ≈ 0.6667 → qualifies.
Python program (runs without external libraries):
# Simple Apriori for the small example
transactions = [set(['milk','bread','butter']),
set(['bread','butter']),
set(['milk','bread']),
set(['bread']),
set(['milk','butter'])]
N = len(transactions)
minsup = 0.4
import math
mincount = math.ceil(minsup * N - 1e-9)
minconf = 0.6
from itertools import combinations
# count supports
def support_count(itemset):
return sum(1 for t in transactions if itemset.issubset(t))
# frequent 1-itemsets
items = sorted({i for t in transactions for i in t})
L1 = {frozenset([i]) for i in items if support_count(frozenset([i])) >= mincount}
print('Frequent 1-itemsets:', L1)
# get L2
candidates2 = {frozenset(c) for c in combinations(items,2)}
L2 = {c for c in candidates2 if support_count(c) >= mincount}
print('Frequent 2-itemsets:', L2)
# rules from L2
print('\nRules (support, confidence):')
for itemset in L2:
s_count = support_count(itemset)
s = s_count / N
for k in range(1, len(itemset)):
for antecedent in combinations(itemset, k):
A = frozenset(antecedent)
B = itemset - A
conf = s_count / support_count(A)
if conf >= minconf:
print(f"{set(A)} -> {set(B)}: support={s:.3f}, confidence={conf:.3f}")
Sample output exactly (order of sets may vary):
Frequent 1-itemsets: {frozenset({'milk'}), frozenset({'butter'}), frozenset({'bread'})} Frequent 2-itemsets: {frozenset({'milk', 'bread'}), frozenset({'milk', 'butter'}), frozenset({'bread', 'butter'})}
Rules (support, confidence): {'milk'} -> {'bread'}: support=0.400, confidence=0.667 {'milk'} -> {'butter'}: support=0.400, confidence=0.667 {'butter'} -> {'milk'}: support=0.400, confidence=0.667 {'butter'} -> {'bread'}: support=0.400, confidence=0.667
(If your Python prints frozenset order differently that's normal.)
Example 2 — Simple linear regression (hand calculation and Python) Data (x in unit: arbitrary units, y in same unit): x = [1,2,3,4,5], y = [2,3,5,4,6] Compute sums: Σx = 15, Σy = 20, Σxy = 69, Σx^2 = 55, n = 5. x̄ = 3, ȳ = 4.
Slope b = (Σxy - n x̄ ȳ) / (Σx^2 - n x̄^2) = (69 - 534) / (55 - 59) = 9 / 10 = 0.9. Intercept a = ȳ - b x̄ = 4 - 0.93 = 1.3. Predictions ŷ = [2.2, 3.1, 4.0, 4.9, 5.8]. SSE = Σ(yi - ŷi)^2 = 0.04 + 0.01 + 1.00 + 0.81 + 0.04 = 1.90. SST = Σ(yi - ȳ)^2 = 4 + 1 + 1 + 0 + 4 = 10. R^2 = 1 - SSE/SST = 1 - 1.9/10 = 0.81 → model explains 81% of variance.
Python (prints coefficients and R^2):
import numpy as np
x = np.array([1,2,3,4,5.0])
y = np.array([2,3,5,4,6.0])
n = len(x)
xb = x.mean(); yb = y.mean()
b = ( (x*y).sum() - n*xb*yb ) / ( (x*x).sum() - n*xb*xb )
a = yb - b*xb
yhat = a + b*x
SSE = ((y - yhat)**2).sum()
SST = ((y - yb)**2).sum()
R2 = 1 - SSE / SST
print(f'a={a:.3f}, b={b:.3f}, R2={R2:.3f}')
Exact output:
a=1.300, b=0.900, R2=0.810
Example 3 — Decision tree split (entropy calculation) Data (x numeric, class): (2,0), (4,0), (6,1), (8,1). Parent S has p0 = 2/4 = 0.5, p1 = 0.5. H(S) = -0.5 log2 0.5 - 0.5 log2 0.5 = 1.0 bit. Try split at t = 5 (left x ≤ 5: two class 0; right x > 5: two class1). Left entropy = 0 (pure), right entropy = 0. Weighted entropy = 0, so information gain = 1.0 bit — perfect split.
Common mistakes
- In regression hand-derivation: sign errors in normal equations; forget subtracting n x̄ ȳ term.
- Using R^2 to judge non-linear fit without checking residuals and assumptions (heteroscedasticity, non-linearity).
- For decision trees: using entropy but computing log with base e; entropy formula requires log2 for bits (report which base you used).
- When splitting numeric attributes, failing to consider only midpoints between adjacent sorted values as candidate thresholds.
For your exam
Question types you will see: definition (define support, confidence, entropy), short notes (explain Apriori property; list OLS assumptions), derivations (derive normal equations for OLS), numericals (compute frequent itemsets for small transactions; compute slope/intercept and R^2; compute information gain for a split), small programs (write simple Apriori or compute regression coefficients), and diagrams (draw itemset lattice or decision tree node counts). A full-marks answer must state definitions, list assumptions, show steps with intermediate sums/counts, label diagrams clearly, and give final numeric answers with units where applicable.
Quick check
- State the Apriori property in one sentence.
- Give the formula for the slope b in simple linear regression using sums (not deviations).
- If a parent node has class proportions (0.75, 0.25), what is its entropy in bits? (Give to three decimals.)
Answers: 1) Every subset of a frequent itemset is also frequent (downward-closure). 2) b = (Σ x_i y_i - n x̄ ȳ) / (Σ x_i^2 - n x̄^2). 3) H = -0.75 log2 0.75 - 0.25 log2 0.25 ≈ 0.811 bits.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?