Objetivo

Crear y evaluar un modelo de árbol de regresión para predecir Sales a partir de TV, Radio, News y Web

Descripción

Fundamento teórico

Los algoritmos de aprendizaje basados en árbol se consideran uno de los mejores y más utilizados métodos de aprendizaje supervisado.

Potencian modelos predictivos con alta precisión, estabilidad y facilidad de interpretación.

Los árboles de clasificación y regresión son métodos que proporcionan modelos que satisfacen objetivos tanto predictivos como explicativos.

Algunas ventajas son su sencillez y la representación gráfica mediante árboles y, por otro, la definición de reglas de asociación entre variables que incluye expresiones de condición que permiten explicar las predicciones.

Se pueden usar para regresiones con variables dependientes que tienen valores numéricos continuos o para clasificaciones con variables categóricas.

Utilizar un árbol de regresión para crear un modelo explicativo y predictivo para una variable cuantitativa dependiente basada en variables explicativas independientes cuantitativas y cualitativas (XLSTAT by Addinsoft, n.d.)

Un árbol de regresión consiste en hacer preguntas de tipo\(¿x_k < c?\) para cada una de las covariables, de esta forma el espacio de las covariables es divido en hiper-rectángulos (con el resultado de las condicionales) de las observaciones que queden dentro de un hiper-rectángulo tendrán el mismo valor estimado \(\hat{y}\) o \(Y\) (Hernández 2021).

Por otra parte, bajo el paradigma divide y vencerás, usando árboles de regresión y decisión y correspondientes reglas, el árbol representa el modelo similar a un diagrama de flujo en el que los nodos de decisión, los nodos de hoja y las ramas definen una serie de decisiones que se pueden usar para generar predicciones. Siguiendo las reglas se encuentran predicciones en la hoja final. (Lantz 2013).

Desarrollo

Cargar librerías

library(dplyr)
library(ggplot2)
# library(plotly) # no se está usando
library(knitr)
library(PerformanceAnalytics) # Para coorelaciones gráficas
library(caret)  # Para particionar
library(Metrics) # Para determinar rmse
library(PerformanceAnalytics) # Para
library(rpart)       # arboles
library(rpart.plot)  # arboles visuales

library(PerformanceAnalytics) # Para cor grafica

Cargar datos

datos <- read.csv("https://raw.githubusercontent.com/rpizarrog/Machine-Learning-con-R/main/datos/Advertising_Web.csv")

Explorar datos

str(datos)
## 'data.frame':    200 obs. of  7 variables:
##  $ X.1      : int  1 2 3 4 5 6 7 8 9 10 ...
##  $ X        : int  1 2 3 4 5 6 7 8 9 10 ...
##  $ TV       : num  230.1 44.5 17.2 151.5 180.8 ...
##  $ Radio    : num  37.8 39.3 45.9 41.3 10.8 48.9 32.8 19.6 2.1 2.6 ...
##  $ Newspaper: num  69.2 45.1 69.3 58.5 58.4 75 23.5 11.6 1 21.2 ...
##  $ Web      : num  306.6 302.7 49.5 257.8 195.7 ...
##  $ Sales    : num  22.1 10.4 9.3 18.5 12.9 7.2 11.8 13.2 4.8 10.6 ...
summary(datos)
##       X.1               X                TV             Radio       
##  Min.   :  1.00   Min.   :  1.00   Min.   :  0.70   Min.   : 0.000  
##  1st Qu.: 50.75   1st Qu.: 50.75   1st Qu.: 74.38   1st Qu.: 9.975  
##  Median :100.50   Median :100.50   Median :149.75   Median :22.900  
##  Mean   :100.50   Mean   :100.50   Mean   :147.04   Mean   :23.264  
##  3rd Qu.:150.25   3rd Qu.:150.25   3rd Qu.:218.82   3rd Qu.:36.525  
##  Max.   :200.00   Max.   :200.00   Max.   :296.40   Max.   :49.600  
##    Newspaper           Web              Sales      
##  Min.   :  0.30   Min.   :  4.308   Min.   : 1.60  
##  1st Qu.: 12.75   1st Qu.: 99.049   1st Qu.:10.38  
##  Median : 25.75   Median :156.862   Median :12.90  
##  Mean   : 30.55   Mean   :159.587   Mean   :14.02  
##  3rd Qu.: 45.10   3rd Qu.:212.312   3rd Qu.:17.40  
##  Max.   :114.00   Max.   :358.247   Max.   :27.00

