SAMM5
SAMM5

Reputation: 51

How to apply k-means clustering on Network Graphs in R iGraph?

The following code generates a Netwrok Graph and can separate the data into two groups, but I would like to apply k-means on it and see how the algorithm clusters the data into the same set of clusters.

library(igraphdata)  # library for the graph data 
data(karate)
V(karate) %>% print()  # shows the list of the nodes

# Reproducible layout
set.seed(69)
l <- layout_with_kk(karate)   #sets the layout.

# Plot undecorated Graph Network First.
igraph_options(vertex.size=10)
par(mfrow=c(1,1))                               # sets plotting parameters
plot(karate, layout=l, vertex.label=V(karate), 
     vertex.color=NA)                           # Plots a basic Graph

# Now decorate, starting with labels.
V(karate)$label <- sub("Actor ", "", V(karate)$name)
V(karate)
# Two Club Leaders get shapes different from other club members.
V(karate)$shape <- "circle"
V(karate)[c("Hi", "John")]$shape <- "rectangle"       # sets different shapes for these two only
# Differentiate two factions by color. (Similar to clustering & color-coded)
V(karate)[Faction == 1]$color <- "red"
V(karate)[Faction == 2]$color <- "dodgerblue"
# Vertex area proportional to vertex strength
# (i.e., total weight of incident edges).
V(karate)$size <- 4*sqrt(strength(karate))
V(karate)$size2 <- V(karate)$size * .5

# Weight edges by number of common activities
E(karate)$width <- E(karate)$weight
# Color edges by within/between faction.
F1 <- V(karate)[Faction==1]        # sets variable for first cluster (faction)
F2 <- V(karate)[Faction==2]        # similar to the above.
E(karate)[ F1 %--% F1 ]$color <- "pink"
E(karate)[ F2 %--% F2 ]$color <- "lightblue"
E(karate)[ F1 %--% F2 ]$color <- "green"
# Offset vertex labels for smaller points (size based, default is zero).
V(karate)$label.dist <- 
  ifelse(V(karate)$size >= 9.0, 0, 1.0)
# Plot decorated graph, using same layout.
plot(karate, layout=l)

Final Output:

enter image description here

Upvotes: 0

Views: 801

Answers (1)

Ram
Ram

Reputation: 131

you can get the adjacency matrix of the resultant graph and apply k-means clustering on top of the matrix. It is equivalent to applying k-means to the graph. Following is the sample code

adj.matrix = get.adjacency(graph, sparse=FALSE)
k <- 3 # no of desired clusters
km <- kmeans(matrix , centers = k, nstart = 25)

Upvotes: 1

Related Questions