我有一个名为df的数据框,我正在构建一个机器学习模型(C5.0决策树)来预测一列(loan_approved)的类别:
结构(非真实数据):
id occupation income loan_approved
1 business 4214214 yes
2 business 32134 yes
3 business 43255 no
4 sailor 5642 yes
5 teacher 53335 no
6 teacher 6342 no
过程:
- 我将数据框随机拆分为测试集和训练集,从训练集中学习(使用行1、2、3、5、6作为训练集,使用第4行作为测试集)
- 为了考虑一个或多个列中的新分类级别,我使用了try函数
功能:
error_free_predict = function(x){
output = tryCatch({
predict(C50_model, newdata = test[x,], type = "class")
}, error = function(e) {
"no"
})
return(output)
}
应用预测功能:
test <- mutate(test, predicted_class = error_free_predict(1:NROW(test)))
问题:
id occupation income loan_approved predicted_class
1 business 4214214 yes no
2 business 32134 yes no
3 business 43255 no no
4 sailor 5642 yes no
5 teacher 53335 no no
6 teacher 6342 no no
问题:
我知道这是因为测试数据框中有一个新的级别,而训练数据中没有,但我的函数不应该在除此之外的所有情况下都起作用吗?
P.S.:没有使用sapply,因为它太慢了。
predict
调用返回的错误是什么? - cdeterman