【问题标题】:Permute columns of a square 2-way contingency table (matrix) to maximize its diagonal置换方形 2 路列联表(矩阵)的列以最大化其对角线
【发布时间】:2019-03-03 12:04:24
【问题描述】:

做聚类后,找到的标签是没有意义的。可以计算一个列联表,看看哪些标签与原始类别最相关,如果有可用的基本事实。

我想自动排列列联表的列以最大化其对角线。例如:

# Ground-truth labels
c1 = c(1,1,1,1,1,2,2,2,3,3,3,3,3,3,3)
# Labels found
c2 = c(3,3,3,3,1,1,1,1,2,2,2,3,2,2,1)
# Labels found but renamed correctly
c3 = c(1,1,1,1,2,2,2,2,3,3,3,1,3,3,2)

# Current output
tab1 <- table(c1,c2)
#   c2
#c1  1 2 3
#  1 1 0 4
#  2 3 0 0
#  3 1 5 1

# Desired output
tab2 <- table(c1,c3)
#   c3
#c1  1 2 3
#  1 4 1 0
#  2 0 3 0
#  3 1 1 5

实际上,c3 不可用。有没有从c2tab1获取c3tab2的简单方法?

【问题讨论】:

  • 这个问题已经被问过很多次了。答案是匈牙利算法。
  • @Anony-Mousse 你有什么例子可以提供吗?我用谷歌搜索了“匈牙利算法应急”,但似乎没有出现任何相关内容。
  • 排除意外,你会找到维基百科。

标签: r matrix cluster-analysis crosstab contingency


【解决方案1】:
c1 <- c(1,1,1,1,1,2,2,2,3,3,3,3,3,3,3)
c2 <- c(3,3,3,3,1,1,1,1,2,2,2,3,2,2,1)

## table works with factor variables internally
c1 <- as.factor(c1)
c2 <- as.factor(c2)

tab1 <- table(c1, c2)
#       c2
#    c1  1 2 3
#      1 1 0 4
#      2 3 0 0
#      3 1 5 1

您的问题本质上是:如何重新调整c2 以使一行的最大值位于主对角线上。就矩阵运算而言,这是一个列置换。

## find column permutation index
## this can potentially be buggy if there are multiple maxima on a row
## because `sig` may then not be a permutation index vector
## A simple example is:
## tab1 <- matrix(5, 3, 3); max.col(tab1, "first")
sig <- max.col(tab1, "first")
#[1] 3 1 2

## re-level `c2` (create `c3`)
c3 <- factor(c2, levels = levels(c2)[sig])

## create new contingency table
table(c1, c3)
#   c3
#c1  3 1 2
#  1 4 1 0
#  2 0 3 0
#  3 1 1 5

## if creation of `c3` is not necessary, just do
tab1[, sig]
#   c3
#c1  3 1 2
#  1 4 1 0
#  2 0 3 0
#  3 1 1 5

【讨论】:

  • 如果“如果一行中有多个最大值”怎么办?在这些情况下有没有办法做到这一点?
  • @Tendero 我现在不知道。或者实际上我知道,但是没有简单的 R 代码可以做到这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-21
  • 2021-12-12
  • 2017-10-02
  • 2019-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多