# KCenters

This notebook illustrates graph clustering with the KCenters algorithm.

[1]:

from IPython.display import SVG

[2]:

import numpy as np

[3]:

from sknetwork.data import karate_club, painters, movie_actor
from sknetwork.clustering import get_modularity
from sknetwork.clustering import KCenters
from sknetwork.visualization import svg_graph, svg_bigraph


## Graphs

[4]:

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

[5]:

kcenters = KCenters(n_clusters=2)

[6]:

# cluster centers
kcenters.centers_

[6]:

array([ 5, 26])

[7]:

labels_unique, counts = np.unique(labels, return_counts=True)
print(labels_unique, counts)

[0 1] [15 19]

[8]:

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

[8]:

[9]:

# metric

[9]:

0.3599605522682445


## Directed graphs

[10]:

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

[11]:

# clustering
kcenters = KCenters(n_clusters=3, directed=True)

[12]:

labels_unique, counts = np.unique(labels, return_counts=True)
print(labels_unique, counts)

[0 1 2] [4 6 4]

[13]:

# cluster centers
names[kcenters.centers_]

[13]:

array(['Egon Schiele', 'Claude Monet', 'Rembrandt'], dtype='<U21')

[14]:

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

[14]:

[15]:

get_modularity(adjacency, labels)

[15]:

0.2900000000000001


## Bipartite graphs

[16]:

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

[17]:

# clustering
kcenters = KCenters(n_clusters=3, center_position="both")
labels_row = kcenters.labels_row_
labels_col = kcenters.labels_col_

[18]:

# cluster centers
centers_row = kcenters.centers_row_
centers_col = kcenters.centers_col_

print("centers row:", names_row[centers_row])
print("centers col:", names_col[centers_col])

centers row: ['La La Land' 'Fantastic Beasts 2']
centers col: ['Owen Wilson']

[19]:

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

[19]:

[20]:

# metric

[20]:

0.4623015873015873