如何解决如何在 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)
最终输出:
解决方法
您可以获得结果图的邻接矩阵,并在矩阵顶部应用 k-means 聚类。它相当于将 k-means 应用于图形。 以下是示例代码
{{1}}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。