如何解决具有约束的邻接矩阵聚类:节点权重总和的最大值和最小值
我需要根据以下邻接矩阵找到集群:
library(dplyr)
# importing the adjacency matrix
adj_matrix <- read.table('https://raw.githubusercontent.com/sergiocostafh/adjmatrix_example/main/adj_m.txt',header = T,check.names = F) %>% as.matrix()
row.names(adj_matrix) <- colnames(adj_matrix)
使用 igraph
包,我将矩阵转换为图形以执行聚类。 ggraph
包有助于可视化。
library(ggplot2)
library(igraph)
# turning into a graph
grafo <- graph_from_adjacency_matrix(adj_matrix,'undirected')
# detecting clusters
fc <- cluster_walktrap(as.undirected(grafo))
# results to data.frame
ms <- data.frame(id=membership(fc)%>%names(),cluster=as.character(as.vector(membership(fc))))
# plot
ggraph(grafo)+
geom_edge_link0(edge_colour = "grey66")+
geom_node_point(aes(fill = ms$cluster),size=5,shape=21)
上述过程没有考虑节点权重,但我需要考虑并设置一些约束。 可以按如下方式导入权重向量:
# weights
w <- read.table('https://raw.githubusercontent.com/sergiocostafh/adjmatrix_example/main/weights.txt') %>% as.vector()
# adding the weights column to the dataset
ms$weight <- w
# calculating the total weight of each cluster
ms %>% group_by(cluster) %>% summarise(weight = sum(weight)) %>% arrange(-weight)
# A tibble: 12 x 2
cluster weight
<chr> <dbl>
1 2 429.
2 1 351.
3 6 330.
4 3 325.
5 5 194.
6 7 120.
7 4 80.9
8 11 68.9
9 10 57.4
10 8 53.6
11 9 42.0
12 12 32.9
通过计算每个集群的总权重,我们得到 429 作为最高值(集群 2)和 32.9 作为最低值(集群 12),但我需要考虑以下约束:
- 最大集群总重量:400
- 最小集群总权重:50
我知道使用 cutat
函数可以让我们设置集群的数量,但这并不能保证满足限制。
也许有更好的包来解决这类问题。嗯,我不知道。
对解决此问题的任何帮助将不胜感激。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。