如何在随机森林算法中分组和建模以获得数据中单个人 ID 的单个预测?

How to groupby and model in random forest algorithm to get a single prediction for a single person id in the data?

下面给出的是伪数据-训练数据

我正在为 R 中的二元分类实现随机森林算法。

rf=randomForest(Default~.,data=traindata,ntree=300,mtry=18,importance=TRUE)

我想在个人 personalid 上拟合模型。

比如 personid 112 预测 10.

现在,我的模型接收了全部数据,并对每个月给出了不同的预测。 我想得到基于 personid 的预测。

单个 ID 的单个预测,而不是不同月份。

我的personid总数是265.

使用 dplyr 包中的 group_by() 对我有帮助吗?

由于personid的数量很大,那么我将如何预测新数据?

*条件我无法对数据进行平均以使其变平,因为这是财务数据。

您可以使用 dplyrtidyr 获取每个 personID 一行的所有数据。请参见下面的示例。您将在 rf 模型中使用许多额外变量,这可能正是您所需要的。

library(dplyr)
library(tidyr)


spread_data <- df %>%
  gather(Balances, value, starts_with("Balance")) %>% 
  unite(Bal_month, Balances, Month) %>% 
  spread(Bal_month, value)

personid Default Balance1_Month1 Balance1_Month2 Balance1_Month3 Balance1_Month4 Balance2_Month1 Balance2_Month2 Balance2_Month3
1      112       1          123465        45343456              NA              NA          234567         5498731              NA
2      113       0          534564         9616613            6164              NA           64613            3496         3189479
3      114       1             621         1615494           32165              NA            3168              97          165197
4      115       0       123164964           97946           21679          791639           47643            1679             179
  Balance2_Month4
1              NA
2              NA
3              NA
4          167976

更多关于铸造的阅读: how to spread or cast multiple values in r 要么 can the value.var in dcast be a list or have multiple value variables?

使用的示例数据:

df <-
  structure(
    list(
      personid = c(
        112L,
        112L,
        113L,
        113L,
        113L,
        114L,
        114L,
        114L,
        115L,
        115L,
        115L,
        115L
      ),
      Month = c(
        "Month1",
        "Month2",
        "Month1",
        "Month2",
        "Month3",
        "Month1",
        "Month2",
        "Month3",
        "Month1",
        "Month2",
        "Month3",
        "Month4"
      ),
      Balance1 = c(
        123465,
        45343456,
        534564,
        9616613,
        6164,
        621,
        1615494,
        32165,
        123164964,
        97946,
        21679,
        791639
      ),
      Balance2 = c(
        234567,
        5498731,
        64613,
        3496,
        3189479,
        3168,
        97,
        165197,
        47643,
        1679,
        179,
        167976
      ),
      Default = c(1L, 1L, 0L, 0L, 0L, 1L, 1L, 1L, 0L, 0L, 0L, 0L)
    ),
    .Names = c("personid", "Month", "Balance1", "Balance2", "Default"),
    class = "data.frame",
    row.names = c(NA,-12L)
  )