background-image: url(img/portada.png) background-size: cover class: animated slideInRight fadeOutLeft, middle
# Regresión ### 1º Congreso Latinoamericano de Mujeres en Bioinformática y Ciencia de Datos --- ### Regresión La variable de respuesta `\(Y\)` es numérica. Por ejemplo: * Nivel salinidad marina. * Temperatura media. * Precio de una casa. * Salario mínimo. * Precio dólar blue. --- ## Nuestros pingüinos 🐧 ### Ingreso los datos ```r library(tidymodels) library(datos) dataset <- pinguinos %>% drop_na() %>% #elimino valores perdidos select(-anio,-sexo, -isla) #elimino columnas q no son numéricas glimpse(dataset) ``` ``` ## Rows: 333 ## Columns: 5 ## $ especie <fct> Adelia, Adelia, Adelia, Adelia, Adelia, Adelia, Adeli… ## $ largo_pico_mm <dbl> 39.1, 39.5, 40.3, 36.7, 39.3, 38.9, 39.2, 41.1, 38.6,… ## $ alto_pico_mm <dbl> 18.7, 17.4, 18.0, 19.3, 20.6, 17.8, 19.6, 17.6, 21.2,… ## $ largo_aleta_mm <int> 181, 186, 195, 193, 190, 181, 195, 182, 191, 198, 185… ## $ masa_corporal_g <int> 3750, 3800, 3250, 3450, 3650, 3625, 4675, 3200, 3800,… ``` --- ## Analizamos: Relación entre variables continuas: ancho y largo de pico ```r ggplot(dataset,aes(largo_pico_mm,alto_pico_mm)) + geom_point() ``` <img src="regresion_files/figure-html/unnamed-chunk-4-1.png" width="50%" /> ??? No observamos correlación --- ## Analizamos: La relación entre variables continuas: peso y largo de alas ```r ggplot(dataset,aes(largo_aleta_mm,masa_corporal_g)) + geom_point() ``` <img src="regresion_files/figure-html/unnamed-chunk-5-1.png" width="50%" /> --- ## Correlación Observamos una mayor correlación entre el peso y el largo de las alas. ```r cor(dataset$largo_aleta_mm,dataset$masa_corporal_g) ``` ``` ## [1] 0.8729789 ``` ```r cor(dataset$largo_aleta_mm,dataset$alto_pico_mm) ``` ``` ## [1] -0.5777917 ``` ```r cor(dataset$largo_pico_mm,dataset$masa_corporal_g) ``` ``` ## [1] 0.5894511 ``` --- background-image: url(img/penguin2.jpg) background-size: cover class: inverse, animated slideInRight fadeOutLeft, middle ### Pregunta - Hipótesis * ¿Es posible predecir el peso del pingüino a partir de la medición de la aleta? * ¿Es posible predecir el peso del pingüino a partir de otras mediciones? --- ## Vamos a dividir el set de datos ```r set.seed(123) # <- muy importante p_split <- dataset %>% initial_split(prop=0.75) p_train <- training(p_split) p_test <- testing(p_split) p_split ``` ``` ## <Analysis/Assess/Total> ## <250/83/333> ``` Estos son los datos de entrenamiento/prueba/total * __Vamos a _entrenar_ con 250 muestras__ * __Vamos a _validar_ con 83 muestras__ * __Datos totales: 333__ --- ## Modelos lineales * ¿Cuántos modelos lineales para regresión conoces? * ¿ O cuántas implementaciones de modelo lineal? Por ejemplo, librerías como: * lm * glm * stan * keras <img src="img/parsnip_allison.png" width="80%" style="display: block; margin: auto;" /> --- ## Modelo lineal lm ```r lm_spec <- linear_reg() %>% set_engine(engine = "lm") lm_spec ``` ``` ## Linear Regression Model Specification (regression) ## ## Computational engine: lm ``` --- ## Modelo lineal lm ```r set.seed(123) lm_fit <- lm_spec %>% fit(largo_aleta_mm ~ masa_corporal_g, data = p_train ) lm_fit ``` ``` ## parsnip model object ## ## Fit time: 14ms ## ## Call: ## stats::lm(formula = largo_aleta_mm ~ masa_corporal_g, data = data) ## ## Coefficients: ## (Intercept) masa_corporal_g ## 137.95557 0.01496 ``` --- ## Ejercicio 1 Chequea que el resultado anterior es igual a usar un modelo lm() ```r set.seed(123) lm(largo_aleta_mm ~ masa_corporal_g, data = p_train) ```
00
:
30
--- ## Ejercicio 1 - respuesta Chequea que el resultado anterior es igual a usar un modelo lm() ```r set.seed(123) lm(largo_aleta_mm ~ masa_corporal_g, data = p_train) ``` ``` ## ## Call: ## lm(formula = largo_aleta_mm ~ masa_corporal_g, data = p_train) ## ## Coefficients: ## (Intercept) masa_corporal_g ## 137.95557 0.01496 ``` --- ## Todo junto ```r set.seed(123) lm_fit <- linear_reg() %>% set_engine(engine = "lm") %>% fit(largo_aleta_mm ~ masa_corporal_g, data = p_train ) ``` --- ## Todo nuestro análisis ```r set.seed(100) # Importante p_split <- initial_split(dataset, prop=0.75) p_train <- training(p_split) p_test <- testing(p_split) lm_fit <- lm_spec %>% fit(masa_corporal_g ~ largo_aleta_mm, data = p_train) predicho <- lm_fit %>% predict(new_data = p_test) %>% mutate(verdadero = p_test$masa_corporal_g) rmse(predicho, truth = verdadero,estimate=.pred) ``` ``` ## # A tibble: 1 x 3 ## .metric .estimator .estimate ## <chr> <chr> <dbl> ## 1 rmse standard 366. ``` --- ## Root Mean Standard Error `\(RMSE = \sqrt{ \frac{1}{N}\sum_{i=1}^{N} ( y_{pred_i} - y_{i})^2}\)` ```r rmse(predicho, truth = verdadero,estimate=.pred) ``` ``` ## # A tibble: 1 x 3 ## .metric .estimator .estimate ## <chr> <chr> <dbl> ## 1 rmse standard 366. ``` ```r mae(predicho, truth = verdadero,estimate=.pred) ``` ``` ## # A tibble: 1 x 3 ## .metric .estimator .estimate ## <chr> <chr> <dbl> ## 1 mae standard 290. ``` `\(mae = (\frac{1}{n})\sum_{i=1}^{n}\left | y_{i} - x_{i} \right|\)` --- ### Graficando el modelo lineal <img src="regresion_files/figure-html/unnamed-chunk-16-1.png" width="70%" /> --- ## Ejercicio 2 ¿Podemos mejorar el desempeño del modelo agregando más variables? Modifica la fórmula de lm agregando las variables * largo_pico_mm * alto_pico_mm * largo_aleta_mm ¿Mejora el error (RMSE) ?
01
:
00
--- ## Ejercicio 2 - respuesta ```r set.seed(100) # Importante p_split <- initial_split(dataset, prop=0.75) p_train <- training(p_split) p_test <- testing(p_split) lm_fit_all <- lm_spec %>% fit(masa_corporal_g ~ largo_pico_mm +alto_pico_mm+largo_aleta_mm, data = p_train) peso_pred_all <- lm_fit_all %>% predict(new_data = p_test) %>% mutate(verdadero = p_test$masa_corporal_g) rmse(peso_pred_all, truth = verdadero,estimate=.pred) ``` ``` ## # A tibble: 1 x 3 ## .metric .estimator .estimate ## <chr> <chr> <dbl> ## 1 rmse standard 372. ``` --- ### Modelo lm para varias variables de entrada ```r lm_fit_all ``` ``` ## parsnip model object ## ## Fit time: 7ms ## ## Call: ## stats::lm(formula = masa_corporal_g ~ largo_pico_mm + alto_pico_mm + ## largo_aleta_mm, data = data) ## ## Coefficients: ## (Intercept) largo_pico_mm alto_pico_mm largo_aleta_mm ## -6700.908 2.089 31.021 51.180 ``` --- background-image: url(img/rf-fondo.png) background-size: cover ### Random Forest ```r rf_spec <- rand_forest(mode = "regression") %>% #<- set_engine("ranger") rf_spec ``` ``` ## Random Forest Model Specification (regression) ## ## Computational engine: ranger ``` --- background-image: url(img/rf-fondo.png) background-size: cover ### Random Forest ```r set.seed(123) rf_fit <- rf_spec %>% fit(masa_corporal_g ~ largo_pico_mm +alto_pico_mm + largo_aleta_mm, data = p_train) rf_fit ``` ``` ## parsnip model object ## ## Fit time: 233ms ## Ranger result ## ## Call: ## ranger::ranger(formula = masa_corporal_g ~ largo_pico_mm + alto_pico_mm + largo_aleta_mm, data = data, num.threads = 1, verbose = FALSE, seed = sample.int(10^5, 1)) ## ## Type: Regression ## Number of trees: 500 ## Sample size: 250 ## Number of independent variables: 3 ## Mtry: 1 ## Target node size: 5 ## Variable importance mode: none ## Splitrule: variance ## OOB prediction error (MSE): 125163.4 ## R squared (OOB): 0.8054198 ``` --- background-image: url(img/rf-fondo.png) background-size: cover ## Random forest ```r rf_fit %>% predict(new_data = p_test) %>% mutate(verdadero = p_test$masa_corporal_g) ``` ``` ## # A tibble: 83 x 2 ## .pred verdadero ## <dbl> <int> ## 1 3781. 3450 ## 2 3985. 4675 ## 3 3853. 3450 ## 4 3525. 3400 ## 5 3389. 3250 ## 6 4081. 4150 ## 7 4028. 3900 ## 8 3844. 3425 ## 9 4108. 4150 ## 10 3461. 3450 ## # … with 73 more rows ``` --- background-image: url(img/rf-fondo.png) background-size: cover ## Random forest ```r peso_pred_rf <- rf_fit %>% predict(new_data = p_test) %>% mutate(verdadero = p_test$masa_corporal_g) rmse(peso_pred_rf, truth = verdadero,estimate=.pred) ``` ``` ## # A tibble: 1 x 3 ## .metric .estimator .estimate ## <chr> <chr> <dbl> ## 1 rmse standard 321. ``` --- background-image: url(img/rf-fondo.png) background-size: cover ```r peso_pred_rf <- rf_fit %>% predict(new_data = p_test) %>% mutate(verdadero = p_test$masa_corporal_g) rmse(peso_pred_rf, truth = verdadero,estimate=.pred) ``` ``` ## # A tibble: 1 x 3 ## .metric .estimator .estimate ## <chr> <chr> <dbl> ## 1 rmse standard 321. ``` --- ## Comparando desempeño en el conjunto de entrenamiento ```r results_train <- lm_fit_all %>% predict(new_data = p_train) %>% mutate( verdadero = p_train$masa_corporal_g, model = "lm" ) %>% bind_rows(rf_fit %>% predict(new_data = p_train) %>% mutate( verdadero = p_train$masa_corporal_g, model = "rf" )) ``` --- ## Resultados conjunto entrenamiento ```r results_train %>% group_by(model) %>% rmse(truth = verdadero, estimate = .pred) ``` ``` ## # A tibble: 2 x 4 ## model .metric .estimator .estimate ## <chr> <chr> <chr> <dbl> ## 1 lm rmse standard 398. ## 2 rf rmse standard 185. ``` --- background-image: url(img/dt-fondo.png) background-size: cover ### Ejercicio 3 .bg-near-white.b--purple.ba.bw2.br3.shadow-5.ph4.mt5[ #### Compare el rendimiento de los modelos en el conjunto de datos de testeo. Copie y pegue el código anterior. Modifique lo necesario. ]
01
:
00
--- ## Comparando modelos en el testeo ```r results_test <- lm_fit_all %>% predict(new_data = p_test) %>% mutate( verdadero = p_test$masa_corporal_g, model = "lm" ) %>% bind_rows(rf_fit %>% predict(new_data = p_test) %>% mutate( verdadero = p_test$masa_corporal_g, model = "rf" )) ``` ```r results_test %>% group_by(model) %>% rmse(truth = verdadero, estimate = .pred) ``` ``` ## # A tibble: 2 x 4 ## model .metric .estimator .estimate ## <chr> <chr> <chr> <dbl> ## 1 lm rmse standard 372. ## 2 rf rmse standard 321. ``` --- ### FIN apartado :-) * Muchas gracias * Recreo