Skip to content

Example: spectral clustering based graph - #4643

Closed
sharwinbobde wants to merge 15 commits into
networkx:mainfrom
SA-networkx:bugfix-for-issue-4261
Closed

sharwinbobde wants to merge 15 commits into
networkx:mainfrom
SA-networkx:bugfix-for-issue-4261

Conversation

@sharwinbobde

@sharwinbobde sharwinbobde commented Feb 27, 2021 •

Copy link
Copy Markdown
Contributor

[Updated]
This example is meant to address Issue #4261
More specifically, using scikit-learn to cluster data using Spectral Clustering. Then using the adjacency matrix from the same to generate a graph for the data points to understand the clustering.

image

Follow the below thread and the issue to view the iterations of the demo.

@sharwinbobde

Copy link
Copy Markdown
Contributor Author

@dschult we changed the colour schemes for plots of Step 1 and 2 to indicate that because clustering is an unsupervised method, the grouping does not necessarily indicate class membership.

@dschult

dschult commented Feb 27, 2021

Copy link
Copy Markdown
Member

This is much clearer--thank you.

But it still is not clear how you are assigning the edges in a network. It looks like you start with a dataset with three variables for each observation ==> two are continuous variables and the third is a binary classification. Then you use an AI method (which one?) to classify the observations into two groups. The clustering output shows these groups and they are close but not the same as the original groups. Is this correct?

Then you show the network -- but there is no explanation for what the nodes represent, how the edges are chosen, etc.

@sharwinbobde

Copy link
Copy Markdown
Contributor Author

I'll write a detailed flow here first thing in the morning :)

@sharwinbobde

sharwinbobde commented Feb 28, 2021 •

Copy link
Copy Markdown
Contributor Author

Demonstartion Explanation

Task overview

  • We do everything on a toy dataset
  • We know data comes from 3 distributions, just so that we can compare results.
  • The data is noisy (to show actual problems with clustering).
  • We will use Spectral Clustering to 1.) understand the data and 2.) cluster it
  • We will build a network using the affinity matrix which results in the following:
    • nodes are data points in the dataset
    • edges' weight is the value in the affinity matrix (show approximate association information about neighbouring node)
    • nodes have cluster membership information

Usage

  • This can be used to understand unlabelled data in a network form. For example, we can represent a 10-dimensional dataset using networks while preserving local information and making it obvious.
  • The resulting graph is a condensed form of the feature space information
  • We can indirectly use graph algorithms on feature space information
  • Edge weights do not have small noisy information from feature measurements, only the neighbourhood relation information.

Step 1: Generating sample dataset

  • Generate 3-class data sklearn.datasets.make_blobs docs
n_samples = 500
X, Y = make_blobs(n_samples=n_samples, centers=3, n_features=3, random_state=4242)

Step 2: Clustering

  • Lets conveniently select 3 as the number of clusters. (this is just an example/demonstration :) )

  • We will use nearest-neighbour based affinity matrix for SpectralClustering. This is what the method does under the hood:

    • Given only the feature space information, find 10 nearest neighbours for each data point using euclidean distance.
    • create the affinity matrix. Here is the code snippet from the scikit-learn source code.
    connectivity = kneighbors_graph(X, n_neighbors=self.n_neighbors,
                                           include_self=True,
                                           n_jobs=self.n_jobs)
    self.affinity_matrix_ = 0.5 * (connectivity + connectivity.T)
    
    • this is what a sample affinity sparse matrix looks like:
      Format: (<node>, <node>) <weight>
    (0, 76) 0.5
    (0, 70) 0.5
    (0, 61) 0.5
    (0, 36) 0.5
    (0, 66) 1.0
    (0, 92) 1.0
    (0, 15) 1.0
    ...
    (98, 83) 1.0
    (98, 99) 1.0
    (98, 98) 1.0
    (99, 25) 1.5
    (99, 20) 1.0
    (99, 48) 1.0
  • label the data points according to the cluster membership
  • plot the data with colours according to cluster membership.

