diabetes2_1 <- read.csv("diabetes2.txt", sep=";")
diabetes2 <- diabetes2_1
diabetes2 <- as.data.frame(lapply(diabetes2, function(x) if(is.character(x)) 
  as.factor(x) else x))

DIAGRAMA DE BOXPLOT DE LAS VARIABLES NÚMERICAS.

library(ggplot2)
library(gridExtra)

p1 <- ggplot(diabetes2, aes(x=Diabetic,
                            y= BMI, color =Diabetic))+
  geom_boxplot() +coord_flip()+
  theme_classic()

p2 <- ggplot(diabetes2, aes(x=Diabetic,
                            y= Sleep, color =Diabetic))+
  geom_boxplot()+coord_flip()+
  theme_classic()

p3 <- ggplot(diabetes2, aes(x=Diabetic,
                            y= SoundSleep, color =Diabetic))+
  geom_boxplot()+coord_flip()+
  theme_classic()

p4 <- ggplot(diabetes2, aes(x=Diabetic,
                            y= Pregancies, color =Diabetic))+
  geom_boxplot()+coord_flip()+
  theme_classic()

grid.arrange(p1,p2,p3,p4, nrow = 2, ncol = 2)

BMI y pacientes que presentan o no diabetes

Sleep y pacientes que presentan o no diabetes

SoundSleep y pacientes que presentan o no diabetes

Pregancies y pacientes que presentan o no diabetes

Relación entre la variable binaria y las variables nominales.

library(ggmosaic)
library(gridExtra)

m1 <- ggplot(data = diabetes2)+
  geom_mosaic(aes(x = product(Diabetic, Age),
                  fill = Diabetic)) + 
  labs(x = "Age", title = "Factores_Diabetes")
m2 <- ggplot(data = diabetes2)+
  geom_mosaic(aes(x = product(Diabetic, Gender),
                  fill = Diabetic)) + 
  labs(x = "Gender", title = "Factores_Diabetes")
m3 <- ggplot(data = diabetes2)+
  geom_mosaic(aes(x = product(Diabetic, Family_Diabetes),
                  fill = Diabetic)) + 
  labs(x = "Family_Diabetes", title = "Factores_Diabetes")
m4 <- ggplot(data = diabetes2)+
  geom_mosaic(aes(x = product(Diabetic, highBP),
                  fill = Diabetic)) + 
  labs(x = "highBP", title = "Factores_Diabetes")
m5 <- ggplot(data = diabetes2)+
  geom_mosaic(aes(x = product(Diabetic, PhysicallyActive),
                  fill = Diabetic)) + 
  labs(x = "PhysicallyActive", title = "Factores_Diabetes")
m6 <- ggplot(data = diabetes2)+
  geom_mosaic(aes(x = product(Diabetic, Smoking),
                  fill = Diabetic)) + 
  labs(x = "Smoking", title = "Factores_Diabetes")
m7 <- ggplot(data = diabetes2)+
  geom_mosaic(aes(x = product(Diabetic, Alcohol),
                  fill = Diabetic)) + 
  labs(x = "Alcohol", title = "Factores_Diabetes")
m8 <- ggplot(data = diabetes2)+
  geom_mosaic(aes(x = product(Diabetic, RegularMedicine),
                  fill = Diabetic)) + 
  labs(x = "RegularMedicine", title = "Factores_Diabetes")
m9 <- ggplot(data = diabetes2)+
  geom_mosaic(aes(x = product(Diabetic, JunkFood),
                  fill = Diabetic)) + 
  labs(x = "JunkFood", title = "Factores_Diabetes")
m10 <- ggplot(data = diabetes2)+
  geom_mosaic(aes(x = product(Diabetic, Stress),
                  fill = Diabetic)) + 
  labs(x = "Stress", title = "Factores_Diabetes")
m11 <- ggplot(data = diabetes2)+
  geom_mosaic(aes(x = product(Diabetic, BPLevel),
                  fill = Diabetic)) + 
  labs(x = "BPLevel", title = "Factores_Diabetes")
