R - Random Forest

在随机森林方法中,创建了大量决策树.每个观察都被送入每个决策树.每次观察的最常见结果用作最终输出.一个新的观察结果被输入所有树木并对每个分类模型进行多数投票.

对构建树时未使用的情况进行错误估计.这称为 OOB(Out-of-bag)错误估计值,以百分比形式提及.

R包"randomForest"用于创建随机森林.

安装R软件包

在R控制台中使用以下命令安装软件包.您还必须安装依赖包.如果有的话.

install.packages("randomForest"

包"randomForest"具有函数 randomForest(),用于创建和分析随机森林.

语法

在R中创建随机森林的基本语法是 :

randomForest(formula,data)

以下是所用参数的说明及减号;

  • 公式是描述预测变量和响应变量的公式.

  • 数据是使用的数据集.

输入数据

我们将使用R内置数据设置名为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 &plus; shoeSize &plus; score, 
           data = readingSkills)

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

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

当我们执行上面的代码时,它产生以下结果 :

Call:
 randomForest(formula = nativeSpeaker ~ age &plus; shoeSize &plus; 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%.