如何在 R iGraph 中的网络图上应用 k 均值聚类?

问题描述

下面的代码生成一个 Netwrok Graph 并且可以将数据分成两组,但我想对其应用 k-means,看看算法如何将数据聚类到同一组聚类中。

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,1.0)
# Plot decorated graph,using same layout.
plot(karate,layout=l)

最终输出

enter image description here

解决方法

您可以获得结果图的邻接矩阵,并在矩阵顶部应用 k-means 聚类。它相当于将 k-means 应用于图形。 以下是示例代码

{{1}}