我使用线性回归来处理一个包含许多分类变量的数据集,每个分类变量包含几个类别,其中一个类别中最多有45个类别。
我以这种方式对数据进行采样:
## 70% of the sample size
smp_size <- floor(0.7 * nrow(plot_data))
## set the seed to make your partition reproductible
set.seed(888)
train_ind <- sample(seq_len(nrow(plot_data)), size = smp_size)
train <- plot_data[train_ind, ]
test <- plot_data[-train_ind, ]
然后我把模型做成这样:
linear_model = lm(train$dependent_variable~., data = train)
问题是,每当我尝试预测和使用测试集时,训练集都包含一些训练集没有的类别。
pred_data = predict(linear_model, newdata = test)
这给了我以下错误:
Error in model.frame.default(Terms, newdata, na.action = na.action, xlev = object$xlevels) :
factor origin has new levels someCategory1, SomeCategory2
是否有办法确保所有类别都在列车和测试集中,或者是否有解决方法?