Spectral Clustering a graph in python

share link

by vigneshchennai74 dot icon Updated: Feb 1, 2023

technology logo
technology logo

Solution Kit Solution Kit  

In this solution we are going to learn Spectral clustering .Spectral clustering is a more general technique which can be applied not only to graphs, but also images, or any sort of data, however, it's considered an exceptional graph clustering technique. Scikit Learn has two spectral clustering methods documented: SpectralClustering and spectral_clustering which seem like they're not aliases. Both of those methods mention that they could be used on graphs, but do not offer specific instructions. Neither does the user guide. I've asked for such an example from the developers, but they're overworked and haven't gotten to it. A good network to document this against is the Karate Club Network. It's included as a method in network.


Preview of the output that you will get on running this code from your IDE

Code

In this solution we have used SpectralClustering

import numpy as np
import networkx as nx
from sklearn.cluster import SpectralClustering
from sklearn import metrics
np.random.seed(1)

# Get your mentioned graph
G = nx.karate_club_graph()

# Get ground-truth: club-labels -> transform to 0/1 np-array
#     (possible overcomplicated networkx usage here)
gt_dict = nx.get_node_attributes(G, 'club')
gt = [gt_dict[i] for i in G.nodes()]
gt = np.array([0 if i == 'Mr. Hi' else 1 for i in gt])

# Get adjacency-matrix as numpy-array
adj_mat = nx.to_numpy_matrix(G)

print('ground truth')
print(gt)

# Cluster
sc = SpectralClustering(2, affinity='precomputed', n_init=100)
sc.fit(adj_mat)

# Compare ground-truth and clustering-results
print('spectral clustering')
print(sc.labels_)
print('just for better-visualization: invert clusters (permutation)')
print(np.abs(sc.labels_ - 1))

# Calculate some clustering metrics
print(metrics.adjusted_rand_score(gt, sc.labels_))
print(metrics.adjusted_mutual_info_score(gt, sc.labels_))

ground truth
[0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 1 0 0 1 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1]
spectral clustering
[1 1 0 1 1 1 1 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
just for better-visualization: invert clusters (permutation)
[0 0 1 0 0 0 0 1 1 1 0 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]
0.204094758281
0.271689477828

sc = SpectralClustering(2, affinity='precomputed', n_init=100, assign_labels='discretize')

ground truth
[0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 1 0 0 1 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1]
spectral clustering
[0 0 1 0 0 0 0 0 1 1 0 0 0 0 1 1 0 0 1 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1]
just for better-visualization: invert clusters (permutation)
[1 1 0 1 1 1 1 1 0 0 1 1 1 1 0 0 1 1 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0]
0.771725032425
0.722546051351
  1. Copy the code using the "Copy" button above, and paste it in a Python file in your IDE.
  2. Run the file to get the output


I hope you found this useful. I have added the link to dependent libraries, version information in the following sections.


I found this code snippet by searching for "Spectral Clustering a graph in python" in kandi. You can try any such use case!

Environment Test

I tested this solution in the following versions. Be mindful of changes when working with other versions.


  1. The solution is created in Python 3.7.15 version
  2. The solution is tested on scikit-learn 1.0.2 version


Using this solution, we are able going to learn how to Spectral Clustering a graph in python using Scikit learn library in Python with simple steps. This process also facilities an easy to use, hassle free method to create a hands-on working version of code which would help Spectral Clustering a graph in python in Python.

Dependent Library

scikit-learnby scikit-learn

Python doticonstar image 54584 doticonVersion:1.2.2doticon
License: Permissive (BSD-3-Clause)

scikit-learn: machine learning in Python

Support
    Quality
      Security
        License
          Reuse

            scikit-learnby scikit-learn

            Python doticon star image 54584 doticonVersion:1.2.2doticon License: Permissive (BSD-3-Clause)

            scikit-learn: machine learning in Python
            Support
              Quality
                Security
                  License
                    Reuse

                      If you do not have Scikit-learn that is required to run this code, you can install it by clicking on the above link and copying the pip Install command from the Scikit-learn page in kandi.

                      You can search for any dependent library on kandi like Scikit-learn.

                      Support

                      1. For any support on kandi solution kits, please use the chat
                      2. For further learning resources, visit the Open Weaver Community learning page.


                      See similar Kits and Libraries