m12 <- ggplot(data = diabetes2)+
  geom_mosaic(aes(x = product(Diabetic, Pdiabetes),
                  fill = Diabetic)) + 
  labs(x = "Pdiabetes", title = "Factores_Diabetes")
m13 <- ggplot(data = diabetes2)+
  geom_mosaic(aes(x = product(Diabetic, UriationFreq),
                  fill = Diabetic)) + 
  labs(x = "UriationFreq", title = "Factores_Diabetes")

grid.arrange(m1,m2,m3,m4,m5,m6,m7,nrow = 4, ncol = 2)

grid.arrange(m8,m9,m10,m11,m12,m13,nrow = 3, ncol = 2)

Gráfico multivariante

library(GGally)
classes <- sapply(diabetes2, class)
ggpairs(diabetes2[, classes == "integer"])+
  theme_bw()

Se observa una correlación negativa entre el indice de masa corporal y las horas de sueño, sueño profundo, número de embarazos, es decir que a medida que se aumente una hora de sueño, sueño profundo y el número de embarazos el indice de masa corporal va a disminuir. Adémas las correlaciones son significativas, por lo tanto las variables independientes influyen en el indice de masa corporal de los pacientes con diabetes.

Gráfico múltiple

p <- ggpairs(diabetes2[, c(which(classes == "integer"),18)],
             aes(color = Diabetic))+
  theme_bw()
## change color manually
## Loop through each plot changing relevant scales

for (i in 1:p$nrow) {
  for (j in 1:p$ncol) {
    p[i,j] <- p[i,j]+
      scale_fill_manual(values = c("#00AF88", "#E78800"))
      scale_color_manual(values = c("#00AF88", "#E78800"))
  }
}
p

Escalar variables númericas

Dividiremos el conjunto completo de individuos en dos partes, una para entrenar el modelo, que contiene el 80% de los individuos y otra para validarlo que contiene el resto. Esto es asi porque si valoramos el modelo con las mismas observaciones que usamos para ajustarlo, la bondad del ajuste quedara sobrevalorada.

Antes de ajustar cualquier modelo, es conveniente escalar las variables númericas y tenemos que reacondicionar las variables categoricas convirtiendolas en variables ficticias y usando la primera o la ultia categoria como comparacion.

diabetes2[, classes == "integer"]=scale(diabetes2[, classes == "integer"])
head(diabetes2,15)
            Age Gender Family_Diabetes highBP     PhysicallyActive        BMI
1  less than 40   Male             yes     no       one hr or more -0.6487242
2  less than 40   Male             yes     no       one hr or more -0.6487242
3   60 or older Female             yes     no                 none  0.1294871
4  less than 40   Male             yes     no more than half an hr -1.2323826
5   60 or older   Male              no     no more than half an hr -0.4541713
6         40-49   Male              no     no less than half an hr  0.1294871
7   60 or older   Male             yes     no more than half an hr  0.1294871
8         40-49 Female              no     no                 none -0.4541713
9  less than 40   Male              no     no less than half an hr -0.6487242
10        50-59   Male             yes     no       one hr or more  2.4641210
11 less than 40 Female              no     no       one hr or more -1.0378298
12 less than 40   Male              no     no more than half an hr -0.2596185
13  60 or older Female              no    yes less than half an hr  0.3240400
14 less than 40 Female             yes     no       one hr or more -0.2596185
15 less than 40   Male              no     no                 none -0.2596185
   Smoking Alcohol       Sleep SoundSleep RegularMedicine     JunkFood