Limpiar datos

Quitar las primeras columnas

datos <- select(datos, TV, Radio, Newspaper, Web, Sales)

Correlaciones lineal entre variables

cor(datos)
##                   TV       Radio   Newspaper         Web      Sales
## TV        1.00000000  0.05480866  0.05664787  0.01257597 0.78222442
## Radio     0.05480866  1.00000000  0.35410375 -0.12267338 0.57622257
## Newspaper 0.05664787  0.35410375  1.00000000 -0.05775877 0.22829903
## Web       0.01257597 -0.12267338 -0.05775877  1.00000000 0.00210779
## Sales     0.78222442  0.57622257  0.22829903  0.00210779 1.00000000
chart.Correlation(datos)

Las variables de interés

  • x’s las variable independientes o predictoras son TV, Radio, Newspaper y Web
  • y la variable dependiente o resultado (Sales), es decir y depende de x’s.

Limpiar datos

En caso necesario. No se observan datos extraños …. porque son pocos.

Partir datos

Aleatoriamente se reparten las observaciones con el 70% para datos de entrenamiento y el 30% para datos de validación.

Sembrar una semilla con set.seed()

set.seed(2022)
n <- nrow(datos)  # cantidad de observaciones
entrena <- createDataPartition(y = datos$Sales, p = 0.70, list = FALSE, times = 1)

# Datos entrenamiento
datos.entrenamiento <- datos[entrena, ]  # [renglones, columna]

# Datos validación
datos.validacion <- datos[-entrena, ]

Datos de entrenamiento

