Note
Go to the end to download the full example code or to run this example in your browser via Binder.
First steps: four sequences of the PrefixSpan paper#
The database of Pei et al. (2001) has four customers; each bought itemsets
(several items at once) in a sequence. A sequential pattern is a sequence of
itemsets contained, in order, in at least min_support customers. We mine the
patterns contained in at least half of the customers and show them as a glyph
table: events as colored tiles, simultaneous items stacked, the support and the
confidence of the last extension as bars.
The data and the patterns#
import matplotlib.pyplot as plt
import spmviz as sv
from spmviz.viz import plot_patterns
db = sv.datasets.load_prefixspan_example()
for sid, s in zip(db.ids, db):
print(sid, sv.format_pattern(s, "angle"))
ps = sv.mine(db, min_support=0.5) # in at least 2 of the 4 sequences
print(len(ps), "frequent sequential patterns")
print(ps.to_frame().head(12)[["pattern", "support", "confidence"]])
10 ⟨a (abc) (ac) d (cf)⟩
20 ⟨(ad) c (bc) (ae)⟩
30 ⟨(ef) (ab) (df) c b⟩
40 ⟨e g (af) c b c⟩
53 frequent sequential patterns
pattern support confidence
0 a 4 1.0
1 b 4 1.0
2 c 4 1.0
3 d 3 1.0
4 e 3 1.0
5 f 3 1.0
6 a → a 2 0.5
7 a → b 4 1.0
8 a → c 4 1.0
9 a → d 2 0.5
10 a → f 2 0.5
11 (a, b) 2 0.5
A glyph table of the longest patterns#
Long patterns are the interesting ones; sort("length") puts them first.
plot_patterns(ps.filter(min_length=3), top=12, by="length")

<Figure size 1080x552 with 3 Axes>
Closed and maximal patterns#
Many of the 53 patterns repeat each other: a pattern is closed if no longer pattern has the same support, maximal if no longer pattern is frequent at all. The lossless closed set and the compact maximal set are what we usually draw.
print(len(ps.closed()), "closed,", len(ps.maximal()), "maximal")
print(ps.maximal().labels("angle"))
17 closed, 10 maximal
['⟨a b c⟩', '⟨a c c⟩', '⟨(ab) f⟩', '⟨d c b⟩', '⟨e b c⟩', '⟨f b c⟩', '⟨a (bc) a⟩', '⟨(ab) d c⟩', '⟨e a c b⟩', '⟨e f c b⟩']
Parameter study: the minimum support#
Lowering the threshold makes the number of patterns explode; the closed and the maximal sets grow much more slowly.
counts = sv.measures.pattern_counts(db, [1.0, 0.75, 0.5, 0.25])
print(counts)
sv.viz.plot_explosion(counts)
plt.show()

min_support all closed maximal max_length
0 1.00 5 2 2 2
1 0.75 14 8 6 3
2 0.50 53 17 10 4
3 0.25 812 21 4 9
Total running time of the script: (0 minutes 0.363 seconds)