【问题标题】:How to calculate size and location of multi clusters in matrix (R)如何计算矩阵(R)中多簇的大小和位置
【发布时间】:2021-07-21 00:08:24
【问题描述】:

我有一个矩阵,我想知道由相同数值表示的每个簇的中心和最小/最大大小。

例如,获取由以下矩阵中的数字 2 表示的簇的中心位置和大小(或最小/最大列/行)。这个想法仅限于在图像上执行 How to obtain size of cluster of pixels in RHow to obtain size of multi clusters in matrix (R)

但是当我使用函数apply(matrix2, 2, mean)apply(matrix2, 2, range) 时,结果会合并两个集群。有没有办法获取每个集群?

> matrix<- read.csv("2_ind_matrix.csv")
   X1 X1.1 X1.2 X1.3 X1.4 X1.5
1   1    1    1    1    1    1
2   1    1    1    1    1    1
3   1    1    1    1    1    1
4   1    1    1    2    2    2
5   1    1    1    1    2    2
6   1    1    1    1    1    1
7   1    1    1    1    1    1
8   1    1    1    1    1    1
9   1    1    1    1    1    1
10  1    1    1    1    1    1
11  2    1    1    1    1    1
12  2    1    1    1    1    1
13  2    1    1    1    1    1
14  2    2    1    1    1    1
15  2    2    2    1    1    1
16  2    2    2    2    2    2
17  2    2    2    2    2    2

> matrix2<- which(matrix == 2, TRUE)
> apply(matrix2, 2, range) #Range
     row col
[1,]   4   1
[2,]  17   6
> apply(matrix2, 2, mean) #Center
  row   col 
13.16  3.20 

【问题讨论】:

  • 你的问题不清楚。你到底想要什么?位置的平均值还是平均值?您刚刚使用了 which 功能。这样不行吗?

标签: r matrix


【解决方案1】:

需要决定有多少集群。在这里,我假设有 2 个集群。这些可以通过kmeans 使用从which 返回的位置找到。

y <- which(x==2, TRUE)
y <- cbind(y, cluster=kmeans(y, 2)$cluster)

aggregate(y[,1:2], list(y[,3]), range)
#  Group.1 row.1 row.2 col.1 col.2
#1       1     4     5     4     6
#2       2    11    17     1     6

aggregate(y[,1:2], list(y[,3]), mean)
#  Group.1   row col
#1       1  4.40 5.2
#2       2 15.35 2.7

【讨论】:

  • 谢谢。但是当有很多集群时,我在使用 kmeans 时遇到了问题。簇未被很好地检测到。彼此相距较远的像素被认为是同一个簇的一部分。例如,位于 (1,1) 的集群与集群 (7,6) 重新组合。
  • 也许你可以在kmeans 中尝试不同的algorithm 或使用其他聚类方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多