Step 3: constructing the network

  • get the affinity matrix entries as weights for edges
  • get the cluster membership labels
  • remove self-loops
    clusters = sc.fit(X)
    cluster_affinity_matrix = clusters.affinity_matrix_

    pred_labels = clusters.labels_.astype(int)
    G = nx.from_scipy_sparse_matrix(cluster_affinity_matrix)
    # remove self edges
    G.remove_edges_from(nx.selfloop_edges(G))

    cluser_member = []
    for u in G.nodes:
        cluser_member.append(pred_labels[u])
  • plot the network with node colours according to cluster membership.

@sharwinbobde

Copy link
Copy Markdown
Contributor Author

Oops! posted the messages on the issue thread instead of this PR before.
Deleted the content on the Issue to keep things clean.

@dschult hope this is clearer :)
If there are any doubts we will keep updating the above explanation.
We do believe from our side that this is a strong direction for the Spectral Clustering example because it covers many possibilities of usage while still showing the limitations.

@dschult

dschult commented Mar 2, 2021

Copy link
Copy Markdown
Member

Much more complete information here... Thank you!

The original description had the sentence: "Then using the data from the spectral clustering to generate a graph for the data points." If I understand correctly, the "graph" is constructed using the affinity matrix by computing k-nearest-neighbors. But maybe here you mean "graph" (as in draw) a scatter plot of the feature space showing the clusters. In general, stay away from the word "graph" to mean a scatter plot when you've got graph theory in the mix. Graph Theory graphs can be called "networks", while graphs of datasets can be called scatter plots (or whatever other plot they are).

What is the right visualization of the network that will make this algorithm more clear? I think you have formed the network using distance in the feature space between data points. When you plot it you use a spring_layout for the nodes (which are the data points). Maybe it would be better to use the feature values as the coordinates of the nodes. Then you will show the essentially the scatter plot with edges between neighbors.

Another approach would be to plot the nodes using laplacian eigenvector values for two main eigenvalues. That gives a spectral layout which may (or may not depending on the meaning of "spectral clustering") show how the clustering is being determined.

Perhaps both pictures of the network would be helpful in getting the reader to understand 1) where the matrix/network is coming from, and 2) where the clustering is coming from once the network is formed.

What do you think? Or maybe you can explain why you chose to show the axes and positions you chose -- what is your pedagogical goal and how are you working to attain it?

@rossbar rossbar left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

representing items in a network and creating avenues to using graph algorithms on feature-space information.

This example could be made much more compelling by actually applying a graph algorithm on feature-space information. The one high-level comment I have is that it's not clear why networkx is even necessary, since the data generation and analysis (clustering) are both done w/ scikit-learn. It's nice to be able to explicitly see the edges after converting to a networkx graph, and the demonstration of the layout is also nice, but in its current form this seems more like a pure scikit-learn example than a scikit-learn + networkx example.

That's not to say it isn't valuable though! I'm not an expert so it's quite possible I'm missing interesting details - in that case adding some narrative text in the form of rst comments might help.

@sharwinbobde

sharwinbobde commented Mar 2, 2021 •

Copy link
Copy Markdown
Contributor Author

I see that some choices we made can be a bit confusing and deliver the wrong message. We will try to address these with a modified example.
image

Here you can clearly see that.

  • Step 1. Some data exists. we know there are 3 clusters.
  • Step 2. We do Spectral clustering (based on the nearest neighbours method) with the number of clusters as 3.
  • Step 3. We plot the graph obtained from the affinity matrix.

Modification considerations:

  • clustering is more apparent with consistent colour schemes.
  • it is more apparent that edges have neighbour information
  • what is a scatterplot and what is a simple network is clearer.
  • use case is comparatively more apparent.

This example can be used to observe cluster quality for high-dimensional data using a 2d network plot.
@rossbar I agree with you that there should be a Step 4. where we use some sort of graph technique.

