Recreating a spectral analysis and cluster graph example from RPUBS using K-means algorithm

32 Views Asked by At

I need to do a cluster analysis for my own data. As a first step, I've been running code to produce the same results as this example: https://rpubs.com/gargeejagtap/SpectralClustering. (The first part of the article using K-means to produce a simple 8 node, 2 component graph based on a laplacian matrix which is what I'm doing)

I can get almost everything to work, but the clustering is coming out differently -- as indicated by the clustering in my plot which does not match the pattern of clusters in the example plot -- and I'm assuming it has something to do with the way my eigenvalues/eigenvectors or centers are being sorted. I can't seem to get it to work.

matrix <- read.table(text = "
  V1 V2 V3 V4 V5 V6 V7 V8
1  0  1  1  1  0  0  0  0
2  1  0  1  0  0  0  0  0
3  1  1  0  1  0  0  0  0
4  1  0  1  0  0  0  0  0
5  0  0  0  0  0  1  0  0
6  0  0  0  0  1  0  1  1
7  0  0  0  0  0  1  0  1
8  0  0  0  0  0  1  1  0
", header = TRUE)
M1 <- as.matrix(matrix)

MA <- M1 # adjacency matrix

library(igraph)

# Create an igraph graph object from the adjacency matrix
graph <- graph_from_adjacency_matrix(MA, mode = "undirected")

LM <- laplacian_matrix(graph, normalized = TRUE) # normalized laplacian from RPUBS instructions

# Spectral analysis
eigen_values <- eigen(LM)$values


# Create a graph plot
plot(graph,vertex.color=V(graph)$community, main="Cluster Graph")

########### K means algorithm

Evectors <- eigen(LM)$vectors

#Perform clustering with k-means
k <- 4            #We want 4 clusters
clustering <- kmeans(Evectors[, 2:k], centers = k)   #### number Evectors we want equal to the number of clusters

# Plot the graph with clustering results
plot(graph, vertex.color = clustering$cluster)
0

There are 0 best solutions below