randomForest

Author

データサイエンス関連基礎調査WG

Published

August 1, 2025

パッケージの概要

機械学習におけるRandomForestモデルを構築できます。RandomForestモデルとは、多数の決定木を集めてそれらの予測値よりモデル全体の予測値を算出する、アンサンブルモデルの一種です。

参考URL

https://momonoki2017.blogspot.com/2018/04/r007-riris.html

使用例:irisデータの分類

irisデータを用いて、がく弁・花弁の長さ・幅の情報からアヤメの種類を特定するRandomForestモデルをrandomForestパッケージを用いて構築します。

irisデータセットを読み込む

irisデータを読み込み、データの先頭を表示します。

  • Sepal.Length:がく弁の長さ
  • Sepal.Width:がく弁の幅
  • Petal.Length:花弁の長さ
  • Petal.Width:花弁の幅

アヤメの種類はsetosa(1)、versicolor(2)、virginica(3)の3種類です。

data(iris)
head(iris)
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

irisデータの構造

irisデータの各種構造を確認します。

str(iris)
'data.frame':   150 obs. of  5 variables:
 $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
 $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
 $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
 $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
 $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...

また、データを散布図にプロットして確認します。

plot(iris, col=c(2, 3, 4)[iris$Species])

モデル構築1(全体データ)

まずは全てのデータを使ってRandomForestモデルを構築してみます。

(iris.rf <- randomForest(Species ~ ., data = iris))

Call:
 randomForest(formula = Species ~ ., data = iris) 
               Type of random forest: classification
                     Number of trees: 500
No. of variables tried at each split: 2

        OOB estimate of  error rate: 4%
Confusion matrix:
           setosa versicolor virginica class.error
setosa         50          0         0        0.00
versicolor      0         47         3        0.06
virginica       0          3        47        0.06

重要度の確認

データの各特徴量の重要度を確認することが出来ます。irisデータの分類には花弁の長さ・花弁の幅の情報が重要であることが分かります。

importance(iris.rf)
             MeanDecreaseGini
Sepal.Length         9.937619
Sepal.Width          2.440018
Petal.Length        40.254780
Petal.Width         46.644024

モデル構築2(訓練データとテストデータに分割)

irisデータをモデル生成のための訓練データと、モデル評価のためのテストデータに分割します。データ割合は訓練データを7割、テストデータを3割とします。確認のため、データサイズを出力します。

# 再現性のためにシードを設定
set.seed(123)  

# データの分割
sample_indices <- sample(1:nrow(iris), 0.7 * nrow(iris))  
df.train <- iris[sample_indices, ]
df.test <- iris[-sample_indices, ]

# データサイズの確認
c(nrow(iris), nrow(df.train), nrow(df.test))
[1] 150 105  45

モデル生成

訓練データを用いてRandomFOrestモデルを生成します。

(model.rf <- randomForest(Species ~ ., data = df.train))

Call:
 randomForest(formula = Species ~ ., data = df.train) 
               Type of random forest: classification
                     Number of trees: 500
No. of variables tried at each split: 2

        OOB estimate of  error rate: 5.71%
Confusion matrix:
           setosa versicolor virginica class.error
setosa         36          0         0  0.00000000
versicolor      0         29         3  0.09375000
virginica       0          3        34  0.08108108

モデル評価

テストデータを使ってモデル評価を行います。まずはテストデータを元に生成したモデルを用いて予測結果を算出します。

prediction <- predict(model.rf, df.test)

予測結果とテストデータのもともとのアヤメの分類とを比較します。おおむね正しく分類できていることが分かります。

(result <- table(prediction, df.test$Species))
            
prediction   setosa versicolor virginica
  setosa         14          0         0
  versicolor      0         17         0
  virginica       0          1        13
(accuracy_prediction <- sum(diag(result)) / sum(result))
[1] 0.9777778