# Louvain¶

This notebook illustrates the hierarchical clustering of graphs by the Louvain hierarchical algorithm.

[1]:

from IPython.display import SVG

[2]:

import numpy as np

[3]:

from sknetwork.data import karate_club, painters, movie_actor
from sknetwork.hierarchy import LouvainHierarchy, BiLouvainHierarchy
from sknetwork.hierarchy import cut_straight, dasgupta_score, tree_sampling_divergence
from sknetwork.visualization import svg_graph, svg_digraph, svg_bigraph, svg_dendrogram


## Graphs¶

[4]:

graph = karate_club(metadata=True)
position = graph.position


Hierarchy

[5]:

louvain_hierarchy = LouvainHierarchy()

[6]:

image = svg_dendrogram(dendrogram)

[7]:

SVG(image)

[7]:


Cuts of the dendrogram

[8]:

labels = cut_straight(dendrogram)
print(labels)

[0 0 0 0 3 3 3 0 1 0 3 0 0 0 1 1 3 0 1 0 1 0 1 2 2 2 1 2 2 1 1 2 1 1]

[9]:

labels, dendrogram_aggregate = cut_straight(dendrogram, n_clusters=4, return_dendrogram=True)
print(labels)

[0 0 0 0 3 3 3 0 1 0 3 0 0 0 1 1 3 0 1 0 1 0 1 2 2 2 1 2 2 1 1 2 1 1]

[10]:

_, counts = np.unique(labels, return_counts=True)

[11]:

image = svg_dendrogram(dendrogram_aggregate, names=counts, rotate_names=False)

[12]:

SVG(image)

[12]:

[13]:

image = svg_graph(adjacency, position, labels=labels)

[14]:

SVG(image)

[14]:


Metrics

[15]:

dasgupta_score(adjacency, dendrogram)

[15]:

0.5878582202111614

[16]:

tree_sampling_divergence(adjacency, dendrogram)

[16]:

0.44847800698542856


## Digraphs¶

[17]:

graph = painters(metadata=True)
position = graph.position
names = graph.names


Hierarchy

[18]:

louvain_hierarchy = LouvainHierarchy()

[19]:

image = svg_dendrogram(dendrogram, names, rotate=True)

[20]:

SVG(image)

[20]:


Cuts of the dendrogram

[21]:

# cut with 3 clusters
labels = cut_straight(dendrogram, n_clusters = 3)
print(labels)

[1 0 2 0 2 2 1 0 1 2 1 0 0 1]

[22]:

image = svg_digraph(adjacency, position, names=names, labels=labels)

[23]:

SVG(image)

[23]:


Metrics

[24]:

dasgupta_score(adjacency, dendrogram)

[24]:

0.4842857142857143

[25]:

tree_sampling_divergence(adjacency, dendrogram)

[25]:

0.42595079927794577


## Bigraphs¶

[26]:

graph = movie_actor(metadata=True)
names_row = graph.names_row
names_col = graph.names_col


Hierarchy

[27]:

bilouvain = BiLouvainHierarchy()
dendrogram_row = bilouvain.dendrogram_row_
dendrogram_col = bilouvain.dendrogram_col_
dendrogram_full = bilouvain.dendrogram_full_

[28]:

image = svg_dendrogram(dendrogram_row, names_row, n_clusters=4, rotate=True)

[29]:

SVG(image)

[29]:

[30]:

image = svg_dendrogram(dendrogram_col, names_col, n_clusters=4, rotate=True)

[31]:

SVG(image)

[31]:


Cuts of the dendrogram

[32]:

labels = cut_straight(dendrogram_full, n_clusters = 4)

[33]:

image = svg_bigraph(biadjacency, names_row, names_col, labels_row, labels_col)

[34]:

SVG(image)

[34]: