【问题标题】:How to vote binary outcome of predictions如何对预测的二元结果进行投票
【发布时间】:2026-01-15 11:45:01
【问题描述】:

考虑到泰坦尼克号数据集,我创建了几个关于生存的预测,我想基于投票系统创建最终的生存,这意味着如果大多数预测规定乘客幸存,最终结果为 1,否则为 0

> str(temp)
'data.frame':   179 obs. of  3 variables:
 $ predictions_ldm    : Factor w/ 2 levels "0","1": 1 1 1 1 1 1 1 1 1 1 ...
 $ predictions_qda    : Factor w/ 2 levels "0","1": 1 1 1 1 2 1 1 1 1 1 ...
 $ predictions_glm_age: Factor w/ 2 levels "0","1": 1 1 1 1 1 1 1 1 1 1 ...
> temp[c(4,5,12),]
   predictions_ldm predictions_qda predictions_glm_age
4                0               0                   0
5                0               1                   0
12               1               1                   0

我希望结果是

> temp[c(4,5,12),]
   predictions_ldm predictions_qda predictions_glm_age            Survived
4                0               0                   0                   0
5                0               1                   0                   0
12               1               1                   0                   1

我怎样才能做到这一点?

【问题讨论】:

  • 你可以得到rowMeans,然后如果它们大于0.5就把1,否则0?喜欢ifelse(rowMeans(temp) > 0.5, 1, 0)?
  • 问题是 temp 是因子的数据框
  • 我找到了一个解决方案,但我认为这不是最佳解决方案votedSurvival <- as.factor(as.numeric(apply(temp,1,FUN = function(z) {mean(as.numeric(z))>0.5})))
  • 很好的解决办法,另外一个类似的方法是在函数中使用apply(temp, 1, function(x) names(sort(-table(x[1])))),不会转成数字

标签: r prediction


【解决方案1】:

使用dplyr 是一个不必要的复杂解决方案,但我真的很想使用c_across()。起初,我需要将您的因子转换为保持 0-1 值的整数。

temp %>%
  mutate(across(where(is.factor), function(x) { x %>% 
      as.character() %>% 
      as.integer()
    } )) %>%
  rowwise %>%
  mutate(Survived = c_across() %>% 
           mean() %>%
           round() %>%
           as.integer)

【讨论】:

  • 谢谢,我会试试的,我也找到了一个相当复杂的解决方案votedSurvival <- as.factor(as.numeric(apply(temp,1,FUN = function(z) {mean(as.numeric(z))>0.5})))
  • 您需要Survived 成为一个因素吗?
  • 是的。我想得到准确度print(mean(votedSurvival == test_set$Survived))
【解决方案2】:

你可以使用Mode函数定义here

Mode <- function(x) {
  ux <- unique(x)
  ux[which.max(tabulate(match(x, ux)))]
}

并逐行应用此函数:

temp$Survived <- apply(temp[c(4,5,12),], 1, Mode)

Mode 返回向量中出现频率最高的值。

【讨论】: