我有一个重复了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.041,含 x1
对1885.462,无 x1
)
不过 MAE
稍微好一点的是 x1
(299.0751)与没有它(302.3382)。
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
的模型中?
我认为你需要更多关于模型性能的信息。在只有一个测试样本的情况下,你可以推测很多为什么没有x1的RMSE更好,虽然x1的重要性最高。可能是变量之间的相关性或从训练集的噪声中解释。
为了获得更多的信息,我建议查看袋外误差,并进行交叉验证的超参数优化。如果你在测试不同的测试数据集后看到相同的行为,你可以做交叉验证与否x1。
希望对您有所帮助