Frequent itemsets as a hypergraph#

Frequent theme combinations of the news articles form a weighted hypergraph: every frequent itemset is a hyperedge, its support the weight. Eclat and Apriori give identical results; closed and maximal itemsets compress the pattern set, and the inclusion lattice (Hasse diagram) of the closed itemsets shows how the combinations nest.

import matplotlib.pyplot as plt

import hatvis as hv
from hatvis.plotting import draw_hypergraph, plot_lattice

T = hv.datasets.make_news_transactions(150, random_state=0)
# [snippet:mine]
fi = hv.frequent_itemsets(T, min_support=0.05)
same = fi.equals(hv.frequent_itemsets(T, min_support=0.05, algorithm="apriori"))
closed = hv.closed_itemsets(fi)
maximal = hv.maximal_itemsets(fi)
IH = hv.itemset_hypergraph(closed[closed["support"] >= 0.08], min_size=2)
# [/snippet:mine]
print(f"{len(fi)} frequent, {len(closed)} closed, {len(maximal)} maximal itemsets; eclat == apriori: {same}")
print(maximal.head(6).to_string())
88 frequent, 88 closed, 8 maximal itemsets; eclat == apriori: True
                                    itemset  size  count   support
0   (TEMPERATURE, CLIMATE, EMISSIONS, IPCC)     4   43.0  0.095556
1   (DEVELOPING, AID, FINANCE, LOSS_DAMAGE)     4   37.0  0.082222
2      (FLOOD, WILDFIRE, DROUGHT, HEATWAVE)     4   37.0  0.082222
3  (SUMMIT, NEGOTIATION, AGREEMENT, PLEDGE)     4   36.0  0.080000
4       (COAL, ENERGY, OIL_GAS, RENEWABLES)     4   33.0  0.073333
5               (YOUTH, MIGRATION, PROTEST)     3   25.0  0.055556
fig, ax = plt.subplots(figsize=(9, 7))
draw_hypergraph(IH.remove_isolated(), layout="force", style="smooth", width_by="weight", ax=ax, legend=False,
                pad=0.02, random_state=0, title="closed itemsets with support of at least 8%")
plt.tight_layout()
closed itemsets with support of at least 8%
climate = {"CLIMATE", "EMISSIONS", "IPCC", "TEMPERATURE"}
sub = fi[fi["itemset"].map(lambda x: x <= climate)]
G = hv.patterns.inclusion_lattice(sub["itemset"], weights=sub["support"])
plot_lattice(G, title="inclusion lattice of the frequent itemsets of the climate narrative")
plt.gcf().set_size_inches(10, 4.8)
plt.tight_layout()
inclusion lattice of the frequent itemsets of the climate narrative

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

Gallery generated by Sphinx-Gallery