使用REEMtree模型预测时出现观测数与组标识符不匹配错误
问题:REEMtree预测时出现观测数与分组标识符长度不匹配错误
Error in predict.REEMtree(my_REEMtree, newdata = testing_data) :
number of observations in newdata does not match the length of the group identifiers
可复现代码:
library(caret) library(REEMtree) library(rpart) # Generate synthetic data with pupils in classes n_classes <- 30 n_pupils <- 30 ds <- data.frame( x1 = rnorm(n_classes * n_pupils, 0, 1), z1 = rep(rnorm(n_classes, 0, 1), each = n_pupils) ) ds$y = 1 + 2 * ds$x1 + 3 * ds$z1 + rnorm(n_classes * n_pupils, 0, 1) ds$class_id <- as.factor(rep(1:n_classes, each = n_pupils)) # creates the class id # Split the data set.seed(123) # For reproducibility trainingRows <- createDataPartition(ds$y, p = .80, list = FALSE) training_data <- ds[trainingRows,] testing_data <- ds[-trainingRows,] # Fit the model my_REEMtree <- REEMtree(y ~ x1 + z1, data=training_data, random=~1|class_id, tree.control=rpart.control(cp=0.001)) # Predict with the model predictions <- predict(my_REEMtree, newdata=testing_data) # Perform checks to address error print(levels(ds$class_id)) print(levels(training_data$class_id)) print(levels(testing_data$class_id)) sum(is.na(training_data$class_id)) sum(is.na(testing_data$class_id)) summary(testing_data$class_id) all(levels(training_data$class_id) == levels(testing_data$class_id)) # returns TRUE
已验证:class_id列无NA值,训练集与测试集因子水平完全一致。
错误原因与解决思路
错误原因
REEMtree的predict.REEMtree函数内部逻辑存在缺陷:使用默认参数预测时,它会调用训练集的分组随机效应估计值,但错误要求测试集每个分组的观测数与训练集对应分组的观测数完全匹配——这不符合常规的测试集拆分逻辑,因此触发报错。
解决思路
根据是否需要保留随机效应,有两种解决方案:
1. 仅使用固定效应预测(快速解决)
直接指定type="fixed"参数,跳过随机效应的匹配逻辑,仅用树模型的固定效应部分生成预测结果:
predictions <- predict(my_REEMtree, newdata=testing_data, type="fixed")
2. 包含随机效应的预测(完整逻辑)
如果需要保留随机效应的影响,需手动提取训练集中的随机效应估计值,合并到测试集后计算最终预测:
# 提取训练集中每个class_id的随机效应值 ranef_vals <- data.frame( class_id = rownames(my_REEMtree$ranef), random_effect = my_REEMtree$ranef[, 1] ) # 将随机效应合并到测试集 testing_data <- merge(testing_data, ranef_vals, by = "class_id", all.x = TRUE) # 先计算固定效应预测值 fixed_preds <- predict(my_REEMtree, newdata=testing_data, type="fixed") # 固定效应+随机效应得到最终预测 final_predictions <- fixed_preds + testing_data$random_effect
内容的提问来源于stack exchange,提问作者Linus
相关产品推荐
相关产品推荐

