gpt4 book ai didi

r - 有没有更快的方法在 R 中制作这个混淆矩阵表?

转载 作者:行者123 更新时间:2023-12-02 16:14:30 25 4
gpt4 key购买 nike

我正在尝试使用以下数据框在 R 中制作一个混淆矩阵表:

mydf <- structure(list(pred_class = c("dog", "dog", "fish", "cat", "cat", 
"dog", "fish", "cat", "dog", "fish"), true_class = c("cat", "cat",
"dog", "cat", "cat", "dog", "dog", "cat", "dog", "fish")), row.names = c(NA,
10L), class = "data.frame")

pred_class true_class
1 dog cat
2 dog cat
3 fish dog
4 cat cat
5 cat cat
6 dog dog

我已经生成了代码来执行我想要的操作 - 对于每个类(狗、猫或鱼),说明每一行是真阳性、假阳性、真阴性还是假阴性。

conf_mat <- mydf %>%
mutate(
dog_conf = case_when(
true_class == "dog" & pred_class == "dog" ~ "TP",
true_class == "dog" & pred_class != "dog" ~ "FN",
true_class != "dog" & pred_class == "dog" ~ "FP",
true_class != "dog" & pred_class != "dog" ~ "TN"
),
cat_conf = case_when(
true_class == "cat" & pred_class == "cat" ~ "TP",
true_class == "cat" & pred_class != "cat" ~ "FN",
true_class != "cat" & pred_class == "cat" ~ "FP",
true_class != "cat" & pred_class != "cat" ~ "TN"
),
fish_conf = case_when(
true_class == "fish" & pred_class == "fish" ~ "TP",
true_class == "fish" & pred_class != "fish" ~ "FN",
true_class != "fish" & pred_class == "fish" ~ "FP",
true_class != "fish" & pred_class != "fish" ~ "TN"
)
)

然而,这段代码非常重复且庞大。我不确定如何简化这个。有没有人有什么建议?谢谢。

最佳答案

这是 map 的一个选项,我们在其中循环遍历数据集的唯一元素,根据 OP 的帖子中指定的条件在循环中创建带有 transmute 的列,并且将这些列与原始数据绑定(bind)

library(dplyr)
library(purrr)
library(stringr)

map_dfc(unique(unlist(mydf)), ~
mydf %>%
transmute(!! str_c(.x, '_conf') :=
case_when(true_class == .x & pred_class == .x ~ "TP",
true_class == .x & pred_class != .x ~ "FN",
true_class != .x & pred_class == .x ~ "FP",
true_class != .x & pred_class != .x ~ "TN"
))) %>%
bind_cols(mydf, .)

-输出

#     pred_class true_class dog_conf cat_conf fish_conf
#1 dog cat FP FN TN
#2 dog cat FP FN TN
#3 fish dog FN TN FP
#4 cat cat TN TP TN
#5 cat cat TN TP TN
#6 dog dog TP TN TN
#7 fish dog FN TN FP
#8 cat cat TN TP TN
#9 dog dog TP TN TN
#10 fish fish TN TN TP

或者在关键的 val 数据集上使用 merge

keydat <- data.frame(pred_class = c(TRUE, TRUE, FALSE, FALSE), 
true_class = c(TRUE, FALSE, TRUE, FALSE),
conf = c("TP", "FN", "FP", "TN"))

un1 <- unique(unlist(mydf))
mydf[paste0(un1, "_conf")] <- lapply(un1, function(x)
merge(mydf == x, keydat, all.x = TRUE)$conf)

关于r - 有没有更快的方法在 R 中制作这个混淆矩阵表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67152785/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com