R語言數據挖掘實踐——使用randomForest包構建隨機森林

R語言數據挖掘實踐——使用randomForest包構建隨機森林

下面使用randomForest包在iris數據集上構建一個預測模型。使用randomForest()函數存在兩個限制:第一個限制是該函數不能處理帶有缺失值的數據,因此在用戶傳遞數據前先要推定數據;第二個限制是分類屬性的水平劃分數量的最大值為32,水平劃分大於32的分類屬性需要在調用randomForest()函數之前進行轉換。

另一種建立隨機森林的方法是使用party包中的cforest()函數,該函數沒有限定分類屬性的水平劃分數。但是,一般而言,具有多級水平的分類變量需要更多的內存空間,建立隨機森林所要花費的時間也更長。

這裡首先需要將iris數據集分為兩部分:70%為訓練集,30%為測試集。

> ind <- sample(2,nrow(iris),replace = TRUE,prob = c(0.7,0.3))

> trainData <- iris[ind==1,]

> testData <- iris[ind==2,]

其次,加載randomForest包,並訓練一個隨機森林。

> library(randomForest)

> rf <- randomForest(Species~.,data = trainData,ntree=100,proximity=TRUE)

> table(predict(rf),trainData$Species)

setosa versicolor virginica

setosa 33 0 0

versicolor 0 35 3

virginica 0 2 40

> print(rf)

Call:

randomForest(formula = Species ~ ., data = trainData, ntree = 100, proximity = TRUE)

Type of random forest: classification

Number of trees: 100

No. of variables tried at each split: 2

OOB estimate of error rate: 4.42%

Confusion matrix:

setosa versicolor virginica class.error

setosa 33 0 0 0.00000000

versicolor 0 35 2 0.05405405

virginica 0 3 40 0.06976744

> attributes(rf)

$names

[1] "call" "type" "predicted" "err.rate" "confusion" "votes"

[7] "oob.times" "classes" "importance" "importanceSD" "localImportance" "proximity"

[13] "ntree" "mtry" "forest" "y" "test" "inbag"

[19] "terms"

$class

[1] "randomForest.formula" "randomForest"

由結果可知,即使在決策樹中,仍然有誤差,第二類和第三類話仍然會被誤判,可以通過輸入print(rf)知道誤判率為2.88%,也可以通過輸入plot(rf)繪製每一棵樹的誤判率的圖。

>plot(rf)

R語言數據挖掘實踐——使用randomForest包構建隨機森林

變量的重要性可以通過importance()函數和varImPlot()函數獲得:

> importance(rf)

MeanDecreaseGini

Sepal.Length 9.375216

Sepal.Width 3.225098

Petal.Length 30.026388

Petal.Width 31.218726

> varImpPlot(rf)

R語言數據挖掘實踐——使用randomForest包構建隨機森林

最後,在測試集上測試訓練集上建立的隨機森林,並使用table()函數和margin()函數檢測預測結果。

> irisPred <- predict(rf, newdata = testData)

> table(irisPred, testData$Species)

irisPred setosa versicolor virginica

setosa 17 0 0

versicolor 0 13 2

virginica 0 0 5

> plot(margin(rf,testData$Species))

R語言數據挖掘實踐——使用randomForest包構建隨機森林

由上圖結果可知,數據點的邊距為正確歸類的比例減去被歸到其他類別的最大比例。一般說來,邊距為正數說明 該數據點劃分正確。

相關推薦

推薦中...