Mining and Visualizing Frequent Sequences in PythonThe spmviz toolbox

Chapter 4
Network-based visualization of frequent sequences

This chapter develops the three network-based views of frequent sequences proposed by Bántay and Abonyi [1]: the weighted extension network (NBVFS-WN), which shows how frequent sequences grow out of each other; the confidence-based map (NBVFS-CM), which places the sequences of the same scenario close together; and the transaction-based map (NBVFS-TM), which groups the sequences that occur in the same cases. It then answers two questions left open by the paper, how to combine the similarities and how to segment the pattern set, with a fused map and with communities that cut the log into sub-logs. The chapter closes with the reproduction of the paper on its two logs.

4.1 Problem and idea

The operators of a chemical plant face alarm floods: dozens of alarms in minutes, some caused by others, interleaved with their own actions. Frequent sequences of alarms and actions can support them, by suppressing alarms that predictably follow others [2], by predicting the next alarm [3], or by redesigning the operator interface [4]. But the mined sequences have to be understood first, and a list of several hundred overlapping sequences is no help in that. Bántay and Abonyi observed that the frequent sequences are related to each other in two ways that can be drawn as networks. They form a tree under extension, whose edges carry the confidence of the extension (section 2.2.2). And they are supported by overlapping sets of traces, so their co-occurrence defines a similarity. The first relation gives a weighted network and, through a transitive closure, a similarity; the second gives a similarity directly. Multidimensional scaling turns each similarity into a map [1].

4.2 Theory

4.2.1 The weighted extension network (WN)

Let F = {φ1,…,φP } be a prefix-closed set of frequent sequences, for instance one mined with a gap constraint. The weighted extension network has a node for every φi and an edge φi →φj whenever φi = π(φj), weighted by the confidence c(φj) = σ(φj)∕σ(φi). The network is a forest; each tree is rooted at a frequent single event, the start event of its sequences. In the drawing of the paper the color of a node encodes the length of the sequence, its size the cumulative confidence c∗(φj), the share of the sequences of the start event that reach it, and the width of an edge the confidence [1]. Two layouts suit a forest: a radial layout that puts one start event in the centre and the longer sequences on concentric rings, and a hierarchical layout with one row per length. A tree can be pruned at a minimum confidence, which removes the weak continuations and everything below them.

The WN answers questions of the form how does a process continue after this sequence, and how decisively? A node with one thick outgoing edge is followed by a predictable step; a node with many thin edges is a branching point. Its limitation is that sequences of different trees, or far apart in the same tree, are not related in the picture at all.

4.2.2 The confidence-based map (CM)

The CM view extends the confidences of the extension tree to all pairs of sequences. Let 𝐀 ∈[0,1]P×P be the confidence matrix, aij = c(φj) if φi = π(φj) and aij = 0 otherwise, and let 𝐒(0) = max(𝐀,𝐀𝖳) be its symmetrization. Two sequences of the same tree are connected by a unique path, and the paper defines their similarity as the product of the confidences along it; sequences of different trees are not similar at all. The definition is the max-product transitive closure of 𝐒(0),

aij∗ = max paths i=k0,k1,…,kr=j ∏ q=1rs kq−1kq(0),a ii∗ = 1, (4.1)

which in a forest reduces to the product along the unique path. Because all weights lie in [0,1], a product can only shrink along a path, and one pass of the Floyd–Warshall recursion aij∗ ←max(aij∗,aik∗akj∗) over all intermediate nodes k in the (max,×) semiring computes the closure exactly. The dissimilarity 𝐃 = 1 −𝐀∗ is then embedded in the plane by metric multidimensional scaling (MDS) [20]: coordinates 𝐲i ∈ℝ2 are sought that minimize the stress

σ1(𝐘) = ∑ i<j( ‖𝐲i −𝐲j‖ −dij)2 ∑ i<jdij2 , (4.2)

the normalized stress-1 of Kruskal [77]. spmviz minimizes it by majorization (SMACOF), started from the deterministic classical (Torgerson) solution, and reports σ1 with every map; values around 0.1 are good, values above 0.3 warn that the plane cannot hold the dissimilarities faithfully [20].

