Spectral

This notebook illustrates the spectral embedding of a graph through the spectral decomposition of the Laplacian matrix.

[1]:
from IPython.display import SVG
[2]:
import numpy as np
[3]:
from sknetwork.data import karate_club, painters, movie_actor
from sknetwork.embedding import Spectral, BiSpectral, cosine_modularity
from sknetwork.visualization import svg_graph, svg_digraph, svg_bigraph

Graphs

[4]:
graph = karate_club(metadata=True)
adjacency = graph.adjacency
labels = graph.labels

Embedding

[5]:
spectral = Spectral(2, normalized=False)
embedding = spectral.fit_transform(adjacency)
embedding.shape
[5]:
(34, 2)
[6]:
image = svg_graph(adjacency, embedding, labels=labels)
[7]:
SVG(image)
[7]:
../../_images/tutorials_embedding_spectral_10_0.svg

Predict

[8]:
# find the embedding of a new node
adjacency_vector = np.zeros(adjacency.shape[0], dtype = int)
adjacency_vector[:5] = np.ones(5, dtype = int)
[9]:
embedding_vector = spectral.predict(adjacency_vector)

Metrics

[10]:
cosine_modularity(adjacency, embedding)
[10]:
0.3802862736382374

Digraphs

[11]:
graph = painters(metadata=True)
adjacency = graph.adjacency
position = graph.position
names = graph.names

Embedding

[12]:
bispectral = BiSpectral(2, normalized=False)
embedding = bispectral.fit_transform(adjacency)
embedding.shape
[12]:
(14, 2)
[13]:
image = svg_digraph(adjacency, embedding, names=names)
[14]:
SVG(image)
[14]:
../../_images/tutorials_embedding_spectral_21_0.svg

Metrics

[15]:
cosine_modularity(adjacency, embedding)
[15]:
0.2068899883033235

Bigraphs

[16]:
graph = movie_actor(metadata=True)
biadjacency = graph.biadjacency
names_row = graph.names_row
names_col = graph.names_col

Embedding

[17]:
bispectral = BiSpectral(normalized=False)
bispectral.fit(biadjacency)
[17]:
BiSpectral(n_components=2, regularization=0.01, relative_regularization=True, scaling=0.5, normalized=False, solver='auto')
[18]:
embedding_row = bispectral.embedding_row_
embedding_row.shape
[18]:
(15, 2)
[19]:
embedding_col = bispectral.embedding_col_
embedding_col.shape
[19]:
(16, 2)
[20]:
image = svg_bigraph(biadjacency, names_row, names_col,
                    position_row=embedding_row, position_col=embedding_col,
                    color_row='blue', color_col='red')
[21]:
SVG(image)
[21]:
../../_images/tutorials_embedding_spectral_31_0.svg