Acorde a Becker y otros (2021), el paquete mlr3 provee un marco de trabajo genérico para varias tareas de aprendizaje automático, inluyendo problemas de clasificación, regresión, análisis de supervivencia y otro tipo de modelos para el lenguaje R. Contrario a librerías de python como scikit-learn, lo que hace este paquete es proveer una interfaz unificada para el entrenamiento, selección de variables, optimización de hiperparámetros y evaluación de modelos de aprendizaje automático que podemos encontrar en varias librerías de R. Para muchos de estos casos, la paralelización de procesos viene nativamente soportada.
Si bien mlr3 provee la funcionalidad base del framework, existen librerías que extienden los procesos disponibles, mejorando la creación de flujos de trabajo (pipelines), preprocesamiento, visualización, etc. Estos se pueden observar a continuación:
Finalmente, los creadores de esta librería mencionan que se siguen varios principios de diseño enlistados a continuación, con la finalidad de mantener uniformidad en el análisis de aprendizaje automático realizado con esta librería.
Se prioriza el backend sobre el frontend. Es decir que la gran mayoría de paquetes del ecosistema mlr3 se enfocan en el procesamiento y transformación de datos, estimación de modelos y comparación de resultados, por lo que su objetivo no es ofrecer una interfaz de usuario gráfica, apoyándose para ello de otras librerías como ggplot2.
Se utilizan objetos del tipo R6 con la finalidad de lograr un diseño limpio, orientado a objetos, cambiado su estado con cada ejecución que se realice. Los objetos R6 son internamente tratados como ambientes o environments.
Dado que librería se enfoca en el aprendizaje automático sobre datos coleccionados en memoria (y no en entornos distribuidos), utiliza la librería data.table para realizar la manipulación de datos de manera rápida y eficiente.
Unifica los objetos que se objetan como resultado en objetos data.tables, permitiendo operaciones rápidas de selección y agregación.
Utiliza programación defensiva y segura ante errores de tipeo, evitando simplificaciones dentro del código.
Es ligero en dependencias.
Una vez que hemos interiorizado estas definiciones, podemos comenzar el análisis de clasificación de noticias falsas en la siguiente subsección.
Con el uso de la librería mlr3, a continuación se indica el proceso general de modelamiento utilizado.
En esencia, la librería mlr3 encapsula a los datos de análisis en tasks o tareas. En cada tarea, divide a los datos en conjuntos de datos de entrenamiento y prueba. Dado que el objetivo del aprendizaje automático es construir un modelo que pueda ser extrapolado a nuevos conjuntos de datos, se utilizan los datos de entrenamiento para la estimación de algoritmos, mientras que los datos de prueba se utilizan para evaluar el desempeño de los modelos.
Una vez divididos los datos dentro de la tarea, se entregan los datos de entrenamiento a un learner, el cual es un algoritmo de aprendizaje automático. Este learner construye el modelo y puede ser usado para predecir o para evaluarse a través de distintas métricas.
Adicionalmente podemos aumentar etapas de preprocesamiento entre la etapa de división de los datos y entrenamiento del modelo, o aplicar técnicas de remuestreo para que nuestros modelos sean más robustos.
Sin más preámbulo, manos a la obra, y para ello, cargaremos la librería y los datos que hemos procesado anteriormente.
# Carga de librerías
library(mlr3)
library(mlr3viz)
library(mlr3pipelines)
library(mlr3verse)
library(mlr3tuning)
library(tidyverse)
library(ggpubr)
library(rpart.plot)
# Carga de datos
places_reviews_model_df = readRDS("Caso5_PrediccionRankingLugares/places_reviews_model_df.RDS")
Para comenzar el análisis, definamos una tarea que pueda ser ejecutada por el framework *mlr3*, eliminando las variables identificadores y de texto que no usaremos para predecir.
# Conversión de variable dependiente a factor y remoción de variables
places_reviews_task_df = places_reviews_model_df %>%
select(-comment_id, -text) %>%
mutate(relative_time_description = as.factor(relative_time_description))
# Creación de la tarea
task_places_reviews = TaskRegr$new(id = "rating_restaurantes",
backend = places_reviews_task_df,
target = "target_rating")
print(task_places_reviews)
<TaskRegr:rating_restaurantes> (1022 x 37)
* Target: target_rating
* Properties: -
* Features (36):
- int (20): n_palabras, n_palabras_ADJ, n_palabras_ADV, n_palabras_DET,
n_palabras_NOUN, n_palabras_PRON, n_palabras_PROPN, n_palabras_PUNCT,
n_palabras_VERB, n_palabras_unicas, n_palabras_unicas_ADJ, n_palabras_unicas_ADV,
n_palabras_unicas_DET, n_palabras_unicas_NOUN, n_palabras_unicas_PRON,
n_palabras_unicas_PROPN, n_palabras_unicas_PUNCT, n_palabras_unicas_VERB,
n_signos_admiracion, n_signos_interrogacion
- dbl (15): anger, anticipation, disgust, fear, joy, negative, pin_rtg_1, pin_rtg_2,
pin_rtg_3, pin_rtg_4, pin_rtg_5, positive, sadness, surprise, trust
- fct (1): relative_time_description
Una vez creada la tarea, podremos llamar a los datos que se incluyen en esta, y otros atributos, como se muestra a continuación.
# Datos
task_places_reviews$data()
# Variables explicativas
task_places_reviews$feature_names
[1] "anger" "anticipation" "disgust"
[4] "fear" "joy" "n_palabras"
[7] "n_palabras_ADJ" "n_palabras_ADV" "n_palabras_DET"
[10] "n_palabras_NOUN" "n_palabras_PRON" "n_palabras_PROPN"
[13] "n_palabras_PUNCT" "n_palabras_VERB" "n_palabras_unicas"
[16] "n_palabras_unicas_ADJ" "n_palabras_unicas_ADV" "n_palabras_unicas_DET"
[19] "n_palabras_unicas_NOUN" "n_palabras_unicas_PRON" "n_palabras_unicas_PROPN"
[22] "n_palabras_unicas_PUNCT" "n_palabras_unicas_VERB" "n_signos_admiracion"
[25] "n_signos_interrogacion" "negative" "pin_rtg_1"
[28] "pin_rtg_2" "pin_rtg_3" "pin_rtg_4"
[31] "pin_rtg_5" "positive" "relative_time_description"
[34] "sadness" "surprise" "trust"
Así también, gracias a la extensión mlr3viz podemos realizar varios tipos de visualizaciones para la tarea definida.
# Gráfico de la variable target
autoplot(task_places_reviews)
Una vez que la tarea ha sido definida, deberemos definir el algoritmo que vamos a usar. Para ello, existe en la página ml3learners una lista de los algoritmos que podemos utilizar, entre los cuales podemos encontrar (para llevar a cabo tareas de regresión):
| ID | Learner | Package |
|---|---|---|
| regr.cv_glmnet | Penalized Linear Regression | glmnet |
| regr.glmnet | Penalized Linear Regression | glmnet |
| regr.kknn | k-Nearest Neighbors | kknn |
| regr.km | Kriging | DiceKriging |
| regr.lm | Linear Regression | stats |
| regr.ranger | Random Forest | ranger |
| regr.svm | SVM | e1071 |
| regr.xgboost | Gradient Boosting | xgboost |
Cualquier de estos algoritmos será estimado en los datos de entrenamiento, es decir sobre un subconjunto de los datos analizados, para ser evaluado en los datos de prueba (o datos fuera de la muestra de entrenamiento), como se muestra en la siguiente imagen.
A través de las siguientes líneas de código también podemos observar los algoritmos existentes y sus hiperparámetros. Cabe notar que los hiperparámetros de un modelo son los valores de las configuraciones utilizadas por el algoritmo durante el proceso de entrenamiento, permitiendo su afinación. Específicamente, estos son valores que generalmente no se obtienen de los datos, por lo que tienen que ser especificados, y su valor óptimo tendrá que ser encontrado a través de métodos de pruba y error, uso de reglas o métodos de optimización de hiperparámetros, los cuales visitaremos más adelante.
# Lista de algoritmos de clasificación
regr_learners = mlr_learners$keys()[startsWith(mlr_learners$keys(),"regr")]
regr_learners
[1] "regr.cv_glmnet" "regr.featureless" "regr.glmnet" "regr.kknn"
[5] "regr.km" "regr.lm" "regr.ranger" "regr.rpart"
[9] "regr.svm" "regr.xgboost"
# Hiperparámetros
lrn("regr.rpart")$param_set$ids()
[1] "minsplit" "minbucket" "cp" "maxcompete" "maxsurrogate"
[6] "maxdepth" "usesurrogate" "surrogatestyle" "xval" "keep_model"
Ahora que conocemos cómo definir una tarea y un algoritmo, vamos a entrenar un modelo. Para ello, dividimos primero el conjunto de datos original en dos subconjuntos: entrenamiento y validación. Por lo general se suele tomar el 70% de los datos como muestra de entrenamiento, aunque este criterio dependerá de la situación y el analista.
# Definición de entrenamiento y validación
train_set = sample(task_places_reviews$nrow, 0.7 * task_places_reviews$nrow)
test_set = setdiff(seq_len(task_places_reviews$nrow), train_set)
cat("Dimensión en entrenamiento:",length(train_set),"\n")
Dimensión en entrenamiento: 715
cat("Dimensión en testing:",length(test_set),"\n")
Dimensión en testing: 307
Una vez divididos los datos, inicializamos y entrenamos el modelo (en este caso, un árbol de decisión) con los parámetros por defecto del algoritmo utilizado.
# Inicialización de learner
example_learner = lrn("regr.rpart")
# Entrenamiento
example_learner$train(task_places_reviews, row_ids = train_set)
# Resultados del modelo
rpart.plot(example_learner$model)
Cannot retrieve the data used to build the model (so cannot determine roundint and is.binary for the variables).
To silence this warning:
Call rpart.plot with roundint=FALSE,
or rebuild the rpart model with model=TRUE.
Luego de haber estimado el modelo en los datos de entrenamiento, podemos pasar a realizar las predicciones en el conjunto de datos de test y evaluar allí su rendimiento.
Para realizar la predicción no hace falta nada más que una línea de código.
# Predicción
prediction_rf = example_learner$predict(task_places_reviews, row_ids = test_set)
print(prediction_rf)
<PredictionRegr> for 307 observations:
Una vez que estas predicciones han sido hechas, revisemos su distribución con respecto al valor real de la variable objetivo.
# Gráfico de la predicción
autoplot(prediction_rf)
En este caso, el modelo no parece tener un buen desempeño, dado que tiene predice valores únicamente superiores a 2.75. Quizás el modelo es más util para determinar las variables que están teniendo efecto sobre el rating, mas no para predecir el rating. Sin embargo, evaluemos su desempeño y revisemos si podemos optimizar su predicción.
Para evaluar el desempeño de la regresión existen varias medidas que comparan el valor real contra el valor predicho. Sus fórmulas se puede observar a continuación.
Básicamente, estas medidas son calculadas a partir de los errores de predicción.
Estas medidas se pueden obtener a través del siguiente código.
# Medidas de evaluación
mlr_measures$keys()[startsWith(mlr_measures$keys(),"regr")]
[1] "regr.bias" "regr.ktau" "regr.mae" "regr.mape" "regr.maxae" "regr.medae" "regr.medse"
[8] "regr.mse" "regr.msle" "regr.pbias" "regr.rae" "regr.rmse" "regr.rmsle" "regr.rrse"
[15] "regr.rse" "regr.rsq" "regr.sae" "regr.smape" "regr.srho" "regr.sse"
# Medidas de desempeño
example_measure = list(msr("regr.mae", id = "MAE"),
msr("regr.mape", id = "MAPE"),
msr("regr.rmse", id = "RMSE"))
sapply(example_measure, function(x)prediction_rf$score(x))
MAE MAPE RMSE
0.5986841 0.2123880 0.8747713
En este caso nuestro modelo alcanza un error absoluto porcentual promedio de 21%. Veamos si podemos mejorarlo en la siguiente sección.
Pese a que los hiperparámetros de un modelo no son observados a primera vista durante la inicialización del modelo (en el ejercicio que acabamos de hacer no editamos ningún hiperparámetro), estos juega un rol crucial en el desempeño del algoritmo. Normalmente estos se suelen fijar al iniciar el entrenamiento, pero es posible seleccionar sus valores a través del entrenamiento de varios modelos que nos permitan comprobar el efecto que estos tienen sobre el desempeño del modelo. Para ello se ejecuta un procedimiento conocido como optimización o afinación de hiperparámetros. Este proceso se puede ver de manera gráfica a continuación.
Básicamente lo que hacemos es entrenar varios modelos para un conjunto de hiperparámetros definidos con anterioridad, para luego compararlos y escoger así sus valores ‘’óptimos’’. A continuación resolveremos el problema entre manos a través del uso de un algoritmo de árboles de clasificación, optimizando dos de sus hiperparámetros: el parámetro de complejidad (cp) y el número de observaciones mínimas exigidas en cada nodo (minsplit). Esto lo logramos a través del siguiente código.
# Inicialización del learner
optimizing_learner = lrn("regr.rpart")
# Definición del espacio de búsqueda
search_space = ps(cp = p_dbl(lower = 0.001, upper = 0.1),
minsplit = p_int(lower = 10, upper = 100))
search_space
<ParamSet>
Para ejecutar la afinación deberemos definir previamente tres parámetros:
Estos criterios se definen como se muestra a continuación.
# Método de evaluación
resamp_method = rsmp("cv", folds = 5)
measure_method = msr("regr.mae")
# Criterio de finalización
ending_method = trm("stagnation")
Una vez que tenemos estos parámetros definidos, crearemos la instancia de afinación con el siguiente código.
# Instancia de optimización
instance = TuningInstanceSingleCrit$new(task = task_places_reviews,
learner = optimizing_learner,
resampling = resamp_method,
measure = measure_method,
search_space = search_space,
terminator = ending_method)
instance
<TuningInstanceSingleCrit>
* State: Not optimized
* Objective: <ObjectiveTuning:regr.rpart_on_rating_restaurantes>
* Search Space:
<ParamSet>
* Terminator: <TerminatorStagnation>
* Terminated: FALSE
* Archive:
<ArchiveTuning>
Finalmente realizaremos el entrenamiento a través de uno de los siguientes métodos existentes dentro de la librería mlr3:
En este caso, lo haremos a través de búsqueda aleatoria.
# Método de búsqueda
tuner = tnr("random_search")
# Optimización
tuner$optimize(instance)
INFO [11:04:43.302] [bbotk] Starting to optimize 2 parameter(s) with '<OptimizerRandomSearch>' and '<TerminatorStagnation> [iters=10, threshold=0]'
INFO [11:04:43.334] [bbotk] Evaluating 1 configuration(s)
INFO [11:04:43.373] [mlr3] Running benchmark with 5 resampling iterations
INFO [11:04:43.402] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 4/5)
INFO [11:04:43.437] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 2/5)
INFO [11:04:43.464] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 5/5)
INFO [11:04:43.491] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 1/5)
INFO [11:04:43.519] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 3/5)
INFO [11:04:43.558] [mlr3] Finished benchmark
INFO [11:04:43.626] [bbotk] Result of batch 1:
INFO [11:04:43.650] [bbotk]
INFO [11:04:43.668] [bbotk] Evaluating 1 configuration(s)
INFO [11:04:43.705] [mlr3] Running benchmark with 5 resampling iterations
INFO [11:04:43.727] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 1/5)
INFO [11:04:43.756] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 3/5)
INFO [11:04:43.824] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 5/5)
INFO [11:04:43.901] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 2/5)
INFO [11:04:43.991] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 4/5)
INFO [11:04:44.068] [mlr3] Finished benchmark
INFO [11:04:44.207] [bbotk] Result of batch 2:
INFO [11:04:44.240] [bbotk]
INFO [11:04:44.264] [bbotk] Evaluating 1 configuration(s)
INFO [11:04:44.307] [mlr3] Running benchmark with 5 resampling iterations
INFO [11:04:44.336] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 4/5)
INFO [11:04:44.380] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 1/5)
INFO [11:04:44.954] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 5/5)
INFO [11:04:44.991] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 2/5)
INFO [11:04:45.031] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 3/5)
INFO [11:04:45.082] [mlr3] Finished benchmark
INFO [11:04:45.206] [bbotk] Result of batch 3:
INFO [11:04:45.253] [bbotk]
INFO [11:04:45.280] [bbotk] Evaluating 1 configuration(s)
INFO [11:04:45.335] [mlr3] Running benchmark with 5 resampling iterations
INFO [11:04:45.360] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 4/5)
INFO [11:04:45.392] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 3/5)
INFO [11:04:45.426] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 1/5)
INFO [11:04:45.466] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 2/5)
INFO [11:04:45.500] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 5/5)
INFO [11:04:45.539] [mlr3] Finished benchmark
INFO [11:04:45.632] [bbotk] Result of batch 4:
INFO [11:04:45.662] [bbotk]
INFO [11:04:45.685] [bbotk] Evaluating 1 configuration(s)
INFO [11:04:45.749] [mlr3] Running benchmark with 5 resampling iterations
INFO [11:04:45.785] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 5/5)
INFO [11:04:45.835] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 1/5)
INFO [11:04:45.884] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 3/5)
INFO [11:04:45.936] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 2/5)
INFO [11:04:45.979] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 4/5)
INFO [11:04:46.036] [mlr3] Finished benchmark
INFO [11:04:46.182] [bbotk] Result of batch 5:
INFO [11:04:46.223] [bbotk]
INFO [11:04:46.264] [bbotk] Evaluating 1 configuration(s)
INFO [11:04:46.330] [mlr3] Running benchmark with 5 resampling iterations
INFO [11:04:46.361] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 4/5)
INFO [11:04:46.420] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 1/5)
INFO [11:04:46.488] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 2/5)
INFO [11:04:46.536] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 5/5)
INFO [11:04:46.587] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 3/5)
INFO [11:04:46.648] [mlr3] Finished benchmark
INFO [11:04:46.754] [bbotk] Result of batch 6:
INFO [11:04:46.789] [bbotk]
INFO [11:04:46.814] [bbotk] Evaluating 1 configuration(s)
INFO [11:04:46.883] [mlr3] Running benchmark with 5 resampling iterations
INFO [11:04:46.919] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 2/5)
INFO [11:04:47.010] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 1/5)
INFO [11:04:47.053] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 4/5)
INFO [11:04:47.100] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 3/5)
INFO [11:04:47.146] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 5/5)
INFO [11:04:47.206] [mlr3] Finished benchmark
INFO [11:04:47.364] [bbotk] Result of batch 7:
INFO [11:04:47.418] [bbotk]
INFO [11:04:47.448] [bbotk] Evaluating 1 configuration(s)
INFO [11:04:47.519] [mlr3] Running benchmark with 5 resampling iterations
INFO [11:04:47.551] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 2/5)
INFO [11:04:47.599] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 3/5)
INFO [11:04:47.648] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 1/5)
INFO [11:04:47.713] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 5/5)
INFO [11:04:47.769] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 4/5)
INFO [11:04:47.826] [mlr3] Finished benchmark
INFO [11:04:47.929] [bbotk] Result of batch 8:
INFO [11:04:47.968] [bbotk]
INFO [11:04:47.999] [bbotk] Evaluating 1 configuration(s)
INFO [11:04:48.062] [mlr3] Running benchmark with 5 resampling iterations
INFO [11:04:48.088] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 1/5)
INFO [11:04:48.145] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 5/5)
INFO [11:04:48.195] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 3/5)
INFO [11:04:48.236] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 4/5)
INFO [11:04:48.283] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 2/5)
INFO [11:04:48.344] [mlr3] Finished benchmark
INFO [11:04:48.465] [bbotk] Result of batch 9:
INFO [11:04:48.500] [bbotk]
INFO [11:04:48.530] [bbotk] Evaluating 1 configuration(s)
INFO [11:04:48.589] [mlr3] Running benchmark with 5 resampling iterations
INFO [11:04:48.624] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 4/5)
INFO [11:04:48.671] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 1/5)
INFO [11:04:48.728] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 5/5)
INFO [11:04:48.805] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 3/5)
INFO [11:04:48.855] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 2/5)
INFO [11:04:48.920] [mlr3] Finished benchmark
INFO [11:04:49.063] [bbotk] Result of batch 10:
INFO [11:04:49.101] [bbotk]
INFO [11:04:49.137] [bbotk] Evaluating 1 configuration(s)
INFO [11:04:49.202] [mlr3] Running benchmark with 5 resampling iterations
INFO [11:04:49.241] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 4/5)
INFO [11:04:49.283] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 3/5)
INFO [11:04:49.335] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 2/5)
INFO [11:04:49.381] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 1/5)
INFO [11:04:49.433] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 5/5)
INFO [11:04:49.493] [mlr3] Finished benchmark
INFO [11:04:49.609] [bbotk] Result of batch 11:
INFO [11:04:49.641] [bbotk]
INFO [11:04:49.666] [bbotk] Evaluating 1 configuration(s)
INFO [11:04:49.725] [mlr3] Running benchmark with 5 resampling iterations
INFO [11:04:49.755] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 3/5)
INFO [11:04:49.800] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 5/5)
INFO [11:04:49.849] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 4/5)
INFO [11:04:49.894] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 1/5)
INFO [11:04:49.925] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 2/5)
INFO [11:04:49.969] [mlr3] Finished benchmark
INFO [11:04:50.076] [bbotk] Result of batch 12:
INFO [11:04:50.113] [bbotk]
INFO [11:04:50.148] [bbotk] Evaluating 1 configuration(s)
INFO [11:04:50.383] [mlr3] Running benchmark with 5 resampling iterations
INFO [11:04:50.441] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 2/5)
INFO [11:04:50.482] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 3/5)
INFO [11:04:50.520] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 1/5)
INFO [11:04:50.554] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 4/5)
INFO [11:04:50.581] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 5/5)
INFO [11:04:50.627] [mlr3] Finished benchmark
INFO [11:04:50.760] [bbotk] Result of batch 13:
INFO [11:04:50.801] [bbotk]
INFO [11:04:50.842] [bbotk] Evaluating 1 configuration(s)
INFO [11:04:50.899] [mlr3] Running benchmark with 5 resampling iterations
INFO [11:04:50.928] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 5/5)
INFO [11:04:51.037] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 1/5)
INFO [11:04:51.114] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 2/5)
INFO [11:04:51.154] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 4/5)
INFO [11:04:51.181] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 3/5)
INFO [11:04:51.220] [mlr3] Finished benchmark
INFO [11:04:51.319] [bbotk] Result of batch 14:
INFO [11:04:51.366] [bbotk]
INFO [11:04:51.399] [bbotk] Evaluating 1 configuration(s)
INFO [11:04:51.465] [mlr3] Running benchmark with 5 resampling iterations
INFO [11:04:51.500] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 5/5)
INFO [11:04:51.549] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 3/5)
INFO [11:04:51.603] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 4/5)
INFO [11:04:51.836] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 1/5)
INFO [11:04:51.960] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 2/5)
INFO [11:04:52.089] [mlr3] Finished benchmark
INFO [11:04:52.226] [bbotk] Result of batch 15:
INFO [11:04:52.260] [bbotk]
INFO [11:04:52.287] [bbotk] Evaluating 1 configuration(s)
INFO [11:04:52.338] [mlr3] Running benchmark with 5 resampling iterations
INFO [11:04:52.366] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 3/5)
INFO [11:04:52.402] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 5/5)
INFO [11:04:52.434] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 4/5)
INFO [11:04:52.467] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 1/5)
INFO [11:04:52.502] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 2/5)
INFO [11:04:52.551] [mlr3] Finished benchmark
INFO [11:04:52.636] [bbotk] Result of batch 16:
INFO [11:04:52.670] [bbotk]
INFO [11:04:52.698] [bbotk] Evaluating 1 configuration(s)
INFO [11:04:52.753] [mlr3] Running benchmark with 5 resampling iterations
INFO [11:04:52.785] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 1/5)
INFO [11:04:52.835] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 4/5)
INFO [11:04:52.911] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 2/5)
INFO [11:04:52.947] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 5/5)
INFO [11:04:52.983] [mlr3] Applying learner 'regr.rpart' on task 'rating_restaurantes' (iter 3/5)
INFO [11:04:53.033] [mlr3] Finished benchmark
INFO [11:04:53.168] [bbotk] Result of batch 17:
INFO [11:04:53.206] [bbotk]
INFO [11:04:53.247] [bbotk] Finished optimizing after 17 evaluation(s)
INFO [11:04:53.265] [bbotk] Result:
INFO [11:04:53.309] [bbotk]
Una vez estimado la afinación, podremos ver sus resultados óptimos con el código que sigue.
# Resultado de la optimización
instance$result
Con tales resultados, realizamos la reestimación del modelo y observamos sus resultados.
# Inicialización de learner
final_learner = lrn("regr.rpart", cp = instance$result$cp,
minsplit = instance$result$minsplit)
# Entrenamiento
final_learner$train(task_places_reviews, row_ids = train_set)
# Resultados del modelo
rpart.plot(final_learner$model)
Cannot retrieve the data used to build the model (so cannot determine roundint and is.binary for the variables).
To silence this warning:
Call rpart.plot with roundint=FALSE,
or rebuild the rpart model with model=TRUE.
A la par, evaluamos su desempeño:
# Predicción
prediction_fn = final_learner$predict(task_places_reviews, row_ids = test_set)
final_measure = list(msr("regr.mae", id = "MAE"),
msr("regr.mape", id = "MAPE"),
msr("regr.rmse", id = "RMSE"))
sapply(final_measure, function(x)prediction_fn$score(x))
MAE MAPE RMSE
0.5618156 0.2056518 0.8400972
Con esta optimización hemos mejorado nuestro modelo, reduciendo el error absoluto porcentual en un 1%. En este punto quizás sea prudente comparar una gama más extensa de opciones a través del benchmarking de modelos.