#Control 3-Salinas Profesora: Magdalena Cortina
6/22/2021
Control 3: Métodos estadísticos en DS
Predicción ataques cárdiacos Suponga que Ud. trabaja como analista en conjunto con médicos del área cardiovascular. Estos médicos le entregan una base de datos cuyas observaciones corresponde a personas que han tenido o no un ataque al corazón.
Cuenta con el siguiente diccionario de variable:
age: Edad del paciente. sex: Sexo del paciente. cp: Chest pain. Tipo de dolor de pecho. Valor 1: Angina de pecho típica. Valor 2: Angina de pecho atípica. Valor 3: Dolor no anginoso. Valor 4: Asintomático. trtbps: Presión arterial en reposo (en mm Hg). chol: Colesterol en mg / dl obtenido a través del sensor de IMC. fbs: Variable dummy que indica si el azúcar en sangre en ayunas es mayor a 120 mg / dl Valor 1: verdadero. Valor 0: falso. restecg: Resultados electrocardiográficos en reposo. Valor 0: Normal. Valor 1: Presenta una anomalía de la onda ST-T (inversiones de la onda T y / o elevación o depresión del ST de> 0,05 mV). Valor 2: Muestra hipertrofia ventricular izquierda probable o definitiva según los criterios de Estes. thalachh: Frecuencia cardíaca máxima alcanzada. exng: Variable dummy de angina inducida por ejercicio. Valor 1: Verdadero. Valor 0: Falso. oldpeak: Peak anterior. slp: Pendiente. caa: Número de vasos principales del corazón (1-3) thall: Tasa de thal, proveniente de un trastorno sanguíneo llamado talasemia. output: Variable objetivo. Dummy de ataque al corazón. Valor 1: Verdadero. Valor 0: Falso. Para comenzar con su análisis:
###P1 Cargue todos los paquetes que necesita para trabajar con data.table, modelos de predicción de regresión, árboles de decisión, cluster y Cross-Validation. Además, cargue la base de datos. (1 punto) Importante: Verifique la clase (class) de las variables que vaya a utilizar en todos sus modelos y si es necesario transformarla a numérica o factor, hágalo!
library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.1 ──
## ✓ ggplot2 3.3.4 ✓ purrr 0.3.4
## ✓ tibble 3.1.1 ✓ dplyr 1.0.5
## ✓ tidyr 1.1.3 ✓ stringr 1.4.0
## ✓ readr 1.4.0 ✓ forcats 0.5.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## x dplyr::filter() masks stats::filter()
## x dplyr::lag() masks stats::lag()
library(ggplot2)
library(tibble)
library(tidyr)
library(readr)
library(purrr)
library(dplyr)
library(stringr)
library(forcats)
library(data.table)
##
## Attaching package: 'data.table'
## The following objects are masked from 'package:dplyr':
##
## between, first, last
## The following object is masked from 'package:purrr':
##
## transpose
library(factoextra)
## Welcome! Want to learn more? See two factoextra-related books at https://goo.gl/ve3WBa
library(dbscan)
library(caret)
## Loading required package: lattice
##
## Attaching package: 'caret'
## The following object is masked from 'package:purrr':
##
## lift
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
library(rpart)
library(rpart.plot)
library(moderndive)
library(knitr)
library(jtools)
library(readr)
Ataques_cardiacos <- read_csv("/Users/antoniasalinas/Downloads/DATOS CONTROL 3.csv")
##
## ── Column specification ────────────────────────────────────────────────────────
## cols(
## age = col_double(),
## sex = col_double(),
## cp = col_double(),
## trtbps = col_double(),
## chol = col_double(),
## fbs = col_double(),
## restecg = col_double(),
## thalachh = col_double(),
## exng = col_double(),
## oldpeak = col_double(),
## slp = col_double(),
## caa = col_double(),
## thall = col_double(),
## output = col_double()
## )
class(Ataques_cardiacos)
## [1] "spec_tbl_df" "tbl_df" "tbl" "data.frame"
Ataques_cardiacos <- as.data.table(Ataques_cardiacos)
class(Ataques_cardiacos)
## [1] "data.table" "data.frame"
str(Ataques_cardiacos)
## Classes 'data.table' and 'data.frame': 303 obs. of 14 variables:
## $ age : num 63 37 41 56 57 57 56 44 52 57 ...
## $ sex : num 1 1 0 1 0 1 0 1 1 1 ...
## $ cp : num 3 2 1 1 0 0 1 1 2 2 ...
## $ trtbps : num 145 130 130 120 120 140 140 120 172 150 ...
## $ chol : num 233 250 204 236 354 192 294 263 199 168 ...
## $ fbs : num 1 0 0 0 0 0 0 0 1 0 ...
## $ restecg : num 0 1 0 1 1 1 0 1 1 1 ...
## $ thalachh: num 150 187 172 178 163 148 153 173 162 174 ...
## $ exng : num 0 0 0 0 1 0 0 0 0 0 ...
## $ oldpeak : num 2.3 3.5 1.4 0.8 0.6 0.4 1.3 0 0.5 1.6 ...
## $ slp : num 0 0 2 2 2 1 1 2 2 2 ...
## $ caa : num 0 0 0 0 0 0 0 0 0 0 ...
## $ thall : num 1 2 2 2 2 1 2 3 3 2 ...
## $ output : num 1 1 1 1 1 1 1 1 1 1 ...
## - attr(*, "spec")=
## .. cols(
## .. age = col_double(),
## .. sex = col_double(),
## .. cp = col_double(),
## .. trtbps = col_double(),
## .. chol = col_double(),
## .. fbs = col_double(),
## .. restecg = col_double(),
## .. thalachh = col_double(),
## .. exng = col_double(),
## .. oldpeak = col_double(),
## .. slp = col_double(),
## .. caa = col_double(),
## .. thall = col_double(),
## .. output = col_double()
## .. )
## - attr(*, ".internal.selfref")=<externalptr>
###P2 Realice dos modelos de regresión lineal multiple para predecir la Presión arterial en reposo ¿Cuál predice mejor dentro de muestra?. (8 puntos) Observación: No obtendrá puntaje si compara un modelo de regresión de una variable.
reg_1 <- lm(trtbps~sex, age, data = Ataques_cardiacos)
reg_2 <- lm(trtbps~age, chol, data = Ataques_cardiacos)
prediccion<-predict(reg_1)
Ataques_cardiacos[,prediccion:=predict(reg_1)]
prediccion1=data.table(RMSE=RMSE(prediccion,Ataques_cardiacos$trtbps),
MAE=MAE(prediccion,Ataques_cardiacos$trtbps))
prediccion1
## RMSE MAE
## 1: 18.89238 14.31099
pred2 = predict(reg_2)
prediccion_2 =data.table (RMSE=RMSE(pred2, Ataques_cardiacos$trtbps), MAE=MAE (pred2, Ataques_cardiacos$trtbps))
## Warning in pred - obs: longer object length is not a multiple of shorter object
## length
## Warning in pred - obs: longer object length is not a multiple of shorter object
## length
prediccion_2
## RMSE MAE
## 1: 17.90999 14.2167
###P3 Realice validación cruzada (CV) a los modelos de la pregunta anterior por el método K-folds con 5 folds. ¿Se mantienen las conclusiones anteriores?. (8 putos) Pista1: Recuerde setear la semilla set.seed(12345).
Pista2: Si existen variables con NA recuerde que puede excluirlas esas observaciones del análisis, pero no las elimine.
set.seed(12345)
setupKCV <- trainControl(method = "cv" , number = 5)
predkfolds1<-train(trtbps~sex+age,data=Ataques_cardiacos,method="lm",trControl= setupKCV)
predkfolds2<-train(trtbps~age+ chol, data=Ataques_cardiacos,method="lm",trControl= setupKCV)
print(predkfolds1)
## Linear Regression
##
## 303 samples
## 2 predictor
##
## No pre-processing
## Resampling: Cross-Validated (5 fold)
## Summary of sample sizes: 242, 242, 242, 244, 242
## Resampling results:
##
## RMSE Rsquared MAE
## 16.86589 0.08178795 12.95736
##
## Tuning parameter 'intercept' was held constant at a value of TRUE
print(predkfolds2)
## Linear Regression
##
## 303 samples
## 2 predictor
##
## No pre-processing
## Resampling: Cross-Validated (5 fold)
## Summary of sample sizes: 243, 241, 242, 243, 243
## Resampling results:
##
## RMSE Rsquared MAE
## 16.71265 0.08817041 12.94635
##
## Tuning parameter 'intercept' was held constant at a value of TRUE
###P4 Proponga dos variables sobre las cuales segmentar la muestra, en orden de hacer análisis de clusters con el método de kmeans. Muestre sus resultados gráficamente. (5 puntos) Pista1: Si existen outliers recuerde eliminarlos, para esto cree un nuevo objeto donde se encuentren estas dos variables. ###Utilizaremos sex y trtbps.
base2=Ataques_cardiacos[,.(age,trtbps)]
ggplot(data = base2,aes(x=age,y=trtbps))+
geom_point()
###P5 Realice dos modelos de árboles de clasificación de la variable output. Pruebe cuál modelo clasifica mejor con validación cruzada. Entrene el modelo con un 80% de la muestra y testee con el 20% restante. Explicite qué modelo es mejor y porqué. (12 puntos) Importante: Recuerde setear la semilla set.seed(12345).
Observación: No obtendrá puntaje si compara un modelo de clasificación de una variable.
arbol_1 <- rpart(output + age~., data=Ataques_cardiacos, method = "class")
rpart.plot(arbol_1, main = "Árbol de Clasificación: Sexo")
set.seed(12345)
div=createDataPartition(Ataques_cardiacos$output+Ataques_cardiacos$sex, times = 1, p = 0.8, list = F)
train= Ataques_cardiacos[div,]
test= Ataques_cardiacos[-div,]
arbol_2= rpart(output+sex~., data = train, method = "class")
rpart.plot(arbol_2)
prediccion_1 =predict(arbol_1, newdata = test, type = "class")
matriz= table(test$output + test$age, prediccion_1)
matriz
## prediccion_1
## 30 35 36 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
## 35 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0
## 39 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0
## 40 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0
## 41 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0
## 42 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0
## 43 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
## 44 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0
## 45 0 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 1 0 0 0 0
## 46 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 1
## 48 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2
## 49 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1
## 51 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0
## 52 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 1
## 53 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0
## 54 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 0 0 0 1
## 55 0 0 0 0 0 0 0 0 0 0 0 0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 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
## 49 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
## 51 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
## 52 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
## 53 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
## 54 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
## 55 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
## 56 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0
## 57 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
## 58 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0
## 59 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
## 61 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
## 62 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0
## 63 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0
## 64 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
## 65 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
## 67 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
## 68 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
## 69 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
prediccion_2= predict(arbol_2, newdata= test, type="class")
matriz2= table(test$output + test$sex , prediccion_2)
matriz2
## prediccion_2
## 0 1 2
## 0 1 6 0
## 1 3 20 12
## 2 0 7 11
###Analizaremos la precision de los dos modelos:
sum(diag(matriz))/sum(matriz)
## [1] 0.1
sum(diag(matriz2))/sum(matriz2)
## [1] 0.5333333
El modelo 2 clasifica mejor, ya que la precision del modelo es de 53% , en comparacion con el primer modelo que su precision es muy baja, siendo de 10% aproximadamente.