Capítulo 12 Random forest en R
# Carga el paquete específico del método Random Forest
library(randomForest)
# Carga de datos inicial, tipos de flores con diferentes caracter?sticas
data(iris)
# Selección de una submuestra del 70% de los datos
set.seed(456)
training_sample <- sample(c(TRUE, FALSE), nrow(iris), replace = T, prob = c(0.7,0.3))
train <- iris[training_sample, ]
test <- iris[!training_sample, ]
# Ajustar modelo
modelo <- randomForest(Species~., data=train)
# Resumen del ajuste del modelo
modelo##
## Call:
## randomForest(formula = Species ~ ., data = train)
## Type of random forest: classification
## Number of trees: 500
## No. of variables tried at each split: 2
##
## OOB estimate of error rate: 2.13%
## Confusion matrix:
## setosa versicolor virginica class.error
## setosa 31 0 0 0.00000000
## versicolor 0 34 1 0.02857143
## virginica 0 1 27 0.03571429
## MeanDecreaseGini
## Sepal.Length 4.547454
## Sepal.Width 2.383503
## Petal.Length 25.823796
## Petal.Width 29.080949
# Hacer predicciones
predicciones <- predict(modelo, test)
# Matriz de confusión
(mc <- with(test,table(predicciones, Species)))## Species
## predicciones setosa versicolor virginica
## setosa 19 0 0
## versicolor 0 13 3
## virginica 0 2 19
## [1] 91.07143
Referencias
\(\href{https://www.iartificial.net/random-forest-bosque-aleatorio/}{https://www.iartificial.net/random-forest-bosque-aleatorio/}\)
\(\href{https://www.aprendemachinelearning.com/random-forest-el-poder-del-ensamble/}{https://www.aprendemachinelearning.com/random-forest-el-poder-del-ensamble/}\)