【问题标题】:How to apply k-means clustering on Network Graphs in R iGraph?如何在 R iGraph 中的网络图上应用 k-means 聚类?
【发布时间】:2021-08-30 03:54:55
【问题描述】:

以下代码生成一个网络图,可以将数据分成两组,但我想在上面应用 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, 0, 1.0)
# Plot decorated graph, using same layout.
plot(karate, layout=l)

最终输出:

【问题讨论】:

    标签: r igraph k-means network-analysis


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2013-08-08
      • 2013-02-07
      • 2018-04-05
      • 2018-02-10
      • 2017-08-18
      • 2020-08-27
      • 2015-04-11
      • 2015-05-29
      • 2019-12-18
      相关资源
      最近更新 更多