如果测试数据中存在新的因子水平,R 中的随机森林包在预测()期间会显示错误.有什么办法可以避免这个错误吗? [英] Random forest package in R shows error during prediction() if there are new factor levels present in test data. Is there any way to avoid this error?

查看:36
本文介绍了如果测试数据中存在新的因子水平,R 中的随机森林包在预测()期间会显示错误.有什么办法可以避免这个错误吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的训练数据中有 30 个因子水平的预测变量.我的测试数据中再次有 30 个相同预测因子的因子水平,但有些水平不同.除非级别完全相同,否则 randomForest 不会进行预测.它显示错误.说,predict.randomForest(模型,测试)中的错误训练数据中不存在的新因子水平

I have 30 factor levels of a predictor in my training data. I again have 30 factor levels of the same predictor in my test data but some levels are different. And randomForest does not predict unless the levels are same exactly. It shows error. Says, Error in predict.randomForest(model,test) New factor levels not present in the training data

推荐答案

我发现的一种解决方法是首先将训练和测试集中的因子变量转换为字符

One workaround I've found is to first convert the factor variables in your train and test sets into characters

test$factor <- as.character(test$factor)

然后为每个列添加一个带有测试/训练标志的列,即

Then add a column to each with a flag for test/train, i.e.

test$isTest <- rep(1,nrow(test))
train$isTest <- rep(0,nrow(train))

然后绑定它们

fullSet <- rbind(test,train)

然后转换回一个因子

fullSet$factor <- as.factor(fullSet$factor)

这将确保测试集和训练集具有相同的级别.然后你可以分开:

This will ensure that both the test and train sets have the same levels. Then you can split back off:

test.new <- fullSet[fullSet$isTest==1,]
train.new <- fullSet[fullSet$isTest==0,]

并且您可以从每个列中删除/NULL 的 isTest 列.然后,您将拥有可以训练和测试的相同级别的集合.可能有更优雅的解决方案,但这在过去对我有用,如果您需要经常重复,可以将其写成一个小函数.

and you can drop/NULL out the isTest column from each. Then you'll have sets with identical levels you can train and test on. There might be a more elegant solution, but this has worked for me in the past and you can write it into a little function if you need to repeat it often.

这篇关于如果测试数据中存在新的因子水平,R 中的随机森林包在预测()期间会显示错误.有什么办法可以避免这个错误吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