smartyfy.mrindigi.com

AI & Machine Learning Master Course — 089. Association and pattern discovery

Smartyfy AI & Machine Learning Master Course

Course ID: smartyfy-ai-ml-master-200

Lesson 089: Association and pattern discovery

Prerequisites: Lesson 088. Learning outcome: Assess frequent patterns while guarding against spurious discoveries.

Find co-occurrence before telling a story

Association-rule mining summarizes which items occur together in a collection of transactions. A transaction could be a shopping basket, a set of document tags, or a set of diagnostic events within a defined time window. The meaning of a rule depends on that transaction definition.

A rule A implies B describes an observed conditional association: among transactions containing A, how often is B also present? It does not state that A occurred before B or that adding A would cause B. If timestamps matter, ordinary unordered itemsets discard that information and cannot answer a sequence question.

Start by specifying the unit. Treating each receipt as a transaction differs from merging all purchases by one customer across a month. Duplicated receipts inflate counts; repeated items within a set do not represent quantity. Those choices can change the discovered rules more than the mining algorithm does.

Support, confidence, and lift

Support of an itemset is the fraction of transactions containing all its items. Rule confidence for A implies B is support of A and B divided by support of A. Lift divides confidence by support of B. Lift compares the observed conditional frequency with B's overall frequency.

Suppose ten transactions contain A four times, B five times, and both three times. Support of the rule is 3/10 = 0.3. Confidence is 3/4 = 0.75. Lift is 0.75/0.5 = 1.5. Within these observations, B is one and a half times as frequent among A transactions as overall.

Confidence alone can look impressive when B is common. If B appears in 90 percent of all transactions, a rule with 90 percent confidence has lift one and adds no association relative to that baseline. Conversely, a rare consequent can create high lift from only a handful of co-occurrences. Always report counts and support alongside ratios.

Ten transaction tiles contain four A baskets, five B baskets and three AB baskets. These yield support 0.30, confidence 0.75, baseline 0.50 and lift 1.50.
Counts reveal the denominators behind an apparently strong rule. Open full-size diagram

A compact count table

Ten synthetic transactions, with A as rows and B as columns
A status B present B absent
A present 3 1
A absent 2 4

Why frequent-pattern search can explode

With many possible items, the number of candidate itemsets grows rapidly. Apriori-style reasoning exploits a useful monotonicity property: adding items cannot increase support. Every transaction containing A and B and C also contains A and B. If a smaller itemset already fails a minimum-support threshold, any superset must fail too.

This pruning property applies to support, not automatically to confidence or lift. A longer rule can have larger or smaller confidence depending on the added condition. Do not assume every metric shares the same monotonicity just because support does.

Minimum support controls computational and statistical fragility, but there is no universal good value. A rare safety-relevant event may deserve attention despite low support, while a common operational pattern may be uninteresting. Separate a broad discovery search from any subsequent decision or formal hypothesis test.

CPU lab: calculate one rule exactly

The standalone code creates ten small sets and counts A, B, and their intersection. Python Fraction verifies support 3/10 and confidence 3/4 exactly. Lift is 1.5. No pattern-mining package is installed or required; the optional mlxtend documentation is linked for a fuller implementation.

The code also computes a one-sided Fisher exact test for positive association using the displayed two-by-two table. Its p-value is approximately 0.261905. This is an illustrative, exploratory calculation, not evidence that the mined rule is confirmed. Python 3.12, SciPy 1.17.0, and CPU execution were used. The ten transactions are invented, so the exercise demonstrates arithmetic and interpretation rather than a commercial recommendation.

from fractions import Fraction
from scipy.stats import fisher_exact
baskets = [set('AB'), set('AB'), set('AB'), set('AC'), set('BC'),
           set('B'), set('C'), set('C'), set('C'), set('D')]
n = len(baskets)
count = lambda items: sum(set(items) <= b for b in baskets)
a, b, both = count('A'), count('B'), count('AB')
support = Fraction(both, n)
confidence = Fraction(both, a)
lift = confidence / Fraction(b, n)
print('counts A B AB', a, b, both)
print('support', float(support), 'confidence', float(confidence), 'lift', float(lift))
table = [[both, a - both], [b - both, n - a - b + both]]
print('2x2 counts', table)
print('one-sided exploratory p', round(fisher_exact(table, alternative='greater').pvalue, 6))
assert support == Fraction(3, 10) and confidence == Fraction(3, 4)