datos.entrenamiento
##        TV Radio Newspaper        Web Sales
## 1   230.1  37.8      69.2 306.634752  22.1
## 2    44.5  39.3      45.1 302.653070  10.4
## 3    17.2  45.9      69.3  49.498908   9.3
## 4   151.5  41.3      58.5 257.816893  18.5
## 5   180.8  10.8      58.4 195.660076  12.9
## 6     8.7  48.9      75.0  22.072395   7.2
## 7    57.5  32.8      23.5 246.811598  11.8
## 8   120.2  19.6      11.6 229.971459  13.2
## 9     8.6   2.1       1.0 144.617385   4.8
## 11   66.1   5.8      24.2  45.359029   8.6
## 12  214.7  24.0       4.0 164.971764  17.4
## 13   23.8  35.1      65.9  87.921085   9.2
## 14   97.5   7.6       7.2 173.658035   9.7
## 15  204.1  32.9      46.0 245.774960  19.0
## 16  195.4  47.7      52.9 148.095134  22.4
## 17   67.8  36.6     114.0 202.638903  12.5
## 18  281.4  39.6      55.8  41.755313  24.4
## 19   69.2  20.5      18.3 210.489910  11.3
## 23   13.2  15.9      49.6 219.882776   5.6
## 25   62.3  12.6      18.3 256.965240   9.7
## 28  240.1  16.7      22.9 228.157437  15.9
## 29  248.8  27.1      22.9 318.644967  18.9
## 32  112.9  17.4      38.6 295.883989  11.9
## 37  266.9  43.8       5.0  96.316829  25.4
## 38   74.7  49.4      45.7  56.536223  14.7
## 39   43.1  26.7      35.1 122.753591  10.1
## 40  228.0  37.7      32.0 196.483269  21.5
## 41  202.5  22.3      31.6  88.212823  16.6
## 43  293.6  27.7       1.8 174.716820  20.7
## 44  206.9   8.4      26.4 213.609610  12.9
## 45   25.1  25.7      43.3 245.764410   8.5
## 46  175.1  22.5      31.5  62.809264  14.9
## 47   89.7   9.9      35.7 216.504015  10.6
## 49  227.2  15.8      49.9  75.269182  14.8
## 51  199.8   3.1      34.6 151.990733  11.4
## 52  100.4   9.6       3.6  41.335255  10.7
## 53  216.4  41.7      39.6 161.802512  22.6
## 56  198.9  49.4      60.0 204.418927  23.7
## 57    7.3  28.1      41.4 121.328525   5.5
## 58  136.2  19.2      16.6  60.454355  13.2
## 59  210.8  49.6      37.7  32.411740  23.8
## 61   53.5   2.0      21.4  39.217153   8.1
## 62  261.3  42.7      54.7 224.832039  24.2
## 64  102.7  29.6       8.4 183.009750  14.0
## 65  131.1  42.8      28.9 124.382228  18.0
## 68  139.3  14.5      10.2 207.661990  13.4
## 70  216.8  43.9      27.2 149.396103  22.3
## 71  199.1  30.6      38.7 210.752142  18.3
## 72  109.8  14.3      31.7 151.990733  12.4
## 73   26.8  33.0      19.3 211.990907   8.8
## 74  129.4   5.7      31.3  61.306191  11.0
## 75  213.4  24.6      13.1 156.284261  17.0
## 77   27.5   1.6      20.7 117.101925   6.9
## 78  120.5  28.5      14.2  97.455125  14.2
## 79    5.4  29.9       9.4   4.308085   5.3
## 80  116.0   7.7      23.1 120.053504  11.0
## 81   76.4  26.7      22.3 268.151320  11.8
## 82  239.8   4.1      36.9 169.946395  12.3
## 85  213.5  43.0      33.8 191.868374  21.7
## 86  193.2  18.4      65.7 223.578793  15.2
## 88  110.7  40.6      63.2 107.430521  16.0
## 89   88.3  25.5      73.4 260.101928  12.9
## 91  134.3   4.9       9.3 258.355488  11.2
## 92   28.6   1.5      33.0 172.467947   7.3
## 94  250.9  36.5      72.3 202.102158  22.2
## 96  163.3  31.6      52.9 155.594877  16.9
## 97  197.6   3.5       5.9 139.830544  11.7
## 98  184.9  21.0      22.0 253.300721  15.5
## 99  289.7  42.3      51.2 183.569585  25.4
## 100 135.2  41.7      45.9  40.600350  17.2
## 102 296.4  36.3     100.9  61.005251  23.8
## 103 280.2  10.1      21.4  49.808451  14.8
## 105 238.2  34.3       5.3 112.155489  20.7
## 106 137.9  46.4      59.0 138.762632  19.2
## 108  90.4   0.3      23.2 261.380879   8.7
## 110 255.4  26.9       5.5 273.454125  19.8
## 113 175.7  15.4       2.4  71.682551  14.1
## 115  78.2  46.8      34.5  76.770428  14.6
## 117 139.2  14.3      25.6 234.183118  12.2
## 119 125.7  36.9      79.2 187.840415  15.9
## 121 141.3  26.8      46.2  65.525461  15.5
## 122  18.8  21.7      50.4  63.854924   7.0
## 123 224.0   2.4      15.6  89.515821  11.6
## 124 123.1  34.6      12.4  15.757191  15.2
## 126  87.2  11.8      25.9 121.090982  10.6
## 127   7.8  38.9      50.6 209.471977   6.6
## 129 220.3  49.0       3.2 187.437060  24.7
## 131   0.7  39.6       8.7 162.902591   1.6
## 132 265.2   2.9      43.0 172.156659  12.7
## 134 219.8  33.5      45.1 171.478018  19.6
## 135  36.9  38.6      65.6  81.246748  10.8
## 136  48.3  47.0       8.5  61.227323  11.6
## 137  25.6  39.0       9.3  77.230797   9.5
## 138 273.7  28.9      59.7 288.260611  20.8
## 141  73.4  17.0      12.9 174.772137  10.9
## 142 193.7  35.4      75.6 152.284937  19.2
## 143 220.5  33.2      37.9   6.007436  20.1
## 145  96.2  14.8      38.9 157.440047  11.4
## 146 140.3   1.9       9.0 231.883385  10.3
## 147 240.1   7.3       8.7  23.496943  13.2
## 148 243.2  49.0      44.3 151.990733  25.4
## 150  44.7  25.8      20.6 235.622449  10.1
## 152 121.0   8.4      48.7 103.255212  11.6
## 154 171.3  39.7      37.7 155.016224  19.0
## 155 187.8  21.1       9.5  63.071208  15.6
## 156   4.1  11.6       5.7 113.270712   3.2
## 157  93.9  43.5      50.5  74.361939  15.3
## 158 149.8   1.3      24.3 145.803211  10.1
## 159  11.7  36.9      45.2 185.866079   7.3
## 160 131.7  18.4      34.6 196.370304  12.9
## 161 172.5  18.1      30.7 207.496801  14.4
## 162  85.7  35.8      49.3 188.933530  13.3
## 163 188.4  18.1      25.6 158.461520  14.9
## 164 163.5  36.8       7.4  82.228794  18.0
## 165 117.2  14.7       5.4 109.008763  11.9
## 166 234.5   3.4      84.8 135.024909  11.9
## 167  17.9  37.6      21.6  99.936953   8.0
## 168 206.8   5.2      19.4 115.371957  12.2
## 169 215.4  23.6      57.6 203.431267  17.1
## 170 284.3  10.6       6.4 157.900110  15.0
## 173  19.6  20.1      17.0 155.583662   7.6
## 174 168.4   7.1      12.8 218.180829  11.7
## 175 222.4   3.4      13.1 144.525662  11.5
## 176 276.9  48.9      41.8 151.990733  27.0
## 179 276.7   2.3      23.7 137.323772  11.8
## 180 165.6  10.0      17.6 151.990733  12.6
## 181 156.6   2.6       8.3 122.116470  10.5
## 183  56.2   5.7      29.7  42.199287   8.7
## 184 287.6  43.0      71.8 154.309725  26.2
## 185 253.8  21.3      30.0 181.579051  17.6
## 186 205.0  45.1      19.6 208.692690  22.6
## 187 139.5   2.1      26.6 236.744035  10.3
## 188 191.1  28.7      18.2 239.275713  17.3
## 189 286.0  13.9       3.7 151.990733  15.9
## 190  18.7  12.1      23.4 222.906951   6.7
## 192  75.5  10.8       6.0 301.481194   9.9
## 193  17.2   4.1      31.6 265.028644   5.9
## 195 149.7  35.6       6.0  99.579981  17.3
## 196  38.2   3.7      13.8 248.841073   7.6
## 197  94.2   4.9       8.1 118.041856   9.7
## 198 177.0   9.3       6.4 213.274671  12.8
## 200 232.1   8.6       8.7 151.990733  13.4

Datos de validación

datos.validacion
##        TV Radio Newspaper       Web Sales
## 10  199.8   2.6      21.2 111.27226  10.6
## 20  147.3  23.9      19.1 268.73538  14.6
## 21  218.4  27.7      53.4  59.96055  18.0
## 22  237.4   5.1      23.5 296.95207  12.5
## 24  228.3  16.9      26.2  51.17007  15.5
## 26  262.9   3.5      19.5 160.56286  12.0
## 27  142.9  29.3      12.6 275.51248  15.0
## 30   70.6  16.0      40.8  61.32436  10.5
## 31  292.9  28.3      43.2 121.46435  21.4
## 33   97.2   1.5      30.0 139.78109   9.6
## 34  265.6  20.0       0.3  94.20726  17.4
## 35   95.7   1.4       7.4 321.17461   9.5
## 36  290.7   4.1       8.5 181.98342  12.8
## 42  177.0  33.4      38.7 147.85932  17.1
## 48  239.9  41.5      18.5 105.96291  23.2
## 50   66.9  11.7      36.8 205.25350   9.7
## 54  182.6  46.2      58.7 176.05005  21.2
## 55  262.7  28.8      15.9 324.61518  20.2
## 60  210.7  29.5       9.3 138.89555  18.4
## 63  239.3  15.5      27.3 312.20956  15.7
## 66   69.0   9.3       0.9 205.99349   9.3
## 67   31.5  24.6       2.2 216.47140   9.5
## 69  237.4  27.5      11.0 291.54860  18.9
## 76   16.9  43.7      89.4  70.23428   8.7
## 83   75.3  20.3      32.5 231.20983  11.3
## 84   68.4  44.5      35.6  78.39310  13.6
## 87   76.3  27.5      16.0 193.83089  12.0
## 90  109.8  47.8      51.4 162.72789  16.7
## 93  217.7  33.5      59.0 150.96275  19.4
## 95  107.4  14.0      10.9 151.99073  11.5
## 101 222.4   4.3      49.8 125.62714  11.7
## 104 187.9  17.2      17.9  97.08863  14.7
## 107  25.0  11.0      29.7  15.93821   7.2
## 109  13.1   0.4      25.6 252.39135   5.3
## 111 225.8   8.2      56.5  95.18576  13.4
## 112 241.7  38.0      23.2 180.51153  21.8
## 114 209.6  20.6      10.7  42.88380  15.9
## 116  75.1  35.0      52.7 204.27671  12.6
## 118  76.4   0.8      14.8 234.38450   9.4
## 120  19.4  16.0      22.3 112.89261   6.6
## 125 229.5  32.3      74.2  88.08072  19.7
## 128  80.2   0.0       9.2 358.24704   8.8
## 130  59.6  12.0      43.1 197.19655   9.7
## 133   8.4  27.2       2.1 238.05522   5.7
## 139  43.0  25.9      20.5 181.36874   9.6
## 140 184.9  43.9       1.7 106.25383  20.7
## 144 104.6   5.7      34.4 336.57109  10.4
## 149  38.0  40.3      11.9  75.20798  10.9
## 151 280.7  13.9      37.0  81.04062  16.1
## 153 197.6  23.3      14.2 159.52256  16.6
## 171  50.0  11.6      18.4  64.01480   8.4
## 172 164.5  20.9      47.4  96.18039  14.5
## 177 248.4  30.2      20.3 163.85204  20.2
## 178 170.2   7.8      35.2 104.91734  11.7
## 182 218.5   5.4      27.4 162.38749  12.2
## 191  39.5  41.1       5.8 219.89058  10.8
## 194 166.8  42.0       3.6 192.24621  19.6
## 199 283.6  42.0      66.2 237.49806  25.5

