Instalación de paquetes y librerías

#install.packages("caret")    
library(caret)
#install.packages("ggplot2")  #Para poder graficar con mejor diseño
library(ggplot2)
#install.packages("lattice")  #Para crear gráficos
library(lattice)
#install.packages("datasets") #Para poder usar la base de datos "Iris"
library(datasets)
#install.packages("DataExplorer") #Para poder usar la base de datos "Iris"
library(DataExplorer)
#install.packages("Kernlab") #Para poder usar la base de datos "Iris"
library(tidyverse)
library(kernlab)
library(rpart)
library(mlbench)
library(dplyr)

Crear base de datos

data("BreastCancer")
df <- data.frame(BreastCancer)
#df

Descripción de la data

Análisis observatorio de los datos

summary(df)
##       Id             Cl.thickness   Cell.size     Cell.shape  Marg.adhesion
##  Length:699         1      :145   1      :384   1      :353   1      :407  
##  Class :character   5      :130   10     : 67   2      : 59   2      : 58  
##  Mode  :character   3      :108   3      : 52   10     : 58   3      : 58  
##                     4      : 80   2      : 45   3      : 56   10     : 55  
##                     10     : 69   4      : 40   4      : 44   4      : 33  
##                     2      : 50   5      : 30   5      : 34   8      : 25  
##                     (Other):117   (Other): 81   (Other): 95   (Other): 63  
##   Epith.c.size  Bare.nuclei   Bl.cromatin  Normal.nucleoli    Mitoses   
##  2      :386   1      :402   2      :166   1      :443     1      :579  
##  3      : 72   10     :132   3      :165   10     : 61     2      : 35  
##  4      : 48   2      : 30   1      :152   3      : 44     3      : 33  
##  1      : 47   5      : 30   7      : 73   2      : 36     10     : 14  
##  6      : 41   3      : 28   4      : 40   8      : 24     4      : 12  
##  5      : 39   (Other): 61   5      : 34   6      : 22     7      :  9  
##  (Other): 66   NA's   : 16   (Other): 69   (Other): 69     (Other): 17  
##        Class    
##  benign   :458  
##  malignant:241  
##                 
##                 
##                 
##                 
## 
str(df)
## 'data.frame':    699 obs. of  11 variables:
##  $ Id             : chr  "1000025" "1002945" "1015425" "1016277" ...
##  $ Cl.thickness   : Ord.factor w/ 10 levels "1"<"2"<"3"<"4"<..: 5 5 3 6 4 8 1 2 2 4 ...
##  $ Cell.size      : Ord.factor w/ 10 levels "1"<"2"<"3"<"4"<..: 1 4 1 8 1 10 1 1 1 2 ...
##  $ Cell.shape     : Ord.factor w/ 10 levels "1"<"2"<"3"<"4"<..: 1 4 1 8 1 10 1 2 1 1 ...
##  $ Marg.adhesion  : Ord.factor w/ 10 levels "1"<"2"<"3"<"4"<..: 1 5 1 1 3 8 1 1 1 1 ...
##  $ Epith.c.size   : Ord.factor w/ 10 levels "1"<"2"<"3"<"4"<..: 2 7 2 3 2 7 2 2 2 2 ...
##  $ Bare.nuclei    : Factor w/ 10 levels "1","2","3","4",..: 1 10 2 4 1 10 10 1 1 1 ...
##  $ Bl.cromatin    : Factor w/ 10 levels "1","2","3","4",..: 3 3 3 3 3 9 3 3 1 2 ...
##  $ Normal.nucleoli: Factor w/ 10 levels "1","2","3","4",..: 1 2 1 7 1 7 1 1 1 1 ...
##  $ Mitoses        : Factor w/ 9 levels "1","2","3","4",..: 1 1 1 1 1 1 1 1 5 1 ...
##  $ Class          : Factor w/ 2 levels "benign","malignant": 1 1 1 1 1 2 1 1 1 1 ...
#create_report(df)
#Quitar la columna de Id's
df<- df%>% select(-Id)

#Omitir los NA's
df<- na.omit(df)

#create_report(df)
str(df)
## 'data.frame':    683 obs. of  10 variables:
##  $ Cl.thickness   : Ord.factor w/ 10 levels "1"<"2"<"3"<"4"<..: 5 5 3 6 4 8 1 2 2 4 ...
##  $ Cell.size      : Ord.factor w/ 10 levels "1"<"2"<"3"<"4"<..: 1 4 1 8 1 10 1 1 1 2 ...
##  $ Cell.shape     : Ord.factor w/ 10 levels "1"<"2"<"3"<"4"<..: 1 4 1 8 1 10 1 2 1 1 ...
##  $ Marg.adhesion  : Ord.factor w/ 10 levels "1"<"2"<"3"<"4"<..: 1 5 1 1 3 8 1 1 1 1 ...
##  $ Epith.c.size   : Ord.factor w/ 10 levels "1"<"2"<"3"<"4"<..: 2 7 2 3 2 7 2 2 2 2 ...
##  $ Bare.nuclei    : Factor w/ 10 levels "1","2","3","4",..: 1 10 2 4 1 10 10 1 1 1 ...
##  $ Bl.cromatin    : Factor w/ 10 levels "1","2","3","4",..: 3 3 3 3 3 9 3 3 1 2 ...
##  $ Normal.nucleoli: Factor w/ 10 levels "1","2","3","4",..: 1 2 1 7 1 7 1 1 1 1 ...
##  $ Mitoses        : Factor w/ 9 levels "1","2","3","4",..: 1 1 1 1 1 1 1 1 5 1 ...
##  $ Class          : Factor w/ 2 levels "benign","malignant": 1 1 1 1 1 2 1 1 1 1 ...
##  - attr(*, "na.action")= 'omit' Named int [1:16] 24 41 140 146 159 165 236 250 276 293 ...
##   ..- attr(*, "names")= chr [1:16] "24" "41" "140" "146" ...

Cambiar las variables numeric

df <- mutate_all(df, as.numeric)
df <- df %>% 
  mutate(Class = as.factor(Class))
str(df)
## 'data.frame':    683 obs. of  10 variables:
##  $ Cl.thickness   : num  5 5 3 6 4 8 1 2 2 4 ...
##  $ Cell.size      : num  1 4 1 8 1 10 1 1 1 2 ...
##  $ Cell.shape     : num  1 4 1 8 1 10 1 2 1 1 ...
##  $ Marg.adhesion  : num  1 5 1 1 3 8 1 1 1 1 ...
##  $ Epith.c.size   : num  2 7 2 3 2 7 2 2 2 2 ...
##  $ Bare.nuclei    : num  1 10 2 4 1 10 10 1 1 1 ...
##  $ Bl.cromatin    : num  3 3 3 3 3 9 3 3 1 2 ...
##  $ Normal.nucleoli: num  1 2 1 7 1 7 1 1 1 1 ...
##  $ Mitoses        : num  1 1 1 1 1 1 1 1 5 1 ...
##  $ Class          : Factor w/ 2 levels "1","2": 1 1 1 1 1 2 1 1 1 1 ...
##  - attr(*, "na.action")= 'omit' Named int [1:16] 24 41 140 146 159 165 236 250 276 293 ...
##   ..- attr(*, "names")= chr [1:16] "24" "41" "140" "146" ...

Partir datos 80-20

set.seed(123)
renglones_entrenamiento_cancer <- 
  createDataPartition(df$Class, p=0.8, list= FALSE)
entrenamiento_cancer <- df[renglones_entrenamiento_cancer, ]
prueba_cancer <- df[-renglones_entrenamiento_cancer, ]

1.Modelo con el método svmLineal

modelo1_cancer <- train(Class ~., data=entrenamiento_cancer, 
                method ="svmLinear", #Cambiar
                preProcess =c("scale", "center"),
                trControl=trainControl(method="cv", number=10),#Para una revisada rápida
                tuneGrid =data.frame(C=1)#Cuando es svmLinear
                )