1       no      no  0.78534240  0.2119477              no        often
2       no      no  0.78534240  0.2119477              no        often
3       no      no  0.01861803  0.7543900              no occasionally
4      yes     yes  0.01861803 -0.3304947              no occasionally
5       no     yes  0.01861803  0.2119477             yes occasionally
6      yes      no  0.78534240  0.7543900              no occasionally
7       no     yes  0.78534240 -1.4153793             yes occasionally
8       no      no  0.01861803  0.7543900              no        often
9       no      no -0.74810634 -1.9578216              no        often
10      no     yes  0.78534240  0.2119477             yes occasionally
11      no      no -0.74810634  0.2119477              no   very often
12     yes     yes  0.01861803  0.2119477              no        often
13      no      no -0.74810634  0.2119477             yes occasionally
14      no      no -2.28155509 -0.8729370             yes        often
15      no      no  2.31879115  2.3817169              no occasionally
       Stress BPLevel Pregancies Pdiabetes UriationFreq Diabetic
1  not at all  normal -0.4201082         0     not much       no
2  not at all  normal -0.4201082         0     not much       no
3   sometimes  normal  2.8800479         0     not much       no
4  not at all  normal -0.4201082         0     not much       no
5  very often    high -0.4201082         0  quite often      yes
6   sometimes  normal -0.4201082         0     not much       no
7   sometimes  normal -0.4201082         0  quite often      yes
8  very often  normal  0.6799439         0     not much       no
9  not at all  normal -0.4201082         0  quite often       no
10 very often  normal -0.4201082         0     not much      yes
11 not at all  normal -0.4201082         0     not much       no
12  sometimes  normal -0.4201082         0     not much       no
13     always    high -0.4201082         0  quite often      yes
14     always  normal  2.8800479         0     not much      yes
15 not at all  normal -0.4201082         0     not much       no
X = model.matrix(Diabetic ~., data = diabetes2)
head(X,20)
   (Intercept) Age50-59 Age60 or older Ageless than 40 GenderMale
1            1        0              0               1          1
2            1        0              0               1          1
3            1        0              1               0          0
4            1        0              0               1          1
5            1        0              1               0          1
6            1        0              0               0          1
7            1        0              1               0          1
8            1        0              0               0          0
9            1        0              0               1          1
10           1        1              0               0          1
11           1        0              0               1          0
12           1        0              0               1          1
13           1        0              1               0          0
14           1        0              0               1          0
15           1        0              0               1          1
16           1        0              0               0          1
17           1        0              0               1          0
18           1        0              0               0          1
19           1        0              0               1          1
20           1        1              0               0          1
   Family_Diabetesyes highBPyes PhysicallyActivemore than half an hr
1                   1         0                                    0
2                   1         0                                    0
3                   1         0                                    0
4                   1         0                                    1
5                   0         0                                    1
6                   0         0                                    0
7                   1         0                                    1
8                   0         0                                    0
9                   0         0                                    0
10                  1         0                                    0
11                  0         0                                    0
12                  0         0                                    1
13                  0         1                                    0
14                  1         0                                    0
15                  0         0                                    0
16                  1         0                                    0
17                  1         0                                    0
18                  1         0                                    0
19                  0         0                                    1
20                  0         1                                    0
   PhysicallyActivenone PhysicallyActiveone hr or more        BMI Smokingyes
1                     0                              1 -0.6487242          0
2                     0                              1 -0.6487242          0
3                     1                              0  0.1294871          0
4                     0                              0 -1.2323826          1
5                     0                              0 -0.4541713          0
6                     0                              0  0.1294871          1
7                     0                              0  0.1294871          0
8                     1                              0 -0.4541713          0
9                     0                              0 -0.6487242          0
10                    0                              1  2.4641210          0
11                    0                              1 -1.0378298          0
12                    0                              0 -0.2596185          1
13                    0                              0  0.3240400          0
14                    0                              1 -0.2596185          0
15                    1                              0 -0.2596185          0
16                    0                              0  0.3240400          0
17                    0                              0 -0.8432770          0
18                    0                              1 -0.4541713          0
19                    0                              0 -0.8432770          0
20                    0                              1  2.6586739          0
   Alcoholyes       Sleep SoundSleep RegularMedicineyes JunkFoodoccasionally