Construir el modelo

El modelo se construye con datos de entrenamiento

Arbol de Regresión con variables numéricas

modelo_ar <- rpart(data = datos.entrenamiento, formula = Sales ~ TV + Radio + Newspaper + Web)
summary(modelo_ar)
## Call:
## rpart(formula = Sales ~ TV + Radio + Newspaper + Web, data = datos.entrenamiento)
##   n= 142 
## 
##           CP nsplit  rel error    xerror       xstd
## 1 0.45089318      0 1.00000000 1.0132336 0.10752048
## 2 0.28830145      1 0.54910682 0.7169968 0.06569588
## 3 0.07068285      2 0.26080537 0.3808481 0.04645636
## 4 0.04765527      3 0.19012252 0.2664784 0.02717328
## 5 0.02923525      4 0.14246725 0.2326955 0.02375388
## 6 0.02362595      5 0.11323200 0.2270240 0.02334504
## 7 0.01687223      6 0.08960605 0.1772675 0.01984244
## 8 0.01000000      7 0.07273382 0.1472676 0.01638832
## 
## Variable importance
##        TV     Radio Newspaper       Web 
##        50        30        12         7 
## 
## Node number 1: 142 observations,    complexity param=0.4508932
##   mean=14.07746, MSE=28.99837 
##   left son=2 (58 obs) right son=3 (84 obs)
##   Primary splits:
##       TV        < 122.05   to the left,  improve=0.45089320, (0 missing)
##       Radio     < 39.65    to the left,  improve=0.26412030, (0 missing)
##       Newspaper < 50.9     to the left,  improve=0.10078500, (0 missing)
##       Web       < 146.9492 to the left,  improve=0.02925809, (0 missing)
##   Surrogate splits:
##       Web   < 121.7225 to the left,  agree=0.620, adj=0.069, (0 split)
##       Radio < 1.75     to the left,  agree=0.606, adj=0.034, (0 split)
## 
## Node number 2: 58 observations,    complexity param=0.07068285
##   mean=9.725862, MSE=8.967779 
##   left son=4 (21 obs) right son=5 (37 obs)
##   Primary splits:
##       TV        < 32.75    to the left,  improve=0.55958110, (0 missing)
##       Radio     < 40.1     to the left,  improve=0.13279470, (0 missing)
##       Newspaper < 31.65    to the left,  improve=0.04804439, (0 missing)
##       Web       < 111.1397 to the right, improve=0.04639805, (0 missing)
##   Surrogate splits:
##       Web       < 30.64477 to the left,  agree=0.672, adj=0.095, (0 split)
##       Radio     < 1.8      to the left,  agree=0.655, adj=0.048, (0 split)
##       Newspaper < 49.45    to the right, agree=0.655, adj=0.048, (0 split)
## 
## Node number 3: 84 observations,    complexity param=0.2883014
##   mean=17.08214, MSE=20.72575 
##   left son=6 (44 obs) right son=7 (40 obs)
##   Primary splits:
##       Radio     < 26.85    to the left,  improve=0.68189750, (0 missing)
##       Newspaper < 37.3     to the left,  improve=0.23680930, (0 missing)
##       TV        < 193.45   to the left,  improve=0.21208540, (0 missing)
##       Web       < 146.9492 to the left,  improve=0.03517137, (0 missing)
##   Surrogate splits:
##       Newspaper < 37.3     to the left,  agree=0.738, adj=0.450, (0 split)
##       TV        < 189.75   to the left,  agree=0.607, adj=0.175, (0 split)
##       Web       < 238.0099 to the left,  agree=0.583, adj=0.125, (0 split)
## 
## Node number 4: 21 observations
##   mean=6.752381, MSE=3.770113 
## 
## Node number 5: 37 observations,    complexity param=0.01687223
##   mean=11.41351, MSE=4.051439 
##   left son=10 (14 obs) right son=11 (23 obs)
##   Primary splits:
##       Radio     < 13.45    to the left,  improve=0.46347170, (0 missing)
##       TV        < 66.95    to the left,  improve=0.28113440, (0 missing)
##       Newspaper < 45.4     to the left,  improve=0.26532060, (0 missing)
##       Web       < 232.797  to the right, improve=0.07966511, (0 missing)
##   Surrogate splits:
##       Web       < 50.94763 to the left,  agree=0.730, adj=0.286, (0 split)
##       Newspaper < 8.25     to the left,  agree=0.703, adj=0.214, (0 split)
## 
## Node number 6: 44 observations,    complexity param=0.02923525
##   mean=13.49773, MSE=4.294313 
##   left son=12 (21 obs) right son=13 (23 obs)
##   Primary splits:
##       Radio     < 10.05    to the left,  improve=0.63712160, (0 missing)
##       TV        < 170.45   to the left,  improve=0.24450570, (0 missing)
##       Web       < 88.86432 to the right, improve=0.05211131, (0 missing)
##       Newspaper < 28.3     to the left,  improve=0.04083687, (0 missing)
##   Surrogate splits:
##       Newspaper < 20.4     to the left,  agree=0.614, adj=0.190, (0 split)
##       Web       < 88.86432 to the right, agree=0.614, adj=0.190, (0 split)
##       TV        < 170.45   to the left,  agree=0.591, adj=0.143, (0 split)
## 
## Node number 7: 40 observations,    complexity param=0.04765527
##   mean=21.025, MSE=9.121375 
##   left son=14 (12 obs) right son=15 (28 obs)
##   Primary splits:
##       TV        < 194.55   to the left,  improve=0.53783920, (0 missing)
##       Radio     < 42       to the left,  improve=0.39216040, (0 missing)
##       Newspaper < 39.15    to the left,  improve=0.05520939, (0 missing)
##       Web       < 232.0539 to the right, improve=0.05510135, (0 missing)
##   Surrogate splits:
##       Newspaper < 73.95    to the right, agree=0.725, adj=0.083, (0 split)
## 
## Node number 10: 14 observations
##   mean=9.657143, MSE=1.293878 
## 
## Node number 11: 23 observations
##   mean=12.48261, MSE=2.709263 
## 
## Node number 12: 21 observations
##   mean=11.76667, MSE=0.9031746 
## 
## Node number 13: 23 observations
##   mean=15.07826, MSE=2.156484 
## 
## Node number 14: 12 observations
##   mean=17.64167, MSE=1.472431 
## 
## Node number 15: 28 observations,    complexity param=0.02362595
##   mean=22.475, MSE=5.391161 
##   left son=30 (9 obs) right son=31 (19 obs)
##   Primary splits:
##       Radio     < 35.3     to the left,  improve=0.6444821, (0 missing)
##       TV        < 258.35   to the left,  improve=0.2648266, (0 missing)
##       Web       < 209.7224 to the right, improve=0.2553318, (0 missing)
##       Newspaper < 39.15    to the left,  improve=0.1296573, (0 missing)
##   Surrogate splits:
##       Web       < 209.7224 to the right, agree=0.786, adj=0.333, (0 split)
##       Newspaper < 12.55    to the left,  agree=0.714, adj=0.111, (0 split)
## 
## Node number 30: 9 observations
##   mean=19.76667, MSE=0.7155556 
## 
## Node number 31: 19 observations
##   mean=23.75789, MSE=2.485596