Clarifications for comments:

  • @dschult This modification makes the distinction between scatterplots and network plots clearer.
  • @dschult @rossbar the affinity matrix will bot store real distance information at the clustering phase.
    • edges exist only if two nodes are neighbours
    • the edge weight is either 0.5 (if one node is neighbour of the other) or 1.0 (if both nodes are neighbours of each other)
    • Thus, the network representation has information that depends on feature-space distances but is NOT equal to the euclidean distance. The graph is a condensed form of information.
  • @rossbar In Step 3. We represent neighbours for different cluster members and thus draw the condensed high dimensional feature information using networkx, that is separated properly.
  • @rossbar for step 4. we might compute some heuristics to show clustering quality.

If the use case is still doubtful then this is the output if we select the number of clusters incorrectly (here 5).
image

So now you see we can exactly interpret what the affinity matrix is and why we need to plot the graph to show high-dimensional information.

@sharwinbobde

Copy link
Copy Markdown
Contributor Author

I'll update the above "Demonstration Explanation"

@sharwinbobde

Copy link
Copy Markdown
Contributor Author

image

One more Iteration!
In Step 4 we record the cut-size for different cluster-pair and plot the confusion matrix. The above figure shows that the cut size of clusters 2 and 1 is 0 so they are cleanly separated, whereas clusters 2 and 0 have a lot of similar neighbours. This cut-size is the heuristic Data Scientist can use to actually see how clean the clustering algorithm's output is and quantifiably measure the how good the clustering is.

Base automatically changed from master to main March 4, 2021 18:20
@rossbar

rossbar commented Mar 11, 2021

Copy link
Copy Markdown
Contributor

One thing to keep in mind is that the example should highlight something about graph/network analysis. There is a fine line to walk between making an example compelling and making it understandable. For me anyways, making the example more complex is heading in the wrong direction :). That's not to say that it isn't valuable - in fact, as the scope of the example here continues to increase, it may be a better fit for the networkx-notebooks repo, which is a more natural fit for larger examples and examples that would benefit from some narrative/explanatory text.

Also - there's no need to continue attaching images to the GH comments - all examples are run by the CI and can be previewed by clicking on the "ci/circleci: build artifact" tab in the CI check summary. This is actually better for review because it also guarantees that the image is being generated as expected (which is not currently the case).

@lobpcg

lobpcg commented Oct 16, 2023 •

Copy link
Copy Markdown
Contributor

The PR appears abandoned, and the code no longer runs on the current release. The code can be fixed using slightly edited lines 24-27:

    cluster_affinity_matrix = clusters.affinity_matrix_.H

    pred_labels = clusters.labels_.astype(int)
    G = nx.from_scipy_sparse_array(cluster_affinity_matrix)

def spectral_clustering_to_graph(X, n_clusters: int, sc: SpectralClustering):
# get affinity matrix from spectral clustering
clusters = sc.fit(X)
cluster_affinity_matrix = clusters.affinity_matrix_

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cluster_affinity_matrix = clusters.affinity_matrix_.H

cluster_affinity_matrix = clusters.affinity_matrix_

pred_labels = clusters.labels_.astype(int)
G = nx.from_scipy_sparse_matrix(cluster_affinity_matrix)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

G = nx.from_scipy_sparse_array(cluster_affinity_matrix)

@rossbar

rossbar commented Oct 16, 2023

Copy link
Copy Markdown
Contributor

Thanks for the ping @lobpcg - I still have the sense that this is a better fit for a scikit-learn gallery rather than networkx. Since it's been 18 months since last activity and is still in draft, I'm inclined to close. I'll do so soon if there are no objections!

@lobpcg

lobpcg commented Oct 16, 2023

Copy link
Copy Markdown
Contributor

@rossbar Yes, I agree that this PR could be closed as stalled. I like the idea, but the proposed implementation is still far from being acceptable unfortunately.

@lobpcg

lobpcg commented Nov 2, 2023

Copy link
Copy Markdown
Contributor

@rossbar I have made #7040 replacing this PR - could you please have a look?

@MridulS MridulS closed this Nov 11, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Development

Successfully merging this pull request may close these issues.

7 participants