1           0  0.78534240  0.2119477                  0                    0
2           0  0.78534240  0.2119477                  0                    0
3           0  0.01861803  0.7543900                  0                    1
4           1  0.01861803 -0.3304947                  0                    1
5           1  0.01861803  0.2119477                  1                    1
6           0  0.78534240  0.7543900                  0                    1
7           1  0.78534240 -1.4153793                  1                    1
8           0  0.01861803  0.7543900                  0                    0
9           0 -0.74810634 -1.9578216                  0                    0
10          1  0.78534240  0.2119477                  1                    1
11          0 -0.74810634  0.2119477                  0                    0
12          1  0.01861803  0.2119477                  0                    0
13          0 -0.74810634  0.2119477                  1                    1
14          0 -2.28155509 -0.8729370                  1                    0
15          0  2.31879115  2.3817169                  0                    1
16          0  0.78534240  1.2968323                  0                    1
17          0  0.78534240  0.7543900                  0                    0
18          0  0.01861803  0.7543900                  0                    1
19          0 -1.51483072 -0.3304947                  0                    0
20          0  0.78534240  0.2119477                  0                    1
   JunkFoodoften JunkFoodvery often Stressnot at all Stresssometimes
1              1                  0                1               0
2              1                  0                1               0
3              0                  0                0               1
4              0                  0                1               0
5              0                  0                0               0
6              0                  0                0               1
7              0                  0                0               1
8              1                  0                0               0
9              1                  0                1               0
10             0                  0                0               0
11             0                  1                1               0
12             1                  0                0               1
13             0                  0                0               0
14             1                  0                0               0
15             0                  0                1               0
16             0                  0                0               1
17             1                  0                0               1
18             0                  0                0               1
19             0                  1                0               1
20             0                  0                0               1
   Stressvery often BPLevellow BPLevelnormal Pregancies Pdiabetesyes
1                 0          0             1 -0.4201082            0
2                 0          0             1 -0.4201082            0
3                 0          0             1  2.8800479            0
4                 0          0             1 -0.4201082            0
5                 1          0             0 -0.4201082            0
6                 0          0             1 -0.4201082            0
7                 0          0             1 -0.4201082            0
8                 1          0             1  0.6799439            0
9                 0          0             1 -0.4201082            0
10                1          0             1 -0.4201082            0
11                0          0             1 -0.4201082            0
12                0          0             1 -0.4201082            0
13                0          0             0 -0.4201082            0
14                0          0             1  2.8800479            0
15                0          0             1 -0.4201082            0
16                0          0             1 -0.4201082            0
17                0          0             1 -0.4201082            0
18                0          0             1 -0.4201082            0
19                0          0             1 -0.4201082            0
20                0          0             0 -0.4201082            0
   UriationFreqquite often
1                        0
2                        0
3                        0
4                        0
5                        1
6                        0
7                        1
8                        0
9                        1
10                       0
11                       0
12                       0
13                       1
14                       0
15                       0
16                       0
17                       0
18                       0
19                       0
20                       0

División del conjunto de datos

Observará que las variables numéricas reescaladas contienen los mismos valores iniciales. Cada una de las variables nominales ha sido convertida en variables binarias. El número de variables binarias es siempre el número de categorías de la variable nominal. Por ejemplo, la variable Gender (con dos categorías) ha sido convertida en GenderMale que es una variable numérica que vale 1 cuando el sexo es hombre y o cuando es mujer. El resto de variables también son convertidas a Binarias con el número de categorias que cada una almacena. Los parámetros correspondientes a las categorías retenidas comparan a éstas con la categoría eliminada.

Dividiremos el conjunto completo de individuos en dos partes, un para entrenar el modelo, que contiene el 80% de los individuos y otra para validarlo que contiene el resto. Esto es así porque si valoramos el modelo con las misma observaciones que usamos para ajustarlo, la bondad del ajuste quedará sobrevalorada. Por ejemplo, vamos ausar el 70% de los individuos para ajustar el modelo y el 30% para probarlo. Para que siempre obtengamos los mismos resultados colocamos la semilla de los números pseudo aleatorios con la fecha de nacimiento sin separaciones (diamesaño).

