排列正方形 2 向意外事件 table(矩阵)的列以最大化其对角线
Permute columns of a square 2-way contingency table (matrix) to maximize its diagonal
做聚类后,找到的标签没有意义。可以计算一个偶然性 table 以查看哪些标签与原始标签最相关 类 如果基本事实可用。
我想自动排列意外事件的列 table 以最大化其对角线。例如:
# 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
是不可用的。有没有简单的方法从c2
、tab1
获取c3
、tab2
?
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
做聚类后,找到的标签没有意义。可以计算一个偶然性 table 以查看哪些标签与原始标签最相关 类 如果基本事实可用。
我想自动排列意外事件的列 table 以最大化其对角线。例如:
# 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
是不可用的。有没有简单的方法从c2
、tab1
获取c3
、tab2
?
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