r - 具有约束的邻接矩阵聚类:节点权重总和的最大值和最小值
问题描述
我需要根据以下邻接矩阵找到集群:
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
允许我们设置集群数量的功能,但这并不能保证满足限制。
也许有更好的包来解决这类问题。嗯,我不知道。
解决此问题的任何帮助将不胜感激。
解决方案
推荐阅读
- python - tensor2tensor/avg_checkpoints 脚本是否错误
- postgresql - Flask-Migrate 脚本未对 Postgres 数据库应用更改
- javascript - 如何从javascript中的对象列表中找到字符串的某些部分与对象的字符串值的最完美匹配?
- python - 在 Python 中使用 pymunk 和 pygame 实现内置 GUI?
- java - 是否有任何方法/挂钩来强制 JVM 运行终结?
- lua - 字典帮助/数据存储
- c# - NUnit 获取结果未运行
- python - ColumnTransformer 两次创建估算器(并覆盖默认参数)
- mongodb - 在 Mongoose Schema 上推送子子文档
- python - 在 ndarray 中获取跨通道元素总和的优化方法