Vamos a trabajar con árboles de decisión y bosques aleatorios para la toma de decisiones. Usaremos el dataframe kyphosis que viene en el paquete rpart.
library(rpart)
library(rpart.plot)
df <- kyphosis
head(df)
## Kyphosis Age Number Start
## 1 absent 71 3 5
## 2 absent 158 3 14
## 3 present 128 4 5
## 4 absent 2 5 1
## 5 absent 1 4 15
## 6 absent 1 2 16
El dataframe está relacionado con la cifosis, que es una curvatura de la columna vertebral.
La primera columna indica si el paciente presenta o no cifosis. La segunda es la edad en meses, la tercera el número de vértebras implicadas en la cifosis y la última indica cuál es la vértebra más alta que fue intervenida quirúrgicamente.
model <- rpart(Kyphosis~., method='class', data=df)
printcp(model)
##
## Classification tree:
## rpart(formula = Kyphosis ~ ., data = df, method = "class")
##
## Variables actually used in tree construction:
## [1] Age Start
##
## Root node error: 17/81 = 0.20988
##
## n= 81
##
## CP nsplit rel error xerror xstd
## 1 0.176471 0 1.00000 1.0000 0.21559
## 2 0.019608 1 0.82353 1.0588 0.22010
## 3 0.010000 4 0.76471 1.1176 0.22433
plot(model, uniform=T, main='Kyphosis Tree')
text(model, use.n = T, all=T)
Usamos la función prp del paquete rpart.plot para pintar el árbol de una manera más sencilla.
prp(model)
A continuación vamos a usar los bosques aleatorios pues es un algoritmo más potente de clasificación.
library(randomForest)
## randomForest 4.6-14
## Type rfNews() to see new features/changes/bug fixes.
rf.model <- randomForest(Kyphosis~., data=kyphosis)
print(rf.model)
##
## Call:
## randomForest(formula = Kyphosis ~ ., data = kyphosis)
## Type of random forest: classification
## Number of trees: 500
## No. of variables tried at each split: 1
##
## OOB estimate of error rate: 22.22%
## Confusion matrix:
## absent present class.error
## absent 59 5 0.0781250
## present 13 4 0.7647059
Como podemos observar, ha usado 500 árboles para el modelo.
rf.model$predicted
## 1 2 3 4 5 6 7 8 9
## present absent absent absent absent absent absent absent absent
## 10 11 12 13 14 15 16 17 18
## absent absent absent absent absent absent absent absent absent
## 19 20 21 22 23 24 25 26 27
## absent absent absent present absent present absent absent absent
## 28 29 30 31 32 33 34 35 36
## absent absent absent absent absent absent absent absent absent
## 37 38 39 40 41 42 43 44 45
## absent absent absent absent absent absent present absent absent
## 46 47 48 49 50 51 52 53 54
## absent absent absent absent absent absent absent absent absent
## 55 56 57 58 59 60 61 62 63
## absent absent absent present present absent absent present present
## 64 65 66 67 68 69 70 71 72
## absent absent absent absent absent absent absent absent absent
## 73 74 75 76 77 78 79 80 81
## absent absent absent absent absent absent absent present absent
## Levels: absent present