Representar visualmente el árbol de regresión

rpart.plot(modelo_ar)

Hacer predicciones

predicciones <- predict(object = modelo_ar, newdata = datos.validacion)
# predicciones

Construir un data frame para comparar

comparaciones <- data.frame(datos.validacion, predicciones)
comparaciones
##        TV Radio Newspaper       Web Sales predicciones
## 10  199.8   2.6      21.2 111.27226  10.6    11.766667
## 20  147.3  23.9      19.1 268.73538  14.6    15.078261
## 21  218.4  27.7      53.4  59.96055  18.0    19.766667
## 22  237.4   5.1      23.5 296.95207  12.5    11.766667
## 24  228.3  16.9      26.2  51.17007  15.5    15.078261
## 26  262.9   3.5      19.5 160.56286  12.0    11.766667
## 27  142.9  29.3      12.6 275.51248  15.0    17.641667
## 30   70.6  16.0      40.8  61.32436  10.5    12.482609
## 31  292.9  28.3      43.2 121.46435  21.4    19.766667
## 33   97.2   1.5      30.0 139.78109   9.6     9.657143
## 34  265.6  20.0       0.3  94.20726  17.4    15.078261
## 35   95.7   1.4       7.4 321.17461   9.5     9.657143
## 36  290.7   4.1       8.5 181.98342  12.8    11.766667
## 42  177.0  33.4      38.7 147.85932  17.1    17.641667
## 48  239.9  41.5      18.5 105.96291  23.2    23.757895
## 50   66.9  11.7      36.8 205.25350   9.7     9.657143
## 54  182.6  46.2      58.7 176.05005  21.2    17.641667
## 55  262.7  28.8      15.9 324.61518  20.2    19.766667
## 60  210.7  29.5       9.3 138.89555  18.4    19.766667
## 63  239.3  15.5      27.3 312.20956  15.7    15.078261
## 66   69.0   9.3       0.9 205.99349   9.3     9.657143
## 67   31.5  24.6       2.2 216.47140   9.5     6.752381
## 69  237.4  27.5      11.0 291.54860  18.9    19.766667
## 76   16.9  43.7      89.4  70.23428   8.7     6.752381
## 83   75.3  20.3      32.5 231.20983  11.3    12.482609
## 84   68.4  44.5      35.6  78.39310  13.6    12.482609
## 87   76.3  27.5      16.0 193.83089  12.0    12.482609
## 90  109.8  47.8      51.4 162.72789  16.7    12.482609
## 93  217.7  33.5      59.0 150.96275  19.4    19.766667
## 95  107.4  14.0      10.9 151.99073  11.5    12.482609
## 101 222.4   4.3      49.8 125.62714  11.7    11.766667
## 104 187.9  17.2      17.9  97.08863  14.7    15.078261
## 107  25.0  11.0      29.7  15.93821   7.2     6.752381
## 109  13.1   0.4      25.6 252.39135   5.3     6.752381
## 111 225.8   8.2      56.5  95.18576  13.4    11.766667
## 112 241.7  38.0      23.2 180.51153  21.8    23.757895
## 114 209.6  20.6      10.7  42.88380  15.9    15.078261
## 116  75.1  35.0      52.7 204.27671  12.6    12.482609
## 118  76.4   0.8      14.8 234.38450   9.4     9.657143
## 120  19.4  16.0      22.3 112.89261   6.6     6.752381
## 125 229.5  32.3      74.2  88.08072  19.7    19.766667
## 128  80.2   0.0       9.2 358.24704   8.8     9.657143
## 130  59.6  12.0      43.1 197.19655   9.7     9.657143
## 133   8.4  27.2       2.1 238.05522   5.7     6.752381
## 139  43.0  25.9      20.5 181.36874   9.6    12.482609
## 140 184.9  43.9       1.7 106.25383  20.7    17.641667
## 144 104.6   5.7      34.4 336.57109  10.4     9.657143
## 149  38.0  40.3      11.9  75.20798  10.9    12.482609
## 151 280.7  13.9      37.0  81.04062  16.1    15.078261
## 153 197.6  23.3      14.2 159.52256  16.6    15.078261
## 171  50.0  11.6      18.4  64.01480   8.4     9.657143
## 172 164.5  20.9      47.4  96.18039  14.5    15.078261
## 177 248.4  30.2      20.3 163.85204  20.2    19.766667
## 178 170.2   7.8      35.2 104.91734  11.7    11.766667
## 182 218.5   5.4      27.4 162.38749  12.2    11.766667
## 191  39.5  41.1       5.8 219.89058  10.8    12.482609
## 194 166.8  42.0       3.6 192.24621  19.6    17.641667
## 199 283.6  42.0      66.2 237.49806  25.5    23.757895

