如何处理R的预测函数中的错误? [英] How to handle errors in predict function of R?
问题描述
我有一个数据框 df,我正在构建一个机器学习模型(C5.0 决策树)来预测列的类别(loan_approved):
I have a dataframe df, I am building an machine learning model (C5.0 decision tree) to predict the class of a column (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
问题:
我知道这是因为测试数据框有一个新的级别,在训练数据中不存在,但我的函数不应该在除此之外的所有情况下都适用吗?
I know this is because the test data frame had a new level that was not present in train data, but should not my function work all cases except this?
P.S:没有使用sapply,因为它太慢了
P.S: did not use sapply because it was too slow
推荐答案
这个问题有两个部分.
- 问题的第一部分出现在模型训练期间,因为如果进行随机拆分,则训练和测试之间的分类变量不会平均分配.在您的情况下,假设您只有一个职业水手"的记录,那么当您进行随机拆分时,它可能最终会出现在测试集中.使用火车数据集构建的模型永远不会看到职业水手"的影响,因此会抛出错误.在更一般的情况下,其他一些分类变量级别可能会在随机拆分后完全进入测试集.
因此,您可以进行分层抽样,而不是在训练和测试之间随机划分数据.使用 data.table
进行 70:30 拆分的代码是:
So instead of dividing the data randomly in between train and test you can do stratified sampling. Code using data.table
for 70:30 split is :
ind <- total_data[, sample(.I, round(0.3*.N), FALSE),by="occupation"]$V1
train <- total_data[-ind,]
test <- total_data[ind,]
这确保任何级别在训练和测试数据集之间均分.所以你不会在测试数据集中得到新的"分类级别;在随机分裂的情况下可能存在.
This makes sure any level is divided equally among train and test dataset. So you will not get "new" categorical level in test dataset; which in random splitting case could be there.
问题的第二部分出现在模型在生产中时,它遇到了一个全新的变量,该变量甚至在训练或测试集中都不存在.为了解决这个问题,可以使用以下方法维护所有类别变量的所有级别的列表
lvl_cat_var1 <- unique(cat_var1)
和lvl_cat_var2 <- unique(cat_var2)
等等.然后在预测之前可以检查新级别和过滤器:
Second part of the problem comes when model is in production and it encounters a altogether new variable which was not there in even training or test set. To tackle this problem one can maintain a list of all levels of all categorical variables by using
lvl_cat_var1 <- unique(cat_var1)
andlvl_cat_var2 <- unique(cat_var2)
etc. Then before predict one can check for new level and filter:
new_lvl_data <- total_data[!(var1 %in% lvl_cat_var1 & var2 %in% lvl_cat_var2)]
pred_data <- total_data[(var1 %in% lvl_cat_var1 & var2 %in% lvl_cat_var2)]
然后对于默认预测执行:
then for the default prediction do:
new_lvl_data$predicted_class <- "no"
以及对 pred_data 的全面预测.
and full blown prediction for pred_data.
这篇关于如何处理R的预测函数中的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!