Control the discovery-to-confirmation gap

A search across thousands of itemsets can produce striking ratios by chance. Reporting only the largest lift hides the number of opportunities for a spurious discovery. Formal testing requires a justified null, appropriate handling of repeated or dependent transactions, and a plan for multiple comparisons or independent confirmation.

Fisher's exact test for a prespecified two-by-two comparison conditions on the margins under its null. Applying it after selecting the most extreme rule from the same data does not erase the selection process. A development period can generate candidate rules, followed by a fresh period where the candidates and evaluation criteria are frozen.

Also inspect confounding and aggregation. Two items may co-occur because both are common in one store, season, or customer segment. Pooling groups can create or hide an association. A campaign based on the rule needs a separate intervention design if the question is whether suggesting B after A changes behavior.

Make rules understandable and useful

Show antecedent, consequent, transaction definition, counts, support, confidence, lift, and evaluation period. Avoid a huge unranked rule dump. Remove exact duplicates and explain overlapping rules so readers do not count the same evidence repeatedly.

Use neutral wording such as these items co-occurred more often than their marginal frequencies suggest in this dataset. If the proposed action has costs, compare it with a simple baseline and test whether the rule improves the desired outcome. Association discovery is a source of hypotheses; validation determines whether those hypotheses deserve action.

Four practice questions with worked answers

Practice 1

Compute the reverse rule B implies A for the example.

Answer: Support remains 3/10. Confidence becomes 3/5 = 0.6, because B appears five times. Lift is 0.6/0.4 = 1.5. Direction changes confidence but not this pairwise lift.

Practice 2

Why can an infrequent pair prune all its supersets under a support threshold?

Answer: Every transaction containing a superset also contains the pair. Therefore a superset’s support cannot exceed the pair’s support and cannot pass a threshold the pair already fails.

Practice 3

A consequent has support 0.8 and a rule has confidence 0.8. What is lift?

Answer: Lift is 0.8/0.8 = 1. The rule’s conditional frequency matches the consequent’s baseline frequency, despite the seemingly high 80 percent confidence.

Practice 4

A rule was chosen because it had the largest lift among 10,000 candidates. Is its unadjusted p-value a clean confirmatory test?

Answer: No. Selection among many candidates changes the inferential context. Use a justified multiplicity procedure or freeze candidates and evaluate on independent data, while also accounting for transaction dependence.

Five multiple-choice questions

Question 1

What does rule confidence estimate descriptively?

  • A. The fraction of antecedent transactions also containing the consequent
  • B. The probability that the rule is causally true
  • C. The fraction of all transactions containing only the consequent

Correct: A. Confidence is a conditional co-occurrence frequency.

Question 2

Why report support with lift?

  • A. Lift already supplies the exact sample count
  • B. Support proves the rule is causal
  • C. Large lift can be based on very few transactions

Correct: C. Counts reveal how much evidence supports the ratio.

Question 3

Which property enables Apriori support pruning?

  • A. Every longer rule has lower confidence
  • B. A superset cannot have greater support than its subset
  • C. Every rare item has lift below one

Correct: B. The set-containment relationship makes support antimonotone.

Question 4

What does the implication arrow establish?

  • A. That intervening on the antecedent changes the consequent
  • B. That the antecedent happened first
  • C. A conditional association rule, not temporal or causal order

Correct: C. Unordered transaction sets do not encode sequence or intervention effects.

Question 5

What is a sensible next step after broad discovery?

  • A. Freeze candidate rules and test them on appropriate new evidence
  • B. Declare all high-lift rules confirmed
  • C. Treat repeated transactions as independent without checking

Correct: A. Independent confirmation and dependence-aware analysis address discovery bias.

Common pitfalls

Do not equate confidence with certainty, lift with causality, or a small exploratory p-value with post-selection confirmation. Define transactions carefully and inspect counts, dependencies, and confounding. A large rule list is not automatically a useful decision system.

Summary

Association rules quantify co-occurrence using support, confidence, and lift. Their arithmetic is simple; trustworthy discovery requires careful transaction design, transparent search scope, and independent evidence before action.

Primary sources and further reading