El paquete CARET (Classification and Regression Training) es un paquete integral con una amplia variedad de algoritmos para el aprendizaje automático.
#install.packages("caret") # algoritmos de aprendizaje automático
library(caret)
#install.packages("ggplot2") # graficas
library(ggplot2)
#install.packages("lattice") #crear gráficos
library(lattice)
#install.packages("readxl") # para cargar archivos excel
library(readxl)
#install.packages("DataExplorer") #análisis descriptivo
library(DataExplorer)
#install.packages("kernlab")
library(kernlab)
#install.packages("randomForest")
library(randomForest)
#install.packages("rpart")
library(rpart)
#install.packages("ipred")
library(ipred)
#file.choose()
df <- read_excel("/Users/mayteavalos/Downloads/heart.xlsx")
# Convertir la variable target a FACTOR para modelo de clasificación
df$target <- as.factor(df$target)
summary(df)
## age sex cp trestbps
## Min. :29.00 Min. :0.0000 Min. :0.0000 Min. : 94.0
## 1st Qu.:48.00 1st Qu.:0.0000 1st Qu.:0.0000 1st Qu.:120.0
## Median :56.00 Median :1.0000 Median :1.0000 Median :130.0
## Mean :54.43 Mean :0.6956 Mean :0.9424 Mean :131.6
## 3rd Qu.:61.00 3rd Qu.:1.0000 3rd Qu.:2.0000 3rd Qu.:140.0
## Max. :77.00 Max. :1.0000 Max. :3.0000 Max. :200.0
## chol fbs restecg thalach
## Min. :126 Min. :0.0000 Min. :0.0000 Min. : 71.0
## 1st Qu.:211 1st Qu.:0.0000 1st Qu.:0.0000 1st Qu.:132.0
## Median :240 Median :0.0000 Median :1.0000 Median :152.0
## Mean :246 Mean :0.1493 Mean :0.5298 Mean :149.1
## 3rd Qu.:275 3rd Qu.:0.0000 3rd Qu.:1.0000 3rd Qu.:166.0
## Max. :564 Max. :1.0000 Max. :2.0000 Max. :202.0
## exang oldpeak slope ca
## Min. :0.0000 Min. :0.000 Min. :0.000 Min. :0.0000
## 1st Qu.:0.0000 1st Qu.:0.000 1st Qu.:1.000 1st Qu.:0.0000
## Median :0.0000 Median :0.800 Median :1.000 Median :0.0000
## Mean :0.3366 Mean :1.072 Mean :1.385 Mean :0.7541
## 3rd Qu.:1.0000 3rd Qu.:1.800 3rd Qu.:2.000 3rd Qu.:1.0000
## Max. :1.0000 Max. :6.200 Max. :2.000 Max. :4.0000
## thal target
## Min. :0.000 0:499
## 1st Qu.:2.000 1:526
## Median :2.000
## Mean :2.324
## 3rd Qu.:3.000
## Max. :3.000
str(df)
## tibble [1,025 × 14] (S3: tbl_df/tbl/data.frame)
## $ age : num [1:1025] 52 53 70 61 62 58 58 55 46 54 ...
## $ sex : num [1:1025] 1 1 1 1 0 0 1 1 1 1 ...
## $ cp : num [1:1025] 0 0 0 0 0 0 0 0 0 0 ...
## $ trestbps: num [1:1025] 125 140 145 148 138 100 114 160 120 122 ...
## $ chol : num [1:1025] 212 203 174 203 294 248 318 289 249 286 ...
## $ fbs : num [1:1025] 0 1 0 0 1 0 0 0 0 0 ...
## $ restecg : num [1:1025] 1 0 1 1 1 0 2 0 0 0 ...
## $ thalach : num [1:1025] 168 155 125 161 106 122 140 145 144 116 ...
## $ exang : num [1:1025] 0 1 1 0 0 0 0 1 0 1 ...
## $ oldpeak : num [1:1025] 1 3.1 2.6 0 1.9 1 4.4 0.8 0.8 3.2 ...
## $ slope : num [1:1025] 2 0 0 2 1 1 0 1 2 1 ...
## $ ca : num [1:1025] 2 0 0 1 3 0 3 1 0 2 ...
## $ thal : num [1:1025] 3 3 3 3 2 2 1 3 3 2 ...
## $ target : Factor w/ 2 levels "0","1": 1 1 1 1 1 2 1 1 1 1 ...
#create_report(df)
plot_missing(df)
plot_histogram(df)
plot_correlation(df)
# Normalmente 80-20 o 70-30
set.seed(123)
renglones_entrenamiento <- createDataPartition(df$target, p=0.8, list= FALSE)
entrenamiento <- df[renglones_entrenamiento, ] #cuando despues de la coma no hay nada, considera todos los valores
prueba <- df[-renglones_entrenamiento, ]
Los métodos más utilizados para modelar aprendizaje automático son:
modelo1 <- train(target ~ ., data = entrenamiento,
method = "svmLinear",
preProcess = c("scale", "center"),
trControl = trainControl(method = "cv", number = 10),
tuneGrid = data.frame(C = 1)
)
resultado_entrenamiento1 <- predict(modelo1, entrenamiento)
resultado_prueba1 <- predict(modelo1, prueba)
#Matriz de confusión
# Es una tabla de evaluación que desglosa el rendimiento del modelo de clasificación
#Matriz de confusión del resultado de entrenamiento
mcre1 <- confusionMatrix(resultado_entrenamiento1, entrenamiento$target)
mcre1
## Confusion Matrix and Statistics
##
## Reference
## Prediction 0 1
## 0 301 37
## 1 99 384
##
## Accuracy : 0.8343
## 95% CI : (0.8071, 0.8592)
## No Information Rate : 0.5128
## P-Value [Acc > NIR] : < 2.2e-16
##
## Kappa : 0.6672
##
## Mcnemar's Test P-Value : 1.689e-07
##
## Sensitivity : 0.7525
## Specificity : 0.9121
## Pos Pred Value : 0.8905
## Neg Pred Value : 0.7950
## Prevalence : 0.4872
## Detection Rate : 0.3666
## Detection Prevalence : 0.4117
## Balanced Accuracy : 0.8323
##
## 'Positive' Class : 0
##
#Matriz de confusión del resultado de la prueba
mcrp1 <- confusionMatrix(resultado_prueba1, prueba$target)
mcrp1
## Confusion Matrix and Statistics
##
## Reference
## Prediction 0 1
## 0 78 10
## 1 21 95
##
## Accuracy : 0.848
## 95% CI : (0.7913, 0.8944)
## No Information Rate : 0.5147
## P-Value [Acc > NIR] : < 2e-16
##
## Kappa : 0.6948
##
## Mcnemar's Test P-Value : 0.07249
##
## Sensitivity : 0.7879
## Specificity : 0.9048
## Pos Pred Value : 0.8864
## Neg Pred Value : 0.8190
## Prevalence : 0.4853
## Detection Rate : 0.3824
## Detection Prevalence : 0.4314
## Balanced Accuracy : 0.8463
##
## 'Positive' Class : 0
##
modelo2 <- train(target ~ ., data = entrenamiento,
method = "svmRadial",
preProcess = c("scale", "center"),
trControl = trainControl(method = "cv", number = 10),
tuneGrid = data.frame(sigma = 0.1, C = 1)
)
resultado_entrenamiento2 <- predict(modelo2, entrenamiento)
resultado_prueba2 <- predict(modelo2, prueba)
#Matriz de confusión
# Es una tabla de evaluación que desglosa el rendimiento del modelo de clasificación
#Matriz de confusión del resultado de entrenamiento
mcre2 <- confusionMatrix(resultado_entrenamiento2, entrenamiento$target)
mcre2
## Confusion Matrix and Statistics
##
## Reference
## Prediction 0 1
## 0 385 7
## 1 15 414
##
## Accuracy : 0.9732
## 95% CI : (0.9597, 0.9831)
## No Information Rate : 0.5128
## P-Value [Acc > NIR] : <2e-16
##
## Kappa : 0.9463
##
## Mcnemar's Test P-Value : 0.1356
##
## Sensitivity : 0.9625
## Specificity : 0.9834
## Pos Pred Value : 0.9821
## Neg Pred Value : 0.9650
## Prevalence : 0.4872
## Detection Rate : 0.4689
## Detection Prevalence : 0.4775
## Balanced Accuracy : 0.9729
##
## 'Positive' Class : 0
##
#Matriz de confusión del resultado de la prueba
mcrp2 <- confusionMatrix(resultado_prueba2, prueba$target)
mcrp2
## Confusion Matrix and Statistics
##
## Reference
## Prediction 0 1
## 0 95 5
## 1 4 100
##
## Accuracy : 0.9559
## 95% CI : (0.9179, 0.9796)
## No Information Rate : 0.5147
## P-Value [Acc > NIR] : <2e-16
##
## Kappa : 0.9117
##
## Mcnemar's Test P-Value : 1
##
## Sensitivity : 0.9596
## Specificity : 0.9524
## Pos Pred Value : 0.9500
## Neg Pred Value : 0.9615
## Prevalence : 0.4853
## Detection Rate : 0.4657
## Detection Prevalence : 0.4902
## Balanced Accuracy : 0.9560
##
## 'Positive' Class : 0
##
modelo3 <- train(target ~ ., data = entrenamiento,
method = "svmPoly",
preProcess = c("scale", "center"),
trControl = trainControl(method = "cv", number = 10),
tuneGrid = data.frame(degree = 2, scale = 1, C = 1)
)
resultado_entrenamiento3 <- predict(modelo3, entrenamiento)
resultado_prueba3 <- predict(modelo3, prueba)
#Matriz de confusión
# Es una tabla de evaluación que desglosa el rendimiento del modelo de clasificación
#Matriz de confusión del resultado de entrenamiento
mcre3 <- confusionMatrix(resultado_entrenamiento3, entrenamiento$target)
mcre3
## Confusion Matrix and Statistics
##
## Reference
## Prediction 0 1
## 0 398 1
## 1 2 420
##
## Accuracy : 0.9963
## 95% CI : (0.9894, 0.9992)
## No Information Rate : 0.5128
## P-Value [Acc > NIR] : <2e-16
##
## Kappa : 0.9927
##
## Mcnemar's Test P-Value : 1
##
## Sensitivity : 0.9950
## Specificity : 0.9976
## Pos Pred Value : 0.9975
## Neg Pred Value : 0.9953
## Prevalence : 0.4872
## Detection Rate : 0.4848
## Detection Prevalence : 0.4860
## Balanced Accuracy : 0.9963
##
## 'Positive' Class : 0
##
#Matriz de confusión del resultado de la prueba
mcrp3 <- confusionMatrix(resultado_prueba3, prueba$target)
mcrp3
## Confusion Matrix and Statistics
##
## Reference
## Prediction 0 1
## 0 97 2
## 1 2 103
##
## Accuracy : 0.9804
## 95% CI : (0.9506, 0.9946)
## No Information Rate : 0.5147
## P-Value [Acc > NIR] : <2e-16
##
## Kappa : 0.9608
##
## Mcnemar's Test P-Value : 1
##
## Sensitivity : 0.9798
## Specificity : 0.9810
## Pos Pred Value : 0.9798
## Neg Pred Value : 0.9810
## Prevalence : 0.4853
## Detection Rate : 0.4755
## Detection Prevalence : 0.4853
## Balanced Accuracy : 0.9804
##
## 'Positive' Class : 0
##
modelo4 <- train(target ~ ., data = entrenamiento,
method = "rpart",
preProcess = c("scale", "center"),
trControl = trainControl(method = "cv", number = 10),
tuneLength = 10
)
resultado_entrenamiento4 <- predict(modelo4, entrenamiento)
resultado_prueba4 <- predict(modelo4, prueba)
#Matriz de confusión
# Es una tabla de evaluación que desglosa el rendimiento del modelo de clasificación
#Matriz de confusión del resultado de entrenamiento
mcre4 <- confusionMatrix(resultado_entrenamiento4, entrenamiento$target)
mcre4
## Confusion Matrix and Statistics
##
## Reference
## Prediction 0 1
## 0 360 29
## 1 40 392
##
## Accuracy : 0.916
## 95% CI : (0.8948, 0.934)
## No Information Rate : 0.5128
## P-Value [Acc > NIR] : <2e-16
##
## Kappa : 0.8317
##
## Mcnemar's Test P-Value : 0.2286
##
## Sensitivity : 0.9000
## Specificity : 0.9311
## Pos Pred Value : 0.9254
## Neg Pred Value : 0.9074
## Prevalence : 0.4872
## Detection Rate : 0.4385
## Detection Prevalence : 0.4738
## Balanced Accuracy : 0.9156
##
## 'Positive' Class : 0
##
#Matriz de confusión del resultado de la prueba
mcrp4 <- confusionMatrix(resultado_prueba4, prueba$target)
mcrp4
## Confusion Matrix and Statistics
##
## Reference
## Prediction 0 1
## 0 81 7
## 1 18 98
##
## Accuracy : 0.8775
## 95% CI : (0.8244, 0.9191)
## No Information Rate : 0.5147
## P-Value [Acc > NIR] : <2e-16
##
## Kappa : 0.7539
##
## Mcnemar's Test P-Value : 0.0455
##
## Sensitivity : 0.8182
## Specificity : 0.9333
## Pos Pred Value : 0.9205
## Neg Pred Value : 0.8448
## Prevalence : 0.4853
## Detection Rate : 0.3971
## Detection Prevalence : 0.4314
## Balanced Accuracy : 0.8758
##
## 'Positive' Class : 0
##
modelo5 <- train(target ~ ., data = entrenamiento,
method = "rf",
preProcess = c("scale", "center"),
trControl = trainControl(method = "cv", number = 10),
tuneGrid = expand.grid(mtry = c(2, 4, 6, 8))
)
resultado_entrenamiento5 <- predict(modelo5, entrenamiento)
resultado_prueba5 <- predict(modelo5, prueba)
#Matriz de confusión
# Es una tabla de evaluación que desglosa el rendimiento del modelo de clasificación
#Matriz de confusión del resultado de entrenamiento
mcre5 <- confusionMatrix(resultado_entrenamiento5, entrenamiento$target)
mcre5
## Confusion Matrix and Statistics
##
## Reference
## Prediction 0 1
## 0 400 0
## 1 0 421
##
## Accuracy : 1
## 95% CI : (0.9955, 1)
## No Information Rate : 0.5128
## P-Value [Acc > NIR] : < 2.2e-16
##
## Kappa : 1
##
## Mcnemar's Test P-Value : NA
##
## Sensitivity : 1.0000
## Specificity : 1.0000
## Pos Pred Value : 1.0000
## Neg Pred Value : 1.0000
## Prevalence : 0.4872
## Detection Rate : 0.4872
## Detection Prevalence : 0.4872
## Balanced Accuracy : 1.0000
##
## 'Positive' Class : 0
##
#Matriz de confusión del resultado de la prueba
mcrp5 <- confusionMatrix(resultado_prueba5, prueba$target)
mcrp5
## Confusion Matrix and Statistics
##
## Reference
## Prediction 0 1
## 0 99 0
## 1 0 105
##
## Accuracy : 1
## 95% CI : (0.9821, 1)
## No Information Rate : 0.5147
## P-Value [Acc > NIR] : < 2.2e-16
##
## Kappa : 1
##
## Mcnemar's Test P-Value : NA
##
## Sensitivity : 1.0000
## Specificity : 1.0000
## Pos Pred Value : 1.0000
## Neg Pred Value : 1.0000
## Prevalence : 0.4853
## Detection Rate : 0.4853
## Detection Prevalence : 0.4853
## Balanced Accuracy : 1.0000
##
## 'Positive' Class : 0
##
modelo6 <- train(target ~ ., data = entrenamiento,
method = "nnet",
preProcess = c("scale", "center"),
trControl = trainControl(method = "cv", number = 10),
trace = FALSE
)
resultado_entrenamiento6 <- predict(modelo6, entrenamiento)
resultado_prueba6 <- predict(modelo6, prueba)
#Matriz de confusión
# Es una tabla de evaluación que desglosa el rendimiento del modelo de clasificación
#Matriz de confusión del resultado de entrenamiento
mcre6 <- confusionMatrix(resultado_entrenamiento6, entrenamiento$target)
mcre6
## Confusion Matrix and Statistics
##
## Reference
## Prediction 0 1
## 0 386 18
## 1 14 403
##
## Accuracy : 0.961
## 95% CI : (0.9454, 0.9732)
## No Information Rate : 0.5128
## P-Value [Acc > NIR] : <2e-16
##
## Kappa : 0.922
##
## Mcnemar's Test P-Value : 0.5959
##
## Sensitivity : 0.9650
## Specificity : 0.9572
## Pos Pred Value : 0.9554
## Neg Pred Value : 0.9664
## Prevalence : 0.4872
## Detection Rate : 0.4702
## Detection Prevalence : 0.4921
## Balanced Accuracy : 0.9611
##
## 'Positive' Class : 0
##
#Matriz de confusión del resultado de la prueba
mcrp6 <- confusionMatrix(resultado_prueba6, prueba$target)
mcrp6
## Confusion Matrix and Statistics
##
## Reference
## Prediction 0 1
## 0 98 5
## 1 1 100
##
## Accuracy : 0.9706
## 95% CI : (0.9371, 0.9891)
## No Information Rate : 0.5147
## P-Value [Acc > NIR] : <2e-16
##
## Kappa : 0.9412
##
## Mcnemar's Test P-Value : 0.2207
##
## Sensitivity : 0.9899
## Specificity : 0.9524
## Pos Pred Value : 0.9515
## Neg Pred Value : 0.9901
## Prevalence : 0.4853
## Detection Rate : 0.4804
## Detection Prevalence : 0.5049
## Balanced Accuracy : 0.9711
##
## 'Positive' Class : 0
##
resultados <- data.frame(
"Medida" = c("Entrenamiento", "Prueba"),
"svmLinear" = c(mcre1$overall["Accuracy"], mcrp1$overall["Accuracy"]),
"svmRadial" = c(mcre2$overall["Accuracy"], mcrp2$overall["Accuracy"]),
"svmPoly" = c(mcre3$overall["Accuracy"], mcrp3$overall["Accuracy"]),
"rpart" = c(mcre4$overall["Accuracy"], mcrp4$overall["Accuracy"]),
"rf" = c(mcre5$overall["Accuracy"], mcrp5$overall["Accuracy"]),
"nnet" = c(mcre6$overall["Accuracy"], mcrp6$overall["Accuracy"])
)
resultados
## Medida svmLinear svmRadial svmPoly rpart rf nnet
## 1 Entrenamiento 0.8343484 0.9732034 0.9963459 0.9159562 1 0.9610231
## 2 Prueba 0.8480392 0.9558824 0.9803922 0.8774510 1 0.9705882
En conclusión, el modelo de Bosques Aleatorios (rf) es el recomendado para la predicción de cardiopatías en este conjunto de datos, ya que tiene una precisión (Accuracy) perfecta del 100% en la evaluación con los datos de prueba.