resultado_entrenamiento1_cancer <- predict(modelo1_cancer, entrenamiento_cancer)
resultado_prueba1_cancer <- predict(modelo1_cancer, prueba_cancer)

#Matriz de Confusión

mcre1_cancer <- confusionMatrix(resultado_entrenamiento1_cancer, entrenamiento_cancer$Class) #matriz de confusión del entrenamiento
mcre1_cancer
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction   1   2
##          1 347   7
##          2   9 185
##                                          
##                Accuracy : 0.9708         
##                  95% CI : (0.953, 0.9832)
##     No Information Rate : 0.6496         
##     P-Value [Acc > NIR] : <2e-16         
##                                          
##                   Kappa : 0.936          
##                                          
##  Mcnemar's Test P-Value : 0.8026         
##                                          
##             Sensitivity : 0.9747         
##             Specificity : 0.9635         
##          Pos Pred Value : 0.9802         
##          Neg Pred Value : 0.9536         
##              Prevalence : 0.6496         
##          Detection Rate : 0.6332         
##    Detection Prevalence : 0.6460         
##       Balanced Accuracy : 0.9691         
##                                          
##        'Positive' Class : 1              
## 
mcrp1_cancer <- confusionMatrix(resultado_prueba1_cancer, prueba_cancer$Class) #matriz de confusión del resultado de la prueba
mcrp1_cancer
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  1  2
##          1 87  2
##          2  1 45
##                                           
##                Accuracy : 0.9778          
##                  95% CI : (0.9364, 0.9954)
##     No Information Rate : 0.6519          
##     P-Value [Acc > NIR] : <2e-16          
##                                           
##                   Kappa : 0.9508          
##                                           
##  Mcnemar's Test P-Value : 1               
##                                           
##             Sensitivity : 0.9886          
##             Specificity : 0.9574          
##          Pos Pred Value : 0.9775          
##          Neg Pred Value : 0.9783          
##              Prevalence : 0.6519          
##          Detection Rate : 0.6444          
##    Detection Prevalence : 0.6593          
##       Balanced Accuracy : 0.9730          
##                                           
##        'Positive' Class : 1               
## 

2.Modelo con el Método svmRadial

modelo2_cancer <- train(Class ~ ., data=entrenamiento_cancer, method= "svmRadial", preProcess=c("scale", "center"), trControl = trainControl(method = "cv", number=10), tuneGrid= data.frame(sigma=1, C=1) #Cambiar
                )
 
resultado_entrenamiento2_cancer <- predict(modelo2_cancer, entrenamiento_cancer)
resultado_prueba2_cancer <- predict(modelo2_cancer, prueba_cancer)

Matriz de Confusión

mcre2_cancer <- confusionMatrix(resultado_entrenamiento2_cancer, entrenamiento_cancer$Class) #matriz de confusión del resultado del entrenamiento
mcre2_cancer
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction   1   2
##          1 354   0
##          2   2 192
##                                           
##                Accuracy : 0.9964          
##                  95% CI : (0.9869, 0.9996)
##     No Information Rate : 0.6496          
##     P-Value [Acc > NIR] : <2e-16          
##                                           
##                   Kappa : 0.992           
##                                           
##  Mcnemar's Test P-Value : 0.4795          
##                                           
##             Sensitivity : 0.9944          
##             Specificity : 1.0000          
##          Pos Pred Value : 1.0000          
##          Neg Pred Value : 0.9897          
##              Prevalence : 0.6496          
##          Detection Rate : 0.6460          
##    Detection Prevalence : 0.6460          
##       Balanced Accuracy : 0.9972          
##                                           
##        'Positive' Class : 1               
## 
mcrp2_cancer <- confusionMatrix(resultado_prueba2_cancer, prueba_cancer$Class) #matriz de confusión del resultado de la prueba
mcrp2_cancer
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  1  2
##          1 82  0
##          2  6 47
##                                           
##                Accuracy : 0.9556          
##                  95% CI : (0.9058, 0.9835)
##     No Information Rate : 0.6519          
##     P-Value [Acc > NIR] : < 2e-16         
##                                           
##                   Kappa : 0.9049          
##                                           
##  Mcnemar's Test P-Value : 0.04123         
##                                           
##             Sensitivity : 0.9318          
##             Specificity : 1.0000          
##          Pos Pred Value : 1.0000          
##          Neg Pred Value : 0.8868          
##              Prevalence : 0.6519          
##          Detection Rate : 0.6074          
##    Detection Prevalence : 0.6074          
##       Balanced Accuracy : 0.9659          
##                                           
##        'Positive' Class : 1               
## 

