【问题标题】:R update ctree (package party) features factors levelsR更新ctree(包方)功能因素级别
【发布时间】:2016-02-08 13:55:02
【问题描述】:

我正在努力确保在我的树对象和用于预测的测试集中,我的类型因子的所有特征(就所有可能的因子级别而言)都得到了充分的表示。

for (j in 1:length(predictors)){
    if (is.factor(Test[,j])){
      ct [[names(predictors)[j]]] <- union(ct$xlevels[[names(predictors)[j]]], levels(Test[,c(names(predictors)[j])]))

    }
}

但是,对于对象 ct(来自包方的 ctree),我似乎无法理解如何访问功能的因子级别,因为我遇到了错误

Error in ct$xlevels : $ operator not defined for this S4 class

【问题讨论】:

  • party 使用 s4 方法,你没有用 $ 索引,你应该阅读?'BinaryTree-class'
  • 可能在partykit 中使用ctree 的新S3 实现更容易用于您的目的...它还附带更多文档。

标签: r decision-tree party


【解决方案1】:

我无数次遇到这个问题,今天我想出了一个小技巧,应该不需要修复关卡因素的差异。

只需在整个数据集(训练 + 测试)上创建模型,对测试观察结果赋予零权重。这样 ctree 模型就不会降低因子水平。

a <- ctree(Y ~ ., DF[train.IDs,]) %>% predict(newdata = DF) # Would trigger error if the data passed to predict would not match the train data levels
b <- ctree(Y ~ ., weights = as.numeric((1:nrow(DF) %in% train.IDs)), data = DF) %>% predict(newdata = DF) # passing the IDs as 0-1 in the weights instead of subsetting the data solves it
mean(a == b) # test that predictions are equals, should be 1

告诉我它是否按预期工作!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-18
    • 1970-01-01
    • 2012-01-25
    • 2018-04-26
    • 2019-12-21
    • 2018-06-27
    • 1970-01-01
    • 2022-01-18
    相关资源
    最近更新 更多