0

我试图确保在我的树对象和用于预测的测试集中,我的类型因子的所有特征都被完全表示(就所有可能的因子水平而言)。

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
4

1 回答 1

0

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

只需在整个数据集(训练 + 测试)上制作模型,对测试观察结果赋予零权重。这样,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

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

于 2019-11-06T10:52:19.420 回答