【问题标题】:Adding the value to each row of data frame, given a vector of names of columns给定列名向量,将值添加到数据框的每一行
【发布时间】:2019-05-19 12:52:40
【问题描述】:

我正在为分类模型列表编写 predict 函数,因此每个模型都会对某些预测进行投票。

我创建了以下函数,但速度很慢。最里面的for 循环需要很长时间来计算。

predict.risemble <- function(.models, .dataset) {
  all_levels <- unique(unlist(lapply(.models, function(x) x$levels)))
  voting_df <- data.frame(matrix(0, ncol = length(all_levels), nrow = nrow(.dataset)))
  colnames(voting_df) <- all_levels
  voting_df <- as_tibble(voting_df)
  for (model in .models) {
    cat(sprintf("Making predictions for model %s\n", model$method))
    predictions <- predict(model, .dataset)
    cat("Voting ...\n")
    for (i in 1:length(predictions)) {
      prediction <- as.character(predictions[i])
      voting_df[i, prediction] <- voting_df[i, prediction] + model$results$Kappa
      if (mod(i, 1000) == 0) {
        cat(sprintf("%f%%\n", i / length(predictions) * 100))
      }
    }
  }
  return (as.factor(colnames(voting_df)[apply(voting_df, 1, which.max)]))
}

我需要加快最里面的for循环。

因此,给定一个预测向量(factor 类),我们可以使用as.character 将其转换为列名列表(character 类)。我们称这个向量为predictions

在给定列向量predictions 的情况下,我需要为voting_df 的每一行添加一些特定值。

例子:

predictions <- c("a", "a", "a", "b", "c")
> voting_df
# A tibble: 5 x 3
      a     b     c
  <dbl> <dbl> <dbl>
1     1     0     0
2     1     0     0
3     1     0     0
4     0     1     0
5     0     0     1

编辑 我的predict 函数的最终版本是这样的:

predict.risemble <- function(.models, .dataset) {
  all_levels <- unique(unlist(lapply(.models, function(x) x$levels)))
  voting_df <- data.frame(matrix(0, ncol = length(all_levels), nrow = nrow(.dataset)))
  colnames(voting_df) <- all_levels
  voting_df <- as_tibble(voting_df)
  voting_df <- voting_df %>% select(noquote(order(colnames(voting_df))))
  for (model in .models) {
    predictions <- as.character(predict(model, .dataset))
    votes <- tibble(prediction = predictions) %>%
      mutate(prediction_id = row_number(), value = model$results$Kappa) %>%
      spread(prediction, value) %>%
      select(-one_of("prediction_id"))
    votes[, all_levels[!all_levels %in% names(votes)]] <- NA
    votes <- votes %>% select(noquote(order(colnames(votes))))
    votes[is.na(votes)] <- 0
    voting_df <- voting_df + votes
  }
  return (as.factor(colnames(voting_df)[apply(voting_df, 1, which.max)]))
}

【问题讨论】:

  • 我正在编写自己的 predict 函数,因为 caretEnsemble 在训练中需要 savePredictions。但我已经训练过模型。我不会重新进行训练,因为我总共花了 72 小时来训练我的所有模型。

标签: r


【解决方案1】:

我会尝试从您的向量构建一个数据框,然后使用 tidyrs 扩展函数:

library(tidyverse)
tibble(pred =predictions) %>%
mutate(pred_id = row_number(), value =1) %>%
spread(pred, value)

然后可能将 NA 替换为零。这对你的目的有用吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-15
    • 2020-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多