【问题标题】:Cluster groups of 1s in a binary matrix二元矩阵中 1 的聚类组
【发布时间】:2019-11-07 22:23:43
【问题描述】:

我希望围绕所有 1s 和 0s 创建集群。与 Mindsweeper 类似,我想基本上在所有 1s 周围“画一个圆圈”,并在 0s 存在的地方创建一个边框。

我曾尝试使用hclust() 并创建一个距离矩阵,但我正在使用的实际表非常大,而且我遇到了运行时问题。

test_matrix  <- matrix(c( 1,1,0,0,0,0,1,     
                          1,1,1,0,0,1,0,
                          0,1,0,0,0,1,0,
                          0,0,0,1,1,1,0,
                          0,0,0,1,1,1,1),nrow=5)

结果如下所示:

     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    1    0    0    1    0    1    0
[2,]    1    1    0    0    0    1    1
[3,]    0    1    1    0    0    0    1
[4,]    0    1    0    0    0    0    1
[5,]    0    1    0    1    1    0    1

我的规则如下:如果任何1 通过上、下、左、右、对角(任何方向)连接到任何1,则继续增长“集群”。根据这些规则(每个点有 8 个连接点),我可以发现四个具有隔离 1s 的独特集群。

您将如何编写代码来查找这些组?

【问题讨论】:

  • 请说明您想要的结果。 IE。 “结果看起来像这样”和“test_matrix”之间的联系是什么?无论如何,根据您 final 部分中的描述,听起来您正在寻找library(raster)clump(raster(m))。如果是,相关:Extract sub-matrices from binary matrix in R
  • 能否指出以下答案是否解决了您的问题?
  • 能否回复评论,要求澄清并提供潜在的解决方案?

标签: r matrix binary


【解决方案1】:

我认为集群在这里是正确的方法,但是您为该任务选择了一种较差的(计算量大的)方法。我会像这样去 DBSCAN:

library(dbscan)

## slightly altered test matrix to include a "cluster" with a single 1
test_matrix  <- matrix(c( 1,1,0,0,0,0,1,     
                          1,1,1,0,0,1,0,
                          0,1,0,0,0,1,0,
                          0,0,0,1,1,1,0,
                          1,0,0,1,1,1,1),
                          nrow=5, byrow = TRUE)

## find rows and columns of 1s
ones_pos <- which(test_matrix > 0,arr.ind=TRUE)


## perform DBSCAN clustering
## setting eps = sqrt(2) + .1 corresponds to your neighbourhood definition
## setting minPts = 2 will mark clusters of one point as noise
clust <- dbscan(ones_pos, eps = sqrt(2), minPts = 2)

## find the indices of noise elements
singular_ones <- ones_pos[clust$cluster == 0, ]

singular_ones
#> row col 
#>  5   1 

要查找所有簇(包括仅包含一个 1 的簇),只需将 minPts 设置为 1。在这种情况下,不会有噪音。集群成员存储在clust$cluster

我很确定这种方法在处理大型矩阵时也会相当快。

【讨论】:

  • 进行了编辑,删除了 dplyr 的使用,这在这种情况下是不必要的。
  • 这很有意义!谢谢!如果我想查找所有集群,这是否有效,有些集群只有一个点?其他有很多?都在同一个测试中?
  • 这会找到所有集群。每个超过minPts 1s 的集群都被分配了一个 >=1 的数字。在clust$cluster 中,所有其他 1 都被分配为 0
猜你喜欢
  • 2016-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-12
  • 2021-07-10
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
相关资源
最近更新 更多