tr = round(nrow(diabetes2)*0.7)
set.seed(06071981)
muestra = sample.int(nrow(diabetes2), tr)
Train.diabet = diabetes2[muestra, ];head(Train.diabet,15)
             Age Gender Family_Diabetes highBP     PhysicallyActive        BMI
15  less than 40   Male              no     no                 none -0.2596185
736  60 or older   Male              no    yes less than half an hr -2.0105939
266        50-59   Male             yes    yes                 none  1.1022513
75         50-59   Male             yes    yes more than half an hr  2.0750154
442 less than 40   Male             yes     no       one hr or more -0.8432770
341  60 or older   Male             yes     no more than half an hr  0.1294871
481        50-59 Female              no    yes more than half an hr  1.4913569
529 less than 40 Female              no     no       one hr or more  0.1294871
571 less than 40   Male             yes     no less than half an hr -0.4541713
731        40-49   Male             yes    yes       one hr or more -0.6487242
260 less than 40 Female              no     no less than half an hr -0.8432770
177        40-49   Male              no    yes more than half an hr  0.3240400
27         50-59   Male             yes    yes                 none  1.1022513
186        40-49 Female             yes     no less than half an hr  1.4913569
305  60 or older Female             yes    yes                 none -0.2596185
    Smoking Alcohol       Sleep SoundSleep RegularMedicine     JunkFood
15       no      no  2.31879115  2.3817169              no occasionally
736      no      no -2.28155509 -0.8729370             yes occasionally
266      no     yes  0.01861803  0.2119477             yes occasionally
75      yes      no -0.74810634 -0.8729370             yes        often
442      no      no  1.55206678  0.2119477              no   very often
341      no     yes  0.78534240 -1.4153793             yes occasionally
481      no      no -0.74810634 -0.8729370             yes occasionally
529      no      no  0.78534240  0.2119477              no occasionally
571      no      no -1.51483072 -0.3304947              no       always
731      no      no  0.01861803  0.2119477             yes occasionally
260      no      no  0.78534240  1.2968323              no occasionally
177      no      no  0.78534240  1.2968323             yes occasionally
27       no     yes  0.01861803  0.2119477             yes occasionally
186      no      no -0.74810634  0.2119477              no   very often
305      no      no -2.28155509 -0.8729370             yes occasionally
        Stress BPLevel Pregancies Pdiabetes UriationFreq Diabetic
15  not at all  normal -0.4201082         0     not much       no
736 very often    high -0.4201082         0  quite often       no
266     always    high -0.4201082         0     not much      yes
75  very often    high -0.4201082         0     not much      yes
442  sometimes  normal -0.4201082         0     not much       no
341  sometimes  normal -0.4201082         0  quite often      yes
481  sometimes    high -0.4201082         0  quite often       no
529  sometimes     low -0.4201082         0     not much       no
571  sometimes  normal -0.4201082         0     not much       no
731  sometimes    high -0.4201082         0     not much      yes
260  sometimes  normal -0.4201082         0  quite often       no
177 not at all    high -0.4201082         0     not much      yes
27      always    high -0.4201082         0     not much      yes
186 very often  normal  1.7799959       yes     not much      yes
305     always    high  2.8800479         0  quite often      yes
val.diabet = diabetes2[-muestra, ];head(val.diabet, 15)
            Age Gender Family_Diabetes highBP     PhysicallyActive         BMI
4  less than 40   Male             yes     no more than half an hr -1.23238262
7   60 or older   Male             yes     no more than half an hr  0.12948714
8         40-49 Female              no     no                 none -0.45417133
19 less than 40   Male              no     no more than half an hr -0.84327698
22        50-59   Male              no     no more than half an hr  0.51859279
25 less than 40   Male             yes     no less than half an hr  0.32403997
29        40-49   Male              no     no less than half an hr  0.12948714
34 less than 40 Female              no     no more than half an hr  0.51859279
40        40-49   Male              no    yes                 none -0.84327698
45        40-49   Male             yes     no more than half an hr  1.68590974
47 less than 40   Male             yes     no       one hr or more -0.06506568
48  60 or older   Male             yes    yes more than half an hr  0.32403997
49  60 or older   Male             yes    yes less than half an hr  1.29680409
55 less than 40   Male             yes    yes       one hr or more  0.12948714
57  60 or older   Male              no    yes                 none  0.12948714
   Smoking Alcohol       Sleep SoundSleep RegularMedicine     JunkFood