3.Modelo con el Método svmPoly

modelo3_cancer <- train(Class ~ ., data=entrenamiento_cancer, method= "svmPoly", preProcess=c("scale", "center"), trControl = trainControl(method = "cv", number=10), tuneGrid= data.frame(degree=1, scale=1, C=1) #Cambiar
                )
 
resultado_entrenamiento3_cancer <- predict(modelo3_cancer, entrenamiento_cancer)
resultado_prueba3_cancer <- predict(modelo3_cancer, prueba_cancer)

Matriz de Confusión

mcre3_cancer <- confusionMatrix(resultado_entrenamiento3_cancer, entrenamiento_cancer$Class) #matriz de confusión del resultado del entrenamiento
mcre3_cancer
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction   1   2
##          1 347   7
##          2   9 185
##                                          
##                Accuracy : 0.9708         
##                  95% CI : (0.953, 0.9832)
##     No Information Rate : 0.6496         
##     P-Value [Acc > NIR] : <2e-16         
##                                          
##                   Kappa : 0.936          
##                                          
##  Mcnemar's Test P-Value : 0.8026         
##                                          
##             Sensitivity : 0.9747         
##             Specificity : 0.9635         
##          Pos Pred Value : 0.9802         
##          Neg Pred Value : 0.9536         
##              Prevalence : 0.6496         
##          Detection Rate : 0.6332         
##    Detection Prevalence : 0.6460         
##       Balanced Accuracy : 0.9691         
##                                          
##        'Positive' Class : 1              
## 
mcrp3_cancer <- confusionMatrix(resultado_prueba3_cancer, prueba_cancer$Class) #matriz de confusión del resultado de la prueba
mcrp3_cancer
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  1  2
##          1 87  2
##          2  1 45
##                                           
##                Accuracy : 0.9778          
##                  95% CI : (0.9364, 0.9954)
##     No Information Rate : 0.6519          
##     P-Value [Acc > NIR] : <2e-16          
##                                           
##                   Kappa : 0.9508          
##                                           
##  Mcnemar's Test P-Value : 1               
##                                           
##             Sensitivity : 0.9886          
##             Specificity : 0.9574          
##          Pos Pred Value : 0.9775          
##          Neg Pred Value : 0.9783          
##              Prevalence : 0.6519          
##          Detection Rate : 0.6444          
##    Detection Prevalence : 0.6593          
##       Balanced Accuracy : 0.9730          
##                                           
##        'Positive' Class : 1               
## 

4.Modelo con el Método rpart

modelo4_cancer <- train(Class ~ ., data=entrenamiento_cancer, method= "rpart", preProcess=c("scale", "center"), trControl = trainControl(method = "cv", number=10), tuneLength=10 #Cambiar
                )
 
resultado_entrenamiento4_cancer <- predict(modelo4_cancer, entrenamiento_cancer)
resultado_prueba4_cancer <- predict(modelo4_cancer, prueba_cancer)

Matriz de Confusión

