- R 教程
- R - 首頁
- R - 概述
- R - 環境設定
- R - 基本語法
- R - 資料型別
- R - 變數
- R - 運算子
- R - 決策
- R - 迴圈
- R - 函式
- R - 字串
- R - 向量
- R - 列表
- R - 矩陣
- R - 陣列
- R - 因子
- R - 資料框
- R - 包
- R - 資料重塑
R - 隨機森林
在隨機森林方法中,會建立大量的決策樹。每個觀測值都會輸入到每個決策樹中。每個觀測值最常見的輸出結果將用作最終輸出。將新的觀測值輸入到所有樹中,並對每個分類模型進行多數投票。
對構建樹時未使用的案例進行誤差估計。這被稱為**袋外 (OOB)** 誤差估計,以百分比表示。
R 包**“randomForest”** 用於建立隨機森林。
安裝 R 包
在 R 控制檯中使用以下命令安裝包。如有任何依賴包,也需要安裝。
install.packages("randomForest)
“randomForest”包包含**randomForest()** 函式,用於建立和分析隨機森林。
語法
在 R 中建立隨機森林的基本語法如下:
randomForest(formula, data)
以下是所用引數的描述:
**formula** 是一個描述預測變數和響應變數的公式。
**data** 是所用資料集的名稱。
輸入資料
我們將使用名為 readingSkills 的 R 內建資料集來建立決策樹。如果我們知道變數“年齡”、“鞋碼”、“分數”以及此人是否是母語人士,它描述了某人閱讀能力的分數。
以下是示例資料。
# 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
結論
從上面顯示的隨機森林中,我們可以得出結論,鞋碼和分數是決定某人是母語人士還是非母語人士的重要因素。此外,模型的錯誤率僅為 1%,這意味著我們可以以 99% 的準確率進行預測。
廣告