In the CM map the sequences of one tree form a cloud around their start event; a long, confident chain of extensions becomes a ridge reaching away from it, and trees with similar structure lie side by side. The view answers which frequent sequences belong to the same scenario?

4.2.3 The transaction-based map (TM)

The TM view ignores the extension tree and compares the supports. Let 𝐓 ∈{0,1}P×N be the pattern–sequence incidence matrix, tik = 1 if sequence k supports φi. The similarity of two patterns is the Jaccard index of their supporting sets,

sij = |Ti ∩Tj| |Ti ∪Tj| = (𝐓𝐓𝖳)ij σ(φi) + σ(φj) −(𝐓𝐓𝖳)ij, (4.3)

where Ti is the set of sequences supporting φi; 𝐃 = 1 −𝐒 is embedded by MDS as before [1]. Patterns that occur in the same traces — the events of a sub-process that runs interleaved with others — form clusters, whatever their start events. The view answers which frequent sequences occur together?, the question behind the segmentation of a log into sub-processes. The Dice, overlap and cosine coefficients are available as alternatives to the Jaccard index.

Algorithm\special {t4ht^+}

4.2.4 Fused similarities

The paper closes by asking how the similarities could be combined [1]. The CM and TM similarities see different things, and a third one is natural: the similarity of the patterns as strings, the length of their longest common subsequence divided by the longer length (content_similarity). spmviz combines them in two ways. A weighted mean is transparent but sensitive to the different scales of the similarities. Similarity network fusion (SNF), developed for combining patient similarities from several genomic data types [74], avoids the scale problem: each similarity is turned into a row-normalized matrix 𝐏(v) and a sparse local kernel 𝐊(v) that keeps the k nearest neighbours of every pattern, and the matrices are diffused through each other,

𝐏(v) ←𝐊(v)( 1 V −1∑ u≠v𝐏(u))𝐊(v)𝖳,v = 1,…,V, (4.4)

for a fixed number of iterations; the fused similarity is the average of the 𝐏(v), rescaled to [0,1]. Strong local agreements between the similarities are reinforced, weak disagreements fade. NBVFS("fused") uses SNF of the confidence, transaction and content similarities by default and a weighted mean when weights are given.

4.2.5 Communities and sub-logs

The second open question of the paper is how to segment the network [1]. A map invites the eye to find clusters, and an algorithm can find them as well: pattern_communities builds the k-nearest-neighbour graph of a similarity matrix and partitions it by Louvain modularity maximization [75]. With the transaction similarity, a community gathers patterns supported by the same traces, a candidate sub-process. The traces that support the patterns of a community form a sub-log, which can be mined, drawn as a process map or compared with the other sub-logs; sublogs returns one SequenceDatabase per community. The resolution parameter of the modularity sets the granularity.

In a nutshell: Network-based visualization of frequent sequences

  • WN: the extension forest of the frequent sequences, edges weighted by confidence, nodes sized by cumulative confidence — how sequences grow and where they branch.
  • CM: max-product closure of the confidences, embedded by MDS — which sequences belong to the same scenario.
  • TM: Jaccard similarity of the supporting traces, embedded by MDS — which sequences occur together.
  • Fused map: similarity network fusion of the confidence, transaction and content similarities.
  • Communities: Louvain communities of a similarity graph segment the pattern set and the log into sub-processes.
  • Every map comes with its stress; every network is a NetworkX graph with all attributes.

4.3 Using it in spmviz

The NBVFS class follows the estimator convention of scikit-learn: the constructor takes the options, fit(ps) computes the network and the coordinates, and the fitted object exposes graph_ (a NetworkX DiGraph with coordinates x, y and all pattern attributes on the nodes), positions_, similarity_, stress_ and patterns_. plot() draws the view, to_frame() returns the node table and write(path) writes the graph to GEXF, GraphML, Cytoscape JSON or node-link JSON with positions and colors, ready for Gephi [78] or Cytoscape [79]. The options are the view ("wn", "cm", "tm", "fused"), start_items (the filter of the paper), min_confidence, layout of the WN, mds ("smacof", "classical", "sklearn", or neighbourhood embeddings for very large sets), weight ("confidence" as defined in the paper, or "cumulative", the edge value of the reference scripts [5]) and similarity_weights of the fused map. The building blocks are public: extension_network, confidence_matrix, transitive_confidence, transaction_similarity, content_similarity, fuse_similarities, snf, mds, pattern_communities and sublogs.

