R - 決策樹



決策樹是一種以樹的形式表示選擇及其結果的圖形。圖中的節點表示事件或選擇,圖的邊表示決策規則或條件。它主要用於使用 R 的機器學習和資料探勘應用中。

決策樹的應用示例包括:預測電子郵件是否為垃圾郵件,預測腫瘤是否為癌性,或根據每個因素預測貸款是否為良好的信用風險。通常,模型是使用觀察到的資料(也稱為訓練資料)建立的。然後使用一組驗證資料來驗證和改進模型。R 具有用於建立和視覺化決策樹的包。對於新的預測變數集,我們使用此模型來確定資料的類別(是/否、垃圾郵件/非垃圾郵件)。

R 包“**party**”用於建立決策樹。

安裝 R 包

在 R 控制檯中使用以下命令安裝包。如果存在任何依賴包,您也需要安裝它們。

install.packages("party")

包“party”具有函式**ctree()**,用於建立和分析決策樹。

語法

在 R 中建立決策樹的基本語法如下:

ctree(formula, data)

以下是所用引數的說明:

  • **formula** 是一個描述預測變數和響應變數的公式。

  • **data** 是所用資料集的名稱。

輸入資料

我們將使用名為**readingSkills** 的 R 內建資料集來建立決策樹。如果我們知道“年齡”、“鞋碼”、“分數”以及該人是否是母語人士,它描述了某人閱讀技能的分數。

以下是示例資料。

# Load the party package. It will automatically load other
# dependent 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
...............................
...............................

示例

我們將使用**ctree()**函式來建立決策樹並檢視其圖形。

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

# Create the input data frame.
input.dat <- readingSkills[c(1:105),]

# Give the chart file a name.
png(file = "decision_tree.png")

# Create the tree.
  output.tree <- ctree(
  nativeSpeaker ~ age + shoeSize + score, 
  data = input.dat)

# Plot the tree.
plot(output.tree)

# Save the file.
dev.off()

當我們執行以上程式碼時,它會生成以下結果:

null device 
          1 
Loading required package: methods
Loading required package: grid
Loading required package: mvtnorm
Loading required package: modeltools
Loading required package: stats4
Loading required package: strucchange
Loading required package: zoo

Attaching package: ‘zoo’

The following objects are masked from ‘package:base’:

   as.Date, as.Date.numeric

Loading required package: sandwich
Decision Tree using R

結論

從上面顯示的決策樹中,我們可以得出結論,任何閱讀技能得分低於 38.3 且年齡大於 6 的人都不是母語人士。

廣告