[英]How do I find out the RMSE of a random forest in R?
我需要根據回歸找出隨機森林的 RMSE。
首先,我將這個公式用於隨機森林:
randomForest(price ~ ., type = "regression", data = train.data, ntree = 400,
mtry = 20)
我是否需要在進一步的步驟中進行預測以找出其 RMSE? 因為我會用測試數據做一個預測,然后使用 rmse = (actual,predicted),這是我從包“Metrics”下載的。 此外,12 的種子適合具有 1000 個 obs 的數據。 和 20 個變量?
是的,您需要對測試數據使用預測。 我不知道你是在哪個點設置了你的種子,所以在下面的例子中,我在將數據拆分為訓練和測試時設置了一次種子,以便可以重現這個訓練、測試集。 另一個實例是在運行 randomForest 之前(在 lapply 中)。 種子是供您重現 randomForest 的結果。
例如:
library(randomForest)
library(MASS)
data = Boston
set.seed(999)
trn = sample(nrow(data),400)
traindata = data[trn,]
testdata = data[-trn,]
res = lapply(c(111,222),function(i){
set.seed(i)
fit = randomForest(medv ~.,data=traindata)
pred_values = predict(fit,testdata)
actual_values = testdata$medv
data.frame(seed=i,
metrics_rmse = rmse(pred_values,actual_values),
cal_rmse = mean((pred_values-actual_values)^2)^0.5
)
})
res = do.call(rbind,res)
head(res)
seed metrics_rmse cal_rmse
1 111 4.700245 4.700245
2 222 4.742978 4.742978
在將數據划分為training
組和test
組的場景中,要計算測試數據的均方根誤差 (RMSE),可以使用predict()
函數,然后計算 RMSE。
我們將使用來自mlbench
包的BostonHousing
數據進行說明。
library(randomForest)
library(mlbench)
library(caret) # use createDataPartition() function
set.seed(95014)
data(BostonHousing)
# partition based on whether house is adjacent to Charles River
inTraining <- createDataPartition(BostonHousing$chas, p = 0.6, list=FALSE)
training <- BostonHousing[inTraining,]
testing <- BostonHousing[-inTraining,]
fit <- randomForest(medv ~ ., training, ntree=30, type="regression")
生成模型后,我們可以通過打印模型輸出來查看training
數據集中的均方誤差。
fit
> fit
Call:
randomForest(formula = medv ~ ., data = training, ntree = 30, type = "regression")
Type of random forest: regression
Number of trees: 30
No. of variables tried at each split: 4
Mean of squared residuals: 16.90869
% Var explained: 81.51
要計算 RMSE,我們還可以提取fit$mse
的最后一個元素,它對應於創建的最終樹,並取其平方根。
# obtain MSE as of last element in fit$mse
# which should match the output from printout
fit$mse[length(fit$mse)]
# take square root to calculate RMSE for the model
sqrt(fit$mse[length(fit$mse)])
> fit$mse[length(fit$mse)]
[1] 16.90869
> sqrt(fit$mse[length(fit$mse)])
[1] 4.112018
要計算測試數據的 RMSE,我們需要首先生成預測值。
# now illustrate how to calculate RMSE on test data vs. training data
predValues <- predict(fit,testing)
RMSE 只是平方誤差平均值的平方根。
# we can calculate it directly
sqrt(mean((testing$medv -predValues)^2))
> sqrt(mean((testing$medv -predValues)^2))
[1] 2.944943
>
或者,我們可以加載Metrics
庫並使用其rmse()
函數。 請注意,它產生的結果與我們根據 Base R 計算的結果相同。
# compare to Metrics::rmse() function
library(Metrics)
rmse(testing$medv,predValues)
> rmse(testing$medv,predValues)
[1] 2.944943
關於種子的問題, set.seed()
函數固定隨機數生成器的開始,使分析的結果可重現。 它不會影響分析的“質量”。
通過在使用任何訪問隨機數生成器的 R 函數之前使用set.seed(95014)
,任何運行此答案中的代碼的人都將收到與此答案中發布的rmse()
完全相同的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.