Evaluar predicciones

rmse Root Mean Stándard Error (Root-mean-square deviation), este valor normalmente se compara contra otro modelo y el que esté mas cerca de cero es mejor.

La raiz del Error Cuadrático Medio (rmse) es una métrica que dice qué tan lejos están los valores predichos de los valores observados o reales en un análisis de regresión, en promedio. Se calcula como:

\[ rmse = \sqrt{\frac{\sum(predicho_i - real_i)^{2}}{n}} \]

RMSE es una forma útil de ver qué tan bien un modelo de regresión puede ajustarse a un conjunto de datos.

Cuanto mayor sea el rmse, mayor será la diferencia entre los valores predichos y reales, lo que significa que peor se ajusta un modelo de regresión a los datos. Por el contrario, cuanto más pequeño sea el rmse, mejor podrá un modelo ajustar los datos.

Evaluando con rmse

En el modelo de regresión múltiple https://rpubs.com/rpizarro/879843 con los datos Adverstising se tuvo un valor de rmse de: 1.470771.

Con este modelo de árbol de regresión, los mismos datos, mismas particiones se tuvo un valor de 1.455681 por lo que se puede interpretar que este modelo de regresión fué mejor con respecto a la métrica rmse.

rmse <- rmse(actual = comparaciones$Sales, predicted = comparaciones$predicciones)
rmse
## [1] 1.455681

