Instale y cargue todos los paquetes que necesita para trabajar con data.table, modelos de predicción de regresión y CART y Cross-Validation.
library(data.table)
library(caret)
## Loading required package: lattice
## Loading required package: ggplot2
library(rpart)
library(rpart.plot)
library(data.table)
library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.1 ──
## ✓ tibble 3.1.0 ✓ dplyr 1.0.5
## ✓ tidyr 1.1.3 ✓ stringr 1.4.0
## ✓ readr 1.4.0 ✓ forcats 0.5.1
## ✓ purrr 0.3.4
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## x dplyr::between() masks data.table::between()
## x dplyr::filter() masks stats::filter()
## x dplyr::first() masks data.table::first()
## x dplyr::lag() masks stats::lag()
## x dplyr::last() masks data.table::last()
## x purrr::lift() masks caret::lift()
## x purrr::transpose() masks data.table::transpose()
library(leaflet)
library(leaflet.extras)
library(chilemapas)
## Loading required package: sf
## Linking to GEOS 3.8.1, GDAL 3.1.4, PROJ 6.3.1
## Registered S3 method overwritten by 'geojsonlint':
## method from
## print.location dplyr
library(sp)
library(rgdal)
## rgdal: version: 1.5-23, (SVN revision 1121)
## Geospatial Data Abstraction Library extensions to R successfully loaded
## Loaded GDAL runtime: GDAL 3.2.1, released 2020/12/29
## Path to GDAL shared files: /Library/Frameworks/R.framework/Versions/4.0/Resources/library/rgdal/gdal
## GDAL binary built with GEOS: TRUE
## Loaded PROJ runtime: Rel. 7.2.1, January 1st, 2021, [PJ_VERSION: 721]
## Path to PROJ shared files: /Library/Frameworks/R.framework/Versions/4.0/Resources/library/rgdal/proj
## PROJ CDN enabled: FALSE
## Linking to sp version:1.4-5
## To mute warnings of possible GDAL/OSR exportToProj4() degradation,
## use options("rgdal_show_exportToProj4_warnings"="none") before loading rgdal.
## Overwritten PROJ_LIB was /Library/Frameworks/R.framework/Versions/4.0/Resources/library/rgdal/proj
library(KernSmooth)
## KernSmooth 2.23 loaded
## Copyright M. P. Wand 1997-2009
library(classInt)
library(factoextra)
## Welcome! Want to learn more? See two factoextra-related books at https://goo.gl/ve3WBa
library(dbscan)
library(dplyr)
library(car)
## Loading required package: carData
##
## Attaching package: 'car'
## The following object is masked from 'package:dplyr':
##
## recode
## The following object is masked from 'package:purrr':
##
## some
Cargar base de datos Chile que viene en el paquete car. Recuerde que la base debe transofrmarse a data.table.
plebicito = Chile
plebicito <- data.table(plebicito)
Cree una muestra de la base que solo contenga los votos Yes y No. A partir de ahora todo el trabajo se realizará con esa base!
muestreo = sample_n(plebicito, size = 1000)
muestreo1 = muestreo[muestreo$vote== c( "N", "Y")]
Plantee dos modelos de predcción distintos que logren predecir en ingreso de las personas.
reg1 = lm( data =muestreo1, formula = income~ sex + age )
reg2 = lm( data =muestreo1, formula = income~ sex + age + education + vote + population )
summary(reg2)
##
## Call:
## lm(formula = income ~ sex + age + education + vote + population,
## data = muestreo1)
##
## Residuals:
## Min 1Q Median 3Q Max
## -64850 -19520 -5714 6297 175915
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -9.797e+03 7.865e+03 -1.246 0.2138
## sexM 4.941e+02 3.986e+03 0.124 0.9014
## age 3.200e+02 1.394e+02 2.296 0.0223 *
## educationPS 5.546e+04 6.034e+03 9.191 < 2e-16 ***
## educationS 2.579e+04 4.833e+03 5.336 1.81e-07 ***
## voteY 1.056e+04 4.213e+03 2.508 0.0127 *
## population 4.852e-02 2.127e-02 2.281 0.0232 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 34990 on 318 degrees of freedom
## (8 observations deleted due to missingness)
## Multiple R-squared: 0.2541, Adjusted R-squared: 0.24
## F-statistic: 18.05 on 6 and 318 DF, p-value: < 2.2e-16
summary (reg1)
##
## Call:
## lm(formula = income ~ sex + age, data = muestreo1)
##
## Residuals:
## Min 1Q Median 3Q Max
## -34573 -22069 -18772 1174 166244
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 33681.666 6477.277 5.200 3.55e-07 ***
## sexM 3137.587 4464.676 0.703 0.483
## age 3.907 146.034 0.027 0.979
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 40230 on 322 degrees of freedom
## (8 observations deleted due to missingness)
## Multiple R-squared: 0.001532, Adjusted R-squared: -0.00467
## F-statistic: 0.247 on 2 and 322 DF, p-value: 0.7813
Evalue cuál modelo predice mejor el ingreso. Sea claro/a con su criterio de evaluación. Recuerde que no es lo mismo predecir dentro de muestra que fuera de muestra.
R: se puede ver que la regresion 2 (reg2) predice de mejor manera el ingreso qye la regresion 1 (reg1) esto se ve dado que su r cuadrado es mas alto ( 0.2526>0.005501) esto muestra que la regresion 1 predice de mejor manera que la otra regresion
Ahora queremos predecir el voto de una persona en el plebiscito, es decir, si voto por el si o por el no, utilizando árboles de decisión.
str(muestreo1)
## Classes 'data.table' and 'data.frame': 333 obs. of 8 variables:
## $ region : Factor w/ 5 levels "C","M","N","S",..: 4 5 4 3 5 3 5 1 1 5 ...
## $ population: int 250000 250000 250000 250000 250000 175000 250000 15000 250000 250000 ...
## $ sex : Factor w/ 2 levels "F","M": 2 1 1 1 2 2 1 1 1 1 ...
## $ age : int 21 20 38 70 67 65 20 18 37 26 ...
## $ education : Factor w/ 3 levels "P","PS","S": 3 3 2 2 3 1 3 1 2 3 ...
## $ income : int 15000 15000 75000 125000 7500 35000 15000 2500 35000 125000 ...
## $ statusquo : num -0.1683 1.0036 0.0505 1.449 1.5481 ...
## $ vote : Factor w/ 4 levels "A","N","U","Y": 2 4 4 4 4 4 2 4 2 4 ...
## - attr(*, ".internal.selfref")=<externalptr>
muestreo1$vote = as.factor(muestreo1$vote)
muestreo1$sex = as.factor(muestreo1$sex)
muestreo1$education = as.factor(muestreo1$education)
muestreo1$age = as.numeric(muestreo1$age)
muestreo1$income = as.numeric(muestreo1$income)
arbol1 = rpart(vote ~ ., data = muestreo1,method = "class")
rpart.plot(arbol1, main = "arbol de voto")
dado que solo exisiten dos posibilidades (Y & N) el arbol solo tendira 1 face que utiliza con statusquo si el statusquo es inferior a -0,38 en los cuales estan el 48% de la poblacion y por el contrario, si el statusquo es superior a -o,38 se voto que si (Y) aca se encunetra el 52% de la muestra.
Cree el set de entrenamiento y de prueba. Utilice set.seed(1234). Muestre los resultados del set de entrenamiento.
set.seed(1234)
div = createDataPartition(muestreo1$vote, times = 1 , p = 0.8 , list = F)
## Warning in createDataPartition(muestreo1$vote, times = 1, p = 0.8, list = F):
## Some classes have no records ( A, U ) and these will be ignored
test1 = muestreo1[div,]
test2 = muestreo1[-div,]
arbol_2 <- rpart(vote~., data = test1, method = "class")
arbol_3 <- rpart(vote~., data = test2, method = "class")
rpart.plot(arbol_2)
rpart.plot(arbol_3)
Calcule la predicción del modelo
predict1 = predict(arbol_2, newdata = test2, type = "class")
Calcule la matriz de confusión y la precisión del modelo. Muestre y explique ambos.
matriz = table (test2$vote, predict1)
precisio = sum(diag(matriz))/sum(matriz)
matriz
## predict1
## A N U Y
## A 0 0 0 0
## N 0 30 0 5
## U 0 0 0 0
## Y 0 2 0 29
precisio
## [1] 0.8939394
se puede ver que existe un pequeño margen de error pero en general la prediccion tiene ~91% de precision
Cargue la data de USArrests que nos entrega R. Para obtener esta base de datos vea la clase de áboles de decisión, en el código para la data de titanic, guardela n un objeto llamado datos
datos = USArrests
Reescale la base de datos con la función scale() y guardela con el nombre datos1. Además realice un gráfico de codo para saber cuantos cluster realizar.
datos1 = scale(datos)
str(datos)
## 'data.frame': 50 obs. of 4 variables:
## $ Murder : num 13.2 10 8.1 8.8 9 7.9 3.3 5.9 15.4 17.4 ...
## $ Assault : int 236 263 294 190 276 204 110 238 335 211 ...
## $ UrbanPop: int 58 48 80 50 91 78 77 72 80 60 ...
## $ Rape : num 21.2 44.5 31 19.5 40.6 38.7 11.1 15.8 31.9 25.8 ...
ggplot(data = datos,aes(x=Murder,y=Assault))+
geom_point()
fviz_nbclust(x = datos, FUNcluster = kmeans, method = "wss", k.max = 15,
diss = get_dist(datos, method = "euclidean"), nstart = 50)
Realice un k-means con la base de datos datos1 y grafique el resultado.
k1<-kmeans(x=datos,centers=4,nstart=25)
fviz_cluster(k1,data=datos,geom = "point")