mcre4_cancer <- confusionMatrix(resultado_entrenamiento4_cancer, entrenamiento_cancer$Class) #matriz de confusión del resultado del entrenamiento
mcre4_cancer
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction   1   2
##          1 345   9
##          2  11 183
##                                           
##                Accuracy : 0.9635          
##                  95% CI : (0.9442, 0.9776)
##     No Information Rate : 0.6496          
##     P-Value [Acc > NIR] : <2e-16          
##                                           
##                   Kappa : 0.92            
##                                           
##  Mcnemar's Test P-Value : 0.8231          
##                                           
##             Sensitivity : 0.9691          
##             Specificity : 0.9531          
##          Pos Pred Value : 0.9746          
##          Neg Pred Value : 0.9433          
##              Prevalence : 0.6496          
##          Detection Rate : 0.6296          
##    Detection Prevalence : 0.6460          
##       Balanced Accuracy : 0.9611          
##                                           
##        'Positive' Class : 1               
## 
mcrp4_cancer <- confusionMatrix(resultado_prueba4_cancer, prueba_cancer$Class) #matriz de confusión del resultado de la prueba
mcrp4_cancer
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  1  2
##          1 87  5
##          2  1 42
##                                           
##                Accuracy : 0.9556          
##                  95% CI : (0.9058, 0.9835)
##     No Information Rate : 0.6519          
##     P-Value [Acc > NIR] : <2e-16          
##                                           
##                   Kappa : 0.9001          
##                                           
##  Mcnemar's Test P-Value : 0.2207          
##                                           
##             Sensitivity : 0.9886          
##             Specificity : 0.8936          
##          Pos Pred Value : 0.9457          
##          Neg Pred Value : 0.9767          
##              Prevalence : 0.6519          
##          Detection Rate : 0.6444          
##    Detection Prevalence : 0.6815          
##       Balanced Accuracy : 0.9411          
##                                           
##        'Positive' Class : 1               
## 

5.Modelo con el Método nnet

Matriz de Confusión

mcre5_cancer <- confusionMatrix(resultado_entrenamiento5_cancer, entrenamiento_cancer$Class) #matriz de confusión del resultado del entrenamiento
mcre5_cancer
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction   1   2
##          1 351   0
##          2   5 192
##                                          
##                Accuracy : 0.9909         
##                  95% CI : (0.9788, 0.997)
##     No Information Rate : 0.6496         
##     P-Value [Acc > NIR] : < 2e-16        
##                                          
##                   Kappa : 0.9801         
##                                          
##  Mcnemar's Test P-Value : 0.07364        
##                                          
##             Sensitivity : 0.9860         
##             Specificity : 1.0000         
##          Pos Pred Value : 1.0000         
##          Neg Pred Value : 0.9746         
##              Prevalence : 0.6496         
##          Detection Rate : 0.6405         
##    Detection Prevalence : 0.6405         
##       Balanced Accuracy : 0.9930         
##                                          
##        'Positive' Class : 1              
## 
mcrp5_cancer <- confusionMatrix(resultado_prueba5_cancer, prueba_cancer$Class) #matriz de confusión del resultado de la prueba
mcrp5_cancer
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  1  2
##          1 86  4
##          2  2 43
##                                           
##                Accuracy : 0.9556          
##                  95% CI : (0.9058, 0.9835)
##     No Information Rate : 0.6519          
##     P-Value [Acc > NIR] : <2e-16          
##                                           
##                   Kappa : 0.9011          
##                                           
##  Mcnemar's Test P-Value : 0.6831          
##                                           
##             Sensitivity : 0.9773          
##             Specificity : 0.9149          
##          Pos Pred Value : 0.9556          
##          Neg Pred Value : 0.9556          
##              Prevalence : 0.6519          
##          Detection Rate : 0.6370          
##    Detection Prevalence : 0.6667          
##       Balanced Accuracy : 0.9461          
##                                           
##        'Positive' Class : 1               
## 

6.Modelo con el Método rf

modelo6_cancer <- train(Class ~ ., data=entrenamiento_cancer, method= "rf", preProcess=c("scale", "center"), trControl = trainControl(method = "cv", number=10), tuneGrid= expand.grid(mtry=c(2,4,6)) #Cambiar
                )
 