4      yes     yes  0.01861803 -0.3304947              no occasionally
7       no     yes  0.78534240 -1.4153793             yes occasionally
8       no      no  0.01861803  0.7543900              no        often
19      no      no -1.51483072 -0.3304947              no   very often
22      no     yes  0.01861803 -0.8729370              no occasionally
25     yes     yes -0.74810634  0.2119477              no       always
29     yes      no  0.78534240  0.7543900              no occasionally
34      no      no -0.74810634 -0.3304947              no occasionally
40      no     yes  2.31879115  2.3817169              no occasionally
45      no      no  0.01861803 -0.3304947              no        often
47      no      no -1.51483072 -0.3304947              no occasionally
48      no      no -0.74810634 -0.3304947             yes occasionally
49      no      no  0.78534240  1.2968323              no        often
55     yes     yes -1.51483072 -0.8729370             yes        often
57      no      no -2.28155509 -0.8729370             yes occasionally
       Stress BPLevel Pregancies Pdiabetes UriationFreq Diabetic
4  not at all  normal -0.4201082         0     not much       no
7   sometimes  normal -0.4201082         0  quite often      yes
8  very often  normal  0.6799439         0     not much       no
19  sometimes  normal -0.4201082         0     not much       no
22  sometimes    high -0.4201082         0     not much       no
25  sometimes  normal -0.4201082         0  quite often       no
29  sometimes  normal -0.4201082         0     not much       no
34  sometimes  normal -0.4201082         0     not much       no
40  sometimes    high -0.4201082         0     not much      yes
45  sometimes  normal -0.4201082         0  quite often       no
47  sometimes  normal -0.4201082         0     not much       no
48  sometimes    high -0.4201082         0  quite often      yes
49 very often    high -0.4201082         0     not much      yes
55 not at all    high -0.4201082         0     not much      yes
57 not at all    high -0.4201082         0     not much      yes

Ahora disponemos de un conjunto de entrenamiento Train.diabet y un canjunto de validación val.diabet.

\[p_i = P(Y=1/X=x_i)=\frac{e^{\beta_0+\beta_1+...+\beta_k}}{1+e^{\beta_0+\beta_1+...+\beta_k}} \]

se trata de un modelo lineal logit.

Prediccion de la diabetes(binaria) y variable que influye en la misma.

Modelos de clasificacion

Regresion logistica

Trataremos de modelar la probabilidad de DIABETES positiva en funcion del resto de las variables.

El modelo logistico es:

gfit1 <- glm(Diabetic ~ .,family = binomial, data = diabetes2)
summary(gfit1)

Call:
glm(formula = Diabetic ~ ., family = binomial, data = diabetes2)

Deviance Residuals: 
    Min       1Q   Median       3Q      Max  
-2.2942  -0.3430  -0.1211   0.2687   3.0182  

Coefficients:
                                      Estimate Std. Error z value Pr(>|z|)    
