位置:首頁 > 大數據教學 > R語言教學 > R語言隨機森林

R語言隨機森林

在隨機森林做法是由大量的決策樹來創建的。每個觀察被送入每一個決定樹。對於每個觀測的最常見的結果被用作最終的輸出。一個新的觀察被送入所有樹,並采取多數表決每個分類模型。

錯誤估算出其在構建樹不使用的情況下。這就是所謂的 OOB 所提到以百分比(外袋)錯誤估計。

R軟件包 “randomForest” 用於創建隨機森林。

安裝R軟件包

R中控製台使用下麵的命令來安裝該軟件包。還必須安裝相關程序包(如有)。

install.packages("randomForest)

包 “randomForest” 中有 randomForest()函數,它用於創建並分析隨機森林。

語法

在 R 中創建一個隨機森林的基本語法是:

randomForest(formula, data)

以下是所使用的參數的說明:

  • formula 是一個公式描述的預測和響應變量。
  • data 是所使用的數據集的名稱。

輸入數據

我們將使用 R 內置的數據集名為 readingSkills 來創建一個決策樹。它描述了一個人的 readingSkills 的得分,如果我們知道變量:

"age","shoesize","score" 和是否為母語的人。

下麵是示例數據。

# Load the party package. It will automatically load other required packages.
library(party)

# Print some records from data set readingSkills.
print(head(readingSkills))

當我們上麵的代碼執行,它會產生以下結果及圖表:

  nativeSpeaker age shoeSize    score
1           yes   5 24.83189 32.29385
2           yes   6 25.95238 36.63105
3            no  11 30.42170 49.60593
4           yes   7 28.66450 40.28456
5           yes  11 31.88207 55.46085
6           yes  10 30.07843 52.83124
Loading required package: methods
Loading required package: grid
...............................
...............................

示例

我們將使用 randomForest()函數來創建決策樹,看看它的圖形。

# Load the party package. It will automatically load other required packages.
library(party)
library(randomForest)

# Create the forest.
output.forest <- randomForest(nativeSpeaker ~ age + shoeSize + score,   data=readingSkills)

# View the forest results.
print(output.forest) 

# Importance of each predictor.
print(importance(fit,type=2)) 

當我們上麵的代碼執行時,它產生以下結果:

Call:
 randomForest(formula = nativeSpeaker ~ age + shoeSize + score,      data = readingSkills) 
               Type of random forest: classification
                     Number of trees: 500
No. of variables tried at each split: 1

        OOB estimate of  error rate: 1%
Confusion matrix:
    no yes class.error
no  99   1        0.01
yes  1  99        0.01
         MeanDecreaseGini
age              13.95406
shoeSize         18.91006
score            56.73051

結論

從以上所示的隨機森林,我們可以得出這樣的結論:如果有人是或不是母語, shoesize 和 score 是確定的重要因素。另外,模型隻有1%的誤差,這意味著我們能有 99% 的準確度預測。