Evaluando con la correlación

Se puede evaluar con la correlación lineal de los valores predichos contra los valores relaes o viceversa.

chart.Correlation(R = comparaciones[, c('Sales', 'predicciones')], histogram = TRUE)

Se observa una muy fuerte correlación entre las predicciones contra los valores reales (Sales) y viceversa de 0.95.

Visualizar predicciones contra valores reales

ggplot(data = comparaciones) +
  geom_line(aes(x = 1:nrow(comparaciones), y = Sales), col='blue') +
  geom_line(aes(x = 1:nrow(comparaciones), y = predicciones), col='yellow') +
  ggtitle(label="Valores reales vs predichos Adverstising", subtitle = "Arbol de Regresión") 

Predicciones con datos nuevos

TV <- c(140, 160)
Radio <- c(60, 40)
Newspaper <- c(80, 90) 
Web <- c(120, 145)
  
nuevos <- data.frame(TV, Radio, Newspaper, Web)  
nuevos
##    TV Radio Newspaper Web
## 1 140    60        80 120
## 2 160    40        90 145
Y.predicciones <- predict(object = modelo_ar, newdata = nuevos)
Y.predicciones
##        1        2 
## 17.64167 17.64167

Interpretación

Bibliografía

Hernández, Freddy. 2021. Modelos Predictivos. https://fhernanb.github.io/libro_mod_pred/;
Lantz, Brett. 2013. Aprendizaje Automático Con r. Publicación de paquetes. Edición de Kindle. Publicación de paquetes. Edición de Kindle.
XLSTAT by Addinsoft. n.d. “Árboles de Clasificación y Regresión.” https://www.xlstat.com/es/soluciones/funciones/arboles-de-clasificacion-y-de-regresion.