(Intercept)                           -2.77088    1.08160  -2.562 0.010412 *  
Age50-59                               0.41120    0.36291   1.133 0.257177    
Age60 or older                         1.62408    0.41602   3.904 9.47e-05 ***
Ageless than 40                       -1.68936    0.43244  -3.907 9.36e-05 ***
GenderMale                             0.48706    0.37089   1.313 0.189105    
Family_Diabetesyes                     1.00920    0.25459   3.964 7.37e-05 ***
highBPyes                             -0.85083    0.38970  -2.183 0.029013 *  
PhysicallyActivemore than half an hr   0.55514    0.36247   1.532 0.125639    
PhysicallyActivenone                   0.85532    0.38718   2.209 0.027165 *  
PhysicallyActiveone hr or more         1.68317    0.37751   4.459 8.25e-06 ***
BMI                                    0.17735    0.12090   1.467 0.142372    
Smokingyes                             1.15528    0.50424   2.291 0.021955 *  
Alcoholyes                             0.09689    0.36237   0.267 0.789187    
Sleep                                  0.05861    0.15561   0.377 0.706443    
SoundSleep                             0.39536    0.18442   2.144 0.032045 *  
RegularMedicineyes                     2.97844    0.30926   9.631  < 2e-16 ***
JunkFoodoccasionally                   0.08808    0.84774   0.104 0.917245    
JunkFoodoften                          0.25582    0.83663   0.306 0.759775    
JunkFoodvery often                     0.04005    0.97557   0.041 0.967253    
Stressnot at all                      -0.03269    0.51891  -0.063 0.949776    
Stresssometimes                       -0.53932    0.39565  -1.363 0.172845    
Stressvery often                      -0.32951    0.45855  -0.719 0.472393    
BPLevellow                           -15.08888  758.75534  -0.020 0.984134    
BPLevelnormal                         -1.47618    0.39038  -3.781 0.000156 ***
Pregancies                             0.32210    0.14874   2.165 0.030350 *  
Pdiabetesyes                           4.01652    0.88504   4.538 5.67e-06 ***
UriationFreqquite often                0.43749    0.31153   1.404 0.160219    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 1091.56  on 905  degrees of freedom
Residual deviance:  491.38  on 879  degrees of freedom
AIC: 545.38

Number of Fisher Scoring iterations: 16
gfit0 <- glm(Diabetic~1, data = diabetes2,
             family = binomial)
anova(gfit0, gfit1, test = "Chisq")
Analysis of Deviance Table

Model 1: Diabetic ~ 1
Model 2: Diabetic ~ Age + Gender + Family_Diabetes + highBP + PhysicallyActive + 
    BMI + Smoking + Alcohol + Sleep + SoundSleep + RegularMedicine + 
    JunkFood + Stress + BPLevel + Pregancies + Pdiabetes + UriationFreq
  Resid. Df Resid. Dev Df Deviance  Pr(>Chi)    
1       905    1091.56                          
2       879     491.38 26   600.19 < 2.2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

La diferencia es altamente significatva, es decir el modelo con todas las variables es significativamente mejor que el modelo sólo con la constante. Mirando el test de wald para la significación de cada parámetro individual vemos que son altamente significativos los coeficientes para las variables: Age,Family_Diabetes, highBP, PhysicallyActive, Smoking,RegularMedicine, RegularMedicine, BPLevel, Pdiabetes. Esto quiere decir que el resto de las variables no aportan significativamente cuando las demás están presentes. Si queremos ver los efectos conjuntos de cada variable podemos usar el comando “anova en el que las

anova(gfit1, test = "Chisq")
Analysis of Deviance Table

Model: binomial, link: logit

Response: Diabetic

Terms added sequentially (first to last)

                 Df Deviance Resid. Df Resid. Dev  Pr(>Chi)    
