Chapter 2
Sequences, patterns and their mining
Every view of the book draws either a database of sequences or a set of frequent sequences mined from it, so this chapter fixes the vocabulary: sequences of itemsets, containment under gap, span and time constraints, support, the condensed representations of a pattern set, and the extension tree whose confidences the network-based views draw. It then explains the four mining strategies implemented in spmviz — pattern growth, vertical bitmaps, vertical id-lists and level-wise search — and closes with the data model of the package and examples on small and everyday data.
2.1 Problem and idea
A customer buys several items at once, then returns a week later; an operator acknowledges two alarms in the same second. Such data are sequences of itemsets: sets of events that happen together, ordered in time. A pattern is itself a sequence of itemsets, and the basic question of sequential pattern mining is in how many sequences of the database a pattern occurs, its elements in the right order, each element contained in a distinct element of the sequence [6]. The question has two refinements that matter in practice. Occurrences can be restricted, for instance to consecutive elements or to a time window, because a pattern that joins events hours apart may describe nothing real [7]. And the answer is wanted for all patterns at once that occur in enough sequences, which is a search problem over an exponentially large space, made tractable by the fact that a pattern cannot be more frequent than its prefixes.
2.2 Theory
2.2.1 Sequences and containment
Let be a finite set of items (events, pages, alarms). An itemset is a non-empty subset of , a sequence an ordered list of itemsets, its elements; the length of is the total number of items . When every element is a single item we write ; parentheses group simultaneous items, as in . A sequence database is a list of sequences, each with an identifier and possibly a timestamp for each element and attributes (device, group, outcome) for the whole sequence.
A sequence is contained in , written , if there are indices with for every ; the indices form an occurrence of . Constraints restrict the admissible occurrences [7, 26]:
- a gap constraint bounds the distance of consecutive matched elements, ; following the convention of SPMF [28], requires adjacent elements and allows one element in between;
- a span constraint bounds the whole occurrence, ;
- with timestamps, both bounds can be applied to and instead of the indices.
The support is the number of sequences of that contain under the constraints, and the relative support is . Given a threshold , the set of frequent sequences or sequential patterns is . Figure 2.1 shows the four-sequence database of the PrefixSpan paper [30], the running toy example of this chapter.
2.2.2 Anti-monotonicity and the extension tree
Without constraints, every subsequence of a sequence contained in is contained in as well, so implies : support is anti-monotone, and is closed under taking subsequences. This is the property that makes mining feasible. Gap constraints weaken it: deleting a middle element of an occurrence with leaves a gap of two, so a subsequence of a frequent sequence need not be frequent. Prefixes survive, however, because truncating an occurrence after its -th element keeps every gap and shortens the span. Under all constraints of section 2.2.1 the set is therefore prefix-closed.
The parent of a pattern is the pattern without its last item; conversely is a one-item extension of , either a sequence extension that appends a new element, , or an itemset extension that adds an item to the last element, [8, 10]. The parent relation turns a prefix-closed into a forest whose roots are the frequent single items: the extension tree. Its edges carry the confidence of the extension, the share of the sequences containing the parent that also contain the child,
| (2.1) |
where is the first item of and the product runs over the patterns on the path from to . The cumulative confidence is the share of the sequences starting the tree that reach . Bántay and Abonyi draw exactly this tree, with these weights, in their weighted network view (chapter 4) [1]. The confidence of the last extension is related to classical rule measures: if is the added item, the lift compares it with the frequency of alone, and lifts well above one mark extensions that are more than coincidences.
2.2.3 Condensed representations
A frequent sequence of length without constraints implies that all its non-empty subsequences are frequent, so explodes when long patterns exist. Three condensed sets are standard [31, 32, 33, 34, 35]:
- a pattern is closed if no super-pattern has the same support; the closed patterns determine the support of every frequent pattern, so the representation is lossless;
- a pattern is maximal if no super-pattern is frequent; the maximal patterns determine which patterns are frequent, but not their supports;
- a pattern is a generator if no sub-pattern has the same support; generators are the minimal patterns of their support class.
When no sensible threshold is known, top- mining returns the most frequent patterns, raising the threshold internally as better patterns are found [36]. Other generalizations of the pattern concept appear later in the book: sequential rules, which split a pattern into an antecedent and a consequent (chapter 7) [37], and episodes, frequent patterns of one long event stream without case boundaries (chapter 8) [38].
2.3 Mining algorithms
All exact miners of the package enumerate the extension tree depth first or level by level and stop at infrequent nodes; prefix-closure guarantees that nothing frequent lies below them. They differ in how they compute the supports of the candidate extensions (algorithm 2.1).
PrefixSpan [8, 30] grows patterns in projected databases: the sequences that contain , cut after the place where an occurrence of ends, contain every frequent extension of in their suffixes. The package uses pseudo-projection (pointers instead of copies) and, when a gap or span constraint is set, a map from each possible end point of an occurrence to its latest start, which is all a constrained extension needs. SPAM [10] represents a pattern by one bit per element of every sequence, set where an occurrence of the pattern can end. A sequence extension by is the bitmap of shifted to the right (all positions after the first set bit, or only the next positions under a gap constraint) and intersected with the bitmap of ; an itemset extension is a plain intersection. In Python the bitmaps of all sequences are packed into one arbitrary-precision integer, so the shift and the intersection run as single machine-level operations. CM-SPAM [11], the algorithm used in the NBVFS paper, adds a co-occurrence map that discards extensions whose two-item pattern (or ) is infrequent. SPADE [9] stores for every pattern the list of (sequence, end position) pairs and joins two lists to obtain the occurrences of an extension. GSP [7] is the level-wise, Apriori-style algorithm: it is the slowest of the five but the simplest to reason about, and it serves as an independent check.
The five algorithms return identical pattern sets. The test suite of the package compares them with each other and with a brute-force enumeration on random databases with itemsets, gaps and timestamps, and section 2.6 compares them on synthetic click streams. Their speeds differ. On the benchmark databases of chapter 10 the bitmap algorithms, SPAM and CM-SPAM, are the fastest without constraints, because a Python integer operation processes all sequences at once; with a gap constraint PrefixSpan and CM-SPAM are comparable, and GSP is 30 to 370 times slower.
2.4 The data model of spmviz
Two classes carry the data of every analysis. A SequenceDatabase stores sequences of itemsets as tuples of tuples, with identifiers, optional timestamps per element, optional attributes per sequence (a pandas data frame) and optional display labels for the items. It is built from Python lists, strings, wide or long tables, event logs with case, activity and timestamp columns, SPMF files, XES files and pm4py logs (chapter 9). A PatternSet stores the patterns in the same canonical form together with their supports, the identifiers of their supporting sequences, the database and the mining parameters. Because the supporting sequences are kept, every measure and view can be computed afterwards without mining again: confidences, closed and maximal subsets, incidence and similarity matrices, rules, contrasts between groups.
Patterns can be written in several ways. "a (b c) d" separates items by spaces and groups simultaneous items in parentheses; the arrow notation "wake up -> coffee -> (tv, read)", the default output of format_pattern, allows items with spaces; "1 -1 2 3 -1" is the SPMF format. db.pattern(...) resolves a pattern written with the labels of a database to its items. Table 2.1 summarizes the notation of the book and its counterparts in the code.
| Symbol | Meaning | Code |
| item alphabet | db.alphabet |
|
| , | sequence database and its number of sequences | SequenceDatabase, len(db) |
| sequence of itemsets | db[i] (tuple of tuples) |
|
| is contained in (under the constraints) | db.contains(p) |
|
| gap and span bounds (index or time units) | min_gap, max_gap, max_span, gap_unit |
|
| , | support and relative support | ps.support, rel_support |
| set of frequent sequences | PatternSet |
|
| parent: without its last item | parent_pattern(p) |
|
| , | confidence and cumulative confidence, eq. (2.1) | ps.confidence(), cum_confidence() |
| pattern–sequence incidence matrix | ps.incidence() |
|
| , | confidence matrix and its max-product closure (chapter 4) | confidence_matrix, transitive_confidence |
| , | similarity and dissimilarity of patterns | similarity_matrix |
In a nutshell: Sequences and patterns
- A pattern is contained in a sequence if its itemsets are subsets of distinct elements in the same order; gap, span and time constraints restrict the occurrences.
- Support is anti-monotone without constraints; with gap constraints the frequent sequences are still prefix-closed, so they form the extension tree.
- Confidence weights the edges of the tree; the cumulative confidence is the product along the path.
- Closed patterns are a lossless summary, maximal patterns a compact one; top- mining avoids choosing a threshold.
- PrefixSpan, SPAM, CM-SPAM, SPADE and GSP return the same patterns and differ only in speed.
2.5 Using it in spmviz
sv.mine(db, min_support, ...) is the single entry point: min_support is a share of the sequences (rounded up, as in SPMF) or an absolute count, algorithm is "prefixspan", "cmspam", "spam", "spade", "gsp" or an external back end, and "auto" picks CM-SPAM unless a span or time constraint or top- mining calls for PrefixSpan. max_gap, min_gap, max_span, gap_unit, min_length and max_length set the constraints, and closed=True or maximal=True condense the result. sv.topk(db, k) returns the most frequent patterns. The results compare like Python objects: two pattern sets are identical when their patterns and support attributes are equal.
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"]])
print(len(ps.closed()), "closed,", len(ps.maximal()), "maximal") print(ps.maximal().labels("angle"))
2.6 Examples
A textbook database. At the four sequences of fig. 2.1 contain 53 frequent sequences, 17 of them closed and 10 maximal. The glyph table of fig. 2.2 draws every pattern as a row of colored tiles, simultaneous items stacked, with bars for its support and confidence; it is the most compact faithful picture of a short pattern list. Figure 2.3 shows how the set grows when the threshold falls: at a quarter of the sequences there are 812 frequent sequences, but only 21 closed and 4 maximal ones.
An everyday example. The generator make_daily_routines produces days of three kinds of people — early birds, commuters and remote workers — as sequences of activities from waking up to going to sleep. Three hundred days have 19 activities and between 9 and 16 steps. The sunburst of fig. 2.4 summarizes how the days begin before anything is mined; fig. 2.5 draws the 96 frequent sequences found at 30% support when one activity may be skipped (), as a tree that keeps the three most frequent continuations of every node.
db = sv.datasets.make_daily_routines(300, random_state=0) print(db.stats()) print(sv.format_pattern(db[0])) plot_sunburst(db, max_depth=4, title="how the days begin")
ps = sv.mine(db, min_support=0.3, max_gap=2, max_length=6) print(ps) plot_prefix_tree(ps, max_depth=4, max_children=3, title="frequent sequences as a tree (three most frequent continuations per node)")
Open in ColabExample plot_02_daily_routines.py in the gallery
The gap matters more than the threshold here: with only 25 sequences are frequent, with 96, with 346, and without a gap constraint 1425, most of them joining activities hours apart. The glyph table of the ten most supported patterns of length at least three is fig. 2.6.
Five algorithms, one answer. On a thousand synthetic web-shop journeys (make_customer_journeys), the five built-in miners and the prefixspan package return the same 890 patterns at 3% support; the run times are compared in fig. 2.7.
results, times = {}, {} for alg in ["prefixspan", "cmspam", "spam", "spade", "gsp"]: t0 = time.perf_counter() results[alg] = sv.mine(db, min_support=0.03, algorithm=alg, max_length=6) times[alg] = time.perf_counter() - t0 ref = results["prefixspan"] for alg, ps in results.items(): same = ps.patterns == ref.patterns and np.array_equal(ps.support, ref.support) print(f"{alg:10s} {len(ps):5d} patterns {times[alg]:6.3f} s identical={same}")
Constraints. A pattern such as occurs in 276 of the 300 days, in 191 if the two activities must be adjacent, in 151 if coffee must follow within half an hour, and in 268 if the whole occurrence must fit in two hours:
p = "wake up -> coffee" # arrows separate the elements; items may contain spaces for kw in [{}, {"max_gap": 1}, {"max_gap": 0.5, "gap_unit": "time"}, {"max_span": 2.0, "gap_unit": "time"}]: print(f"{str(kw):45s} support = {db.support(p, **kw)}")
The sequence index plot of fig. 2.8 (chapter 8) shows where the occurrences are.