resultado_entrenamiento6_cancer <- predict(modelo6_cancer, entrenamiento_cancer)
resultado_prueba6_cancer <- predict(modelo6_cancer, prueba_cancer)

Matriz de Confusión

mcre6_cancer <- confusionMatrix(resultado_entrenamiento6_cancer, entrenamiento_cancer$Class) #matriz de confusión del resultado del entrenamiento
mcre6_cancer
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction   1   2
##          1 356   1
##          2   0 191
##                                      
##                Accuracy : 0.9982     
##                  95% CI : (0.9899, 1)
##     No Information Rate : 0.6496     
##     P-Value [Acc > NIR] : <2e-16     
##                                      
##                   Kappa : 0.996      
##                                      
##  Mcnemar's Test P-Value : 1          
##                                      
##             Sensitivity : 1.0000     
##             Specificity : 0.9948     
##          Pos Pred Value : 0.9972     
##          Neg Pred Value : 1.0000     
##              Prevalence : 0.6496     
##          Detection Rate : 0.6496     
##    Detection Prevalence : 0.6515     
##       Balanced Accuracy : 0.9974     
##                                      
##        'Positive' Class : 1          
## 
mcrp6_cancer <- confusionMatrix(resultado_prueba6_cancer, prueba_cancer$Class) #matriz de confusión del resultado de la prueba
mcrp6_cancer
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  1  2
##          1 85  1
##          2  3 46
##                                           
##                Accuracy : 0.9704          
##                  95% CI : (0.9259, 0.9919)
##     No Information Rate : 0.6519          
##     P-Value [Acc > NIR] : <2e-16          
##                                           
##                   Kappa : 0.9354          
##                                           
##  Mcnemar's Test P-Value : 0.6171          
##                                           
##             Sensitivity : 0.9659          
##             Specificity : 0.9787          
##          Pos Pred Value : 0.9884          
##          Neg Pred Value : 0.9388          
##              Prevalence : 0.6519          
##          Detection Rate : 0.6296          
##    Detection Prevalence : 0.6370          
##       Balanced Accuracy : 0.9723          
##                                           
##        'Positive' Class : 1               
## 

Resumen de resultados

resultados <- data.frame(
  "1. svmLinear" = c(mcre1_cancer$overall["Accuracy"], mcrp1_cancer$overall["Accuracy"]),
  "2. svmRadial" = c(mcre2_cancer$overall["Accuracy"], mcrp2_cancer$overall["Accuracy"]),
  "3. svmPoly" = c(mcre3_cancer$overall["Accuracy"], mcrp3_cancer$overall["Accuracy"]),
  "4. rpart" = c(mcre4_cancer$overall["Accuracy"], mcrp4_cancer$overall["Accuracy"]),
  "5. nnet" = c(mcre5_cancer$overall["Accuracy"], mcrp5_cancer$overall["Accuracy"]),
  "6. rf" = c (mcre6_cancer$overall["Accuracy"], mcrp6_cancer$overall["Accuracy"])
)
rownames(resultados) <- c("Precisión de entrenamiento", "Precisión de prueba")
resultados
##                            X1..svmLinear X2..svmRadial X3..svmPoly X4..rpart
## Precisión de entrenamiento     0.9708029     0.9963504   0.9708029 0.9635036
## Precisión de prueba            0.9777778     0.9555556   0.9777778 0.9555556
##                             X5..nnet    X6..rf
## Precisión de entrenamiento 0.9908759 0.9981752
## Precisión de prueba        0.9555556 0.9703704

En base a nuestro resumen de resultados, podemos ver que el modelo 1 y el modelo 3 tienen los mismos resultados de precisión, con esto podemos decidir que nuestro mejor modelo es el Lineal (modelo 1) ya que es más fácil de tener una mayor interpretación, es más simple y eficiente, es menos propenso al sobreajuste además de ser robusto y estable.