NULL                               905    1091.56              
Age               3  279.374       902     812.19 < 2.2e-16 ***
Gender            1    7.079       901     805.11  0.007800 ** 
Family_Diabetes   1   46.025       900     759.09 1.168e-11 ***
highBP            1   23.832       899     735.25 1.051e-06 ***
PhysicallyActive  3   24.538       896     710.72 1.929e-05 ***
BMI               1    1.010       895     709.71  0.314887    
Smoking           1   21.493       894     688.21 3.552e-06 ***
Alcohol           1    2.266       893     685.95  0.132259    
Sleep             1    1.686       892     684.26  0.194122    
SoundSleep        1    0.413       891     683.85  0.520206    
RegularMedicine   1  123.729       890     560.12 < 2.2e-16 ***
JunkFood          3    1.505       887     558.61  0.681126    
Stress            3   11.452       884     547.16  0.009515 ** 
BPLevel           2   18.675       882     528.49 8.806e-05 ***
Pregancies        1    9.319       881     519.17  0.002268 ** 
Pdiabetes         1   25.815       880     493.35 3.758e-07 ***
UriationFreq      1    1.976       879     491.38  0.159819    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
gfit2 <- glm(Diabetic ~., data = Train.diabet, family = binomial)
cbind(gfit1$coefficients, gfit2$coefficients)
##                                              [,1]         [,2]
## (Intercept)                           -2.77087932  -1.74808262
## Age50-59                               0.41120398   0.59253917
## Age60 or older                         1.62408303   1.61214689
## Ageless than 40                       -1.68935773  -1.74881721
## GenderMale                             0.48706126   0.75499209
## Family_Diabetesyes                     1.00919861   1.10013745
## highBPyes                             -0.85082885  -1.34929812
## PhysicallyActivemore than half an hr   0.55513711   0.96937032
## PhysicallyActivenone                   0.85532299   1.24247791
## PhysicallyActiveone hr or more         1.68316752   1.65601454
## BMI                                    0.17735494   0.14903473
## Smokingyes                             1.15528381   1.46817871
## Alcoholyes                             0.09688630  -0.93616362
## Sleep                                  0.05860712   0.13708311
## SoundSleep                             0.39536387   0.24376942
## RegularMedicineyes                     2.97844459   3.18194151
## JunkFoodoccasionally                   0.08808372  -0.59620345
## JunkFoodoften                          0.25582142  -0.68203158
## JunkFoodvery often                     0.04005097  -0.80432089
## Stressnot at all                      -0.03268509  -0.09683845
## Stresssometimes                       -0.53932026  -0.66670031
## Stressvery often                      -0.32951273  -0.76141479
## BPLevellow                           -15.08887804 -15.55244810
## BPLevelnormal                         -1.47618023  -1.88078889
## Pregancies                             0.32210269   0.41273999
## Pdiabetesyes                           4.01651629   5.09624708
## UriationFreqquite often                0.43749258   0.41011844
p <- predict(gfit2, val.diabet, type = "response")
predDiabetic <- as.factor(p>0.5)
levels(predDiabetic) = c("no", "yes")
library(lattice)
library(caret)
Warning: package 'caret' was built under R version 4.2.3
matrizLogis <- confusionMatrix(val.diabet$Diabetic,predDiabetic);matrizLogis
Confusion Matrix and Statistics

          Reference
Prediction  no yes
       no  185  20
       yes  16  51
                                          
               Accuracy : 0.8676          
                 95% CI : (0.8215, 0.9056)
    No Information Rate : 0.739           
    P-Value [Acc > NIR] : 1.799e-07       
                                          
                  Kappa : 0.6506          
                                          
 Mcnemar's Test P-Value : 0.6171          
                                          
            Sensitivity : 0.9204          
            Specificity : 0.7183          
         Pos Pred Value : 0.9024          
         Neg Pred Value : 0.7612          
             Prevalence : 0.7390          
         Detection Rate : 0.6801          
   Detection Prevalence : 0.7537          
      Balanced Accuracy : 0.8194          
                                          
       'Positive' Class : no              
                                          

Tambien podemos dibujar la curva ROC para distintas probabilidades de corte. Un buen modelo tendrá un area bajo la curva alta.

library(pROC)
test_prob <- predict(gfit2, newdata = val.diabet, type = "response")
test_roc <- roc(val.diabet$Diabetic ~ test_prob, plot = T, print.auc = T)

Máaquinas de vector soporte

Otro modelo de clasificación, binaria es el conocido como “Support Vector Machine (Máquina de vector soporte). Los paquetes que ajustan los modelos de SVM es e1071 y LibLinear. Ajustamos el modelo para nuestros datos con el kernel radial que es el que se usa por defecto.