Note
Go to the end to download the full example code or to run this example in your browser via Binder.
Association rules as a directed hypergraph#
Rules \(A\Rightarrow C\) are hyperarcs from the antecedent to the consequent set. Their confidence, lift and Zhang’s metric quantify the strength of the association; the weights of association-rule hypergraph partitioning (Han et al. 1997) turn the frequent itemsets into a weighted hypergraph whose clusters group mutually predictive themes.
import matplotlib.pyplot as plt
import hatvis as hv
T = hv.datasets.make_news_transactions(150, random_state=0)
fi = hv.frequent_itemsets(T, min_support=0.04)
# [snippet:rules]
rules = hv.association_rules(fi, min_confidence=0.6)
D = hv.patterns.rule_hypergraph(rules.head(30))
w = hv.patterns.arhp_weights(fi)
W = hv.itemset_hypergraph(fi, min_size=2).with_weights(w.reindex(fi[fi["size"] >= 2]["itemset"]).to_numpy())
clusters = hv.hypergraph_louvain(W, random_state=0)
# [/snippet:rules]
print(rules.head(8)[["antecedent", "consequent", "support", "confidence", "lift", "zhang"]].to_string())
print(D)
for c, m in enumerate(hv.community.communities(clusters)):
print(f"cluster {c}: {m}")
antecedent consequent support confidence lift zhang
0 (AID, FINANCE, LOSS_DAMAGE) (DEVELOPING) 0.082222 0.925000 5.336538 0.891892
1 (WILDFIRE, HEATWAVE) (DROUGHT) 0.104444 0.903846 4.420987 0.874906
2 (AID, DEVELOPING, LOSS_DAMAGE) (FINANCE) 0.082222 0.902439 5.206379 0.888918
3 (FLOOD, WILDFIRE, HEATWAVE) (DROUGHT) 0.082222 0.902439 4.414104 0.850988
4 (FINANCE, AID, DEVELOPING) (LOSS_DAMAGE) 0.082222 0.880952 5.082418 0.885930
5 (NEGOTIATION, AGREEMENT, PLEDGE) (SUMMIT) 0.080000 0.878049 4.248623 0.841280
6 (AID, DEVELOPING) (FINANCE) 0.093333 0.875000 5.048077 0.897655
7 (ENERGY, OIL_GAS, RENEWABLES) (COAL) 0.073333 0.868421 3.947368 0.815534
DirectedHypergraph(name=None, n_nodes=24, n_edges=30)
cluster 0: ['EMISSIONS', 'TEMPERATURE', 'CLIMATE', 'IPCC']
cluster 1: ['COAL', 'OIL_GAS', 'RENEWABLES', 'ENERGY']
cluster 2: ['DROUGHT', 'FLOOD', 'WILDFIRE', 'HEATWAVE']
cluster 3: ['AGREEMENT', 'SUMMIT', 'PLEDGE', 'NEGOTIATION']
cluster 4: ['DEVELOPING', 'LOSS_DAMAGE', 'FINANCE', 'AID']
cluster 5: ['HEALTH', 'MIGRATION', 'PROTEST', 'YOUTH']
fig, ax = plt.subplots(figsize=(6.5, 4.5))
sc = ax.scatter(rules["support"], rules["confidence"], c=rules["lift"], cmap="viridis", s=18)
plt.colorbar(sc, ax=ax, label="lift")
ax.set_xlabel("support")
ax.set_ylabel("confidence")
plt.tight_layout()

Total running time of the script: (0 minutes 0.190 seconds)