db = sv.datasets.load_clickstream() 
ps = sv.mine(db, min_support=0.01, algorithm="cmspam", max_gap=1, max_length=10) 
print(ps, "lengths", ps.lengths.min(), "-", ps.lengths.max()) 
print({k: db.label(k) for k in range(4)})
   
A = confidence_matrix(ps)              # a_ij = c(phi_j) if phi_i is the parent of phi_j 
S = transitive_confidence(A)           # max-product closure of max(A, A^T) 
print("non-zero similarities:", (A > 0).sum(), "->", (S > 0).sum() - len(ps))
   

4.4 Reproducing the paper

The paper analyses two logs, both bundled with the package. The click-stream contains 343 sessions over 14 services of the unemployment-benefit application of the Dutch Employee Insurance Agency, part of the BPI Challenge 2016 data [29]; the services are coded 0–13 in order of first appearance, as in the paper. The alarm log of a hydrofluoric-acid alkylation plant contains 28,536 alarms (codes 100–499, printed A…) and operator actions (codes above 1000, printed O…) in 3,956 traces recorded between September and December 2020. As in the paper, CM-SPAM mines the click-stream with 1% minimum support, maximum gap 1 and maximum length 10, and the alarm log with 1% minimum support and maximum gap 2.

spmviz finds 241 frequent sequences of length 1–8 in the click-stream and 421 of length 1–6 in the alarm log; the paper reports 242 and 420 with the same length ranges [1]. The five algorithms of the package agree with each other and with brute-force counting on both logs, so the differences of one pattern must come from the preparation of the data. The reference scripts convert the logs to the SPMF format with a Java converter and concatenate the item codes into strings before computing the parents [5]; the click-stream records some clicks with minute resolution only, so the order of simultaneous clicks depends on how the file is read. The bundled click-stream keeps the order of the original file. Such details shift the support of a sequence at the threshold by one and are immaterial for the maps, but they illustrate a general point: a reproducible analysis needs the exact data preparation as much as the mining parameters.

4.5 Examples

The weighted network of the click-stream. The paper filters the network by the starting service; fig. 4.1 shows the sessions that start with service 2, Hours worked, in the radial layout. The hierarchical layout of fig. 4.2 draws the trees of four start events side by side, and fig. 4.3 prunes the weak extensions: at a minimum confidence of 0.4 only the decisive continuations remain.

wn = sv.NBVFS("wn", layout="circle", start_items=[2]).fit(ps) 
wn.plot(labels=20, title="NBVFS-WN, sequences starting with ’Hours worked’")
                                                                     

                                                                     
   

Figure 4.1

Figure 4.1. NBVFS-WN of the click-stream sessions starting with Hours worked: radial layout, node color = length, node size = cumulative confidence, edge width = confidence.

Open in ColabExample plot_01_weighted_network.py in the gallery

Figure 4.2

Figure 4.2. The extension trees of the first four services in the hierarchical layout, one row per length.

Figure 4.3

Figure 4.3. Pruning weak extensions of the Hours worked tree at minimum confidences 0, 0.2 and 0.4.

The confidence map. The closure turns the 227 non-zero confidences of the 241 click-stream sequences into 7,372 non-zero similarities. Figure 4.4 highlights three start events; the normalized stress of 0.41 is high, as expected when 241 points are forced into a plane while sequences of different trees are all at distance one. Figure 4.5 compares classical scaling with SMACOF.

cm = sv.NBVFS("cm").fit(ps) 
print("normalized stress:", round(cm.stress_, 3)) 
cm.plot(start_items=[2, 3, 4], labels=16)
   

Figure 4.4

Figure 4.4. NBVFS-CM of the click-stream with three start events highlighted; edges join every sequence to its parent, node size is the support.

Open in ColabExample plot_02_confidence_mds.py in the gallery

Figure 4.5

Figure 4.5. The CM map by classical scaling (left) and by SMACOF (right) with their stress values.

The transaction map finds sub-processes. The synthetic alarm floods of make_alarm_cascades interleave cascades of four sub-processes — pump, cooling, compressor and separator — with nuisance alarms; some floods contain two cascades. The TM map of the frequent sequences (fig. 4.6) separates the four cascades without knowing them; fig. 4.7 highlights the cooling cascade, and fig. 4.8 shows how lower thresholds fill the space between the clusters with mixed combinations.

db = sv.datasets.make_alarm_cascades(600, random_state=0) 
print(db.attributes["scenario"].value_counts().head()) 
ps = sv.mine(db, min_support=0.05, max_length=5) 
tm = sv.NBVFS("tm").fit(ps) 
tm.plot(labels=14)
   

Figure 4.6

Figure 4.6. NBVFS-TM of synthetic alarm floods: the frequent sequences of the four interleaved sub-processes form four clusters.

Open in ColabExample plot_03_transaction_mds.py in the gallery

Figure 4.7

Figure 4.7. The same map with the sequences of the cooling sub-process highlighted.

Figure 4.8

Figure 4.8. TM maps at minimum supports of 0.03, 0.06 and 0.12: rare combinations of cascades and nuisance alarms fill the space between the cores.

The industrial alarm log. The most frequent events of the alkylation plant are operator actions (O1084, O1085, O1080, O1081) followed by the alarms A309 and A330. Figure 4.9 draws the extension tree of the most frequent start event; fig. 4.10 puts the CM and TM maps side by side. The repetitive sequences of operator actions, such as ⟨𝖮1084𝖮1085𝖮1084𝖮1085⋯⟩, are long and confident chains, and the CM map stretches them along one dominant direction. The TM map shows no sharp clusters: the frequent operator actions occur in traces of many kinds, so the sequences of the three most frequent start events spread over the whole map.

db = sv.datasets.load_alarm_log() 
ps = sv.mine(db, min_support=0.01, algorithm="cmspam", max_gap=2, max_length=10) 
print(ps, "lengths", ps.lengths.min(), "-", ps.lengths.max()) 
top = ps.filter(min_length=1, max_length=1).sort("support") 
print("most frequent events:", top.labels()[:8])
   

Figure 4.9

Figure 4.9. NBVFS-WN of the industrial alarm log: the extension tree of the most frequent start event, O1084.

Open in ColabExample plot_04_alarm_log.py in the gallery

Figure 4.10

Figure 4.10. NBVFS-CM (left) and NBVFS-TM (right) of the 421 frequent sequences of the alarm log, the three most frequent start events highlighted.

Beyond the paper. The fused map of the synthetic alarm floods (fig. 4.11) combines the three similarities. Louvain communities of the transaction similarity graph find five groups with modularity 0.78 (fig. 4.12): four of them coincide with the four sub-processes, the fifth gathers the floods in which the pump and the compressor cascades occur together. Each community defines a sub-log of 42 to 209 traces; fig. 4.13 draws one of them as a process map.

fused = sv.NBVFS("fused").fit(ps) 
fused.plot(labels=14)
   
labels, modularity, G = pattern_communities(ps, similarity="transaction", knn=8) 
print(f"{labels.max() + 1} communities, modularity {modularity:.2f}") 
parts = sublogs(ps, labels) 
for c, sub in parts.items(): 
    print(c, len(sub), "traces", sub.attributes["scenario"].value_counts().index[0])
   

Figure 4.11

Figure 4.11. The fused map: similarity network fusion of the confidence, transaction and content similarities of the synthetic alarm floods.

Open in ColabExample plot_05_fused_similarity.py in the gallery

Figure 4.12

Figure 4.12. Louvain communities of the transaction similarity graph: candidate sub-processes.

Figure 4.13

Figure 4.13. The sub-log of the first community, the floods in which the pump and the compressor cascades occur together, drawn as a directly-follows graph (chapter 6).