随机森林中的变量选择和预测精度。

问题描述 投票:0回答:1

我有一个重复了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)。

随机森林不包括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 的模型中?

r random-forest feature-selection variable-selection
1个回答
1
投票

我认为你需要更多关于模型性能的信息。在只有一个测试样本的情况下,你可以推测很多为什么没有x1的RMSE更好,虽然x1的重要性最高。可能是变量之间的相关性或从训练集的噪声中解释。

为了获得更多的信息,我建议查看袋外误差,并进行交叉验证的超参数优化。如果你在测试不同的测试数据集后看到相同的行为,你可以做交叉验证与否x1。

希望对您有所帮助

© www.soinside.com 2019 - 2024. All rights reserved.