我有一个横截面数据集重复了 2 年,2009 年和 2010 年。我使用第一年(2009 年)作为训练集来训练回归问题的随机森林,第二年(2010 年)作为测试集.
加载数据
df <- read.csv("https://www.dropbox.com/s/t4iirnel5kqgv34/df.cv?dl=1")
在 2009 年训练随机森林后,变量重要性表明该变量x1
是最重要的变量。
使用所有变量的随机森林
set.seed(89)
rf2009 <- randomForest(y ~ x1 + x2 + x3 + x4 + x5 + x6,
data = df[df$year==2009,],
ntree=500,
mtry = 6,
importance = TRUE)
print(rf2009)
Call:
randomForest(formula = y ~ x1 + x2 + x3 + x4 + x5 + x6, data = df[df$year == 2009, ], ntree = 500, mtry = 6, importance = TRUE)
Type of random forest: regression
Number of trees: 500
No. of variables tried at each split: 6
Mean of squared residuals: 5208746
% Var explained: 75.59
可变重要性
imp.all <- as.data.frame(sort(importance(rf2009)[,1],decreasing = TRUE),optional = T)
names(imp.all) <- "% Inc MSE"
imp.all
% Inc MSE
x1 35.857840
x2 16.693059
x3 15.745721
x4 15.105710
x5 9.002924
x6 6.160413
然后我转到测试集,我收到以下准确度指标。
对测试集的预测和评估
test.pred.all <- predict(rf2009,df[df$year==2010,])
RMSE.forest.all <- sqrt(mean((test.pred.all-df[df$year==2010,]$y)^2))
RMSE.forest.all
[1] 2258.041
MAE.forest.all <- mean(abs(test.pred.all-df[df$year==2010,]$y))
MAE.forest.all
[1] 299.0751
然后,当我在没有变量的情况下训练模型x1
时,这是上面最重要的变量,并将训练后的模型应用于测试集,我观察到以下情况:
解释的方差
x1
比没有x1
预期的要高但是对于
RMSE
测试数据来说,没有更好x1
(RMSE
:2258.041x1
与 1885.462 没有x1
)尽管如此
MAE
,使用x1
(299.0751) 与没有它 (302.3382) 相比要好一些。
不包括 x1 的随机森林
rf2009nox1 <- randomForest(y ~ x2 + x3 + x4 + x5 + x6,
data = df[df$year==2009,],
ntree=500,
mtry = 5,
importance = TRUE)
print(rf2009nox1)
Call:
randomForest(formula = y ~ x2 + x3 + x4 + x5 + x6, data = df[df$year == 2009, ], ntree = 500, mtry = 5, importance = TRUE)
Type of random forest: regression
Number of trees: 500
No. of variables tried at each split: 5
Mean of squared residuals: 6158161
% Var explained: 71.14
可变重要性
imp.nox1 <- as.data.frame(sort(importance(rf2009nox1)[,1],decreasing = TRUE),optional = T)
names(imp.nox1) <- "% Inc MSE"
imp.nox1
% Inc MSE
x2 37.369704
x4 11.817910
x3 11.559375
x5 5.878555
x6 5.533794
对测试集的预测和评估
test.pred.nox1 <- predict(rf2009nox1,df[df$year==2010,])
RMSE.forest.nox1 <- sqrt(mean((test.pred.nox1-df[df$year==2010,]$y)^2))
RMSE.forest.nox1
[1] 1885.462
MAE.forest.nox1 <- mean(abs(test.pred.nox1-df[df$year==2010,]$y))
MAE.forest.nox1
[1] 302.3382
我知道变量重要性是指训练模型而不是测试模型,但这是否意味着x1
变量不应该包含在模型中?
那么,我应该包含x1
在模型中吗?