#ĐỀ TÀI: PHÂN TÍCH CHẤT LƯỢNG NƯỚC

I. TIỀN XỬ LÝ SỐ LIỆU

#Đọc dữ liệu
water_potability <- read.csv("water_potability.csv", row.names = NULL)
head(water_potability,10)
##           ph Hardness   Solids Chloramines  Sulfate Conductivity Organic_carbon
## 1         NA 204.8905 20791.32    7.300212 368.5164     564.3087      10.379783
## 2   3.716080 129.4229 18630.06    6.635246       NA     592.8854      15.180013
## 3   8.099124 224.2363 19909.54    9.275884       NA     418.6062      16.868637
## 4   8.316766 214.3734 22018.42    8.059332 356.8861     363.2665      18.436524
## 5   9.092223 181.1015 17978.99    6.546600 310.1357     398.4108      11.558279
## 6   5.584087 188.3133 28748.69    7.544869 326.6784     280.4679       8.399735
## 7  10.223862 248.0717 28749.72    7.513408 393.6634     283.6516      13.789695
## 8   8.635849 203.3615 13672.09    4.563009 303.3098     474.6076      12.363817
## 9         NA 118.9886 14285.58    7.804174 268.6469     389.3756      12.706049
## 10 11.180284 227.2315 25484.51    9.077200 404.0416     563.8855      17.927806
##    Trihalomethanes Turbidity Potability
## 1         86.99097  2.963135          0
## 2         56.32908  4.500656          0
## 3         66.42009  3.055934          0
## 4        100.34167  4.628771          0
## 5         31.99799  4.075075          0
## 6         54.91786  2.559708          0
## 7         84.60356  2.672989          0
## 8         62.79831  4.401425          0
## 9         53.92885  3.595017          0
## 10        71.97660  4.370562          0

Ta tiến hành tìm và xử lý các dữ liệu khuyết

#Tìm dữ liệu khuyết
library(questionr)
freq.na(water_potability)
##                 missing  %
## Sulfate             781 24
## ph                  491 15
## Trihalomethanes     162  5
## Hardness              0  0
## Solids                0  0
## Chloramines           0  0
## Conductivity          0  0
## Organic_carbon        0  0
## Turbidity             0  0
## Potability            0  0

Ta kiểm tra phân phối của các biến có dữ liệu khuyết bằng đồ thị Histogram để tìm ra phương pháp xử lý các dữ liệu khuyết

#Kiểm tra phân phối các biến chứa dữ liệu khuyết
#. ph
hist(water_potability$ph[!is.na(water_potability$ph)],
     main = "Histogram of pH (without NA)",
     xlab = "pH",
     col = "#EAD7C0",
     border = "#3B2F2F",)

#. Sulfate
hist(water_potability$Sulfate[!is.na(water_potability$Sulfate)],
     main = "Histogram of Sulfate (without NA)",
     xlab = "Sulfate",
     col = "#EAD7C0",
     border = "#3B2F2F")

#. Trihalomethanes
hist(water_potability$Trihalomethanes[!is.na(water_potability$Trihalomethanes)],
     main = "Histogram of Trihalomethanes (without NA)",
     xlab = "Trihalomethanes",
     col = "#EAD7C0",
     border = "#3B2F2F")

Dựa vào phân phối ta sẽ dùng phương pháp thay thế các dữ liệu khuyết bằng dữ liệu trungvị

#Thay thế các dữ liệu khuyết bằng giá trị trung bình
#. ph
median(water_potability$ph,na.rm=TRUE)
## [1] 7.036752
#Sulfate
median(water_potability$Sulfate,na.rm=TRUE)
## [1] 333.0735
#Trihalomethanes
median(water_potability$Trihalomethanes,na.rm=TRUE)
## [1] 66.62249
#Thay giá trị vào các biến
water_potability$ph[is.na(water_potability$ph)]<-median(water_potability$ph,na.rm=TRUE)
water_potability$Sulfate[is.na(water_potability$Sulfate)]<-median(water_potability$Sulfate,na.rm=TRUE)
water_potability$Trihalomethanes[is.na(water_potability$Trihalomethanes)]<-median(water_potability$Trihalomethanes,na.rm=TRUE)
#Đọc dữ liệu mới và kiểm tra lại
head(water_potability,10)
##           ph Hardness   Solids Chloramines  Sulfate Conductivity Organic_carbon
## 1   7.036752 204.8905 20791.32    7.300212 368.5164     564.3087      10.379783
## 2   3.716080 129.4229 18630.06    6.635246 333.0735     592.8854      15.180013
## 3   8.099124 224.2363 19909.54    9.275884 333.0735     418.6062      16.868637
## 4   8.316766 214.3734 22018.42    8.059332 356.8861     363.2665      18.436524
## 5   9.092223 181.1015 17978.99    6.546600 310.1357     398.4108      11.558279
## 6   5.584087 188.3133 28748.69    7.544869 326.6784     280.4679       8.399735
## 7  10.223862 248.0717 28749.72    7.513408 393.6634     283.6516      13.789695
## 8   8.635849 203.3615 13672.09    4.563009 303.3098     474.6076      12.363817
## 9   7.036752 118.9886 14285.58    7.804174 268.6469     389.3756      12.706049
## 10 11.180284 227.2315 25484.51    9.077200 404.0416     563.8855      17.927806
##    Trihalomethanes Turbidity Potability
## 1         86.99097  2.963135          0
## 2         56.32908  4.500656          0
## 3         66.42009  3.055934          0
## 4        100.34167  4.628771          0
## 5         31.99799  4.075075          0
## 6         54.91786  2.559708          0
## 7         84.60356  2.672989          0
## 8         62.79831  4.401425          0
## 9         53.92885  3.595017          0
## 10        71.97660  4.370562          0
library(questionr)
freq.na(water_potability)
##                 missing %
## ph                    0 0
## Hardness              0 0
## Solids                0 0
## Chloramines           0 0
## Sulfate               0 0
## Conductivity          0 0
## Organic_carbon        0 0
## Trihalomethanes       0 0
## Turbidity             0 0
## Potability            0 0
  1. THỐNG KÊ MÔ TẢ Ta thống kê các giá trị của các biến
#Tính toán các giá trị thống kê của các biến liên tục
cons_data <- water_potability[,c("ph","Hardness","Solids","Chloramines",
"Sulfate","Conductivity","Organic_carbon","Trihalomethanes","Turbidity")]
trungbinh<-apply(cons_data,2,mean)
trungvi<-apply(cons_data,2,median)
dolechchuan<-apply(cons_data,2,sd)
phanvi1<-apply(cons_data,2,quantile,probs=0.25)
phanvi3<-apply(cons_data,2,quantile,probs=0.75)
GTLN<-apply(cons_data,2,max)
GTNN<-apply(cons_data,2,min)
t(data.frame(trungbinh,trungvi,dolechchuan,phanvi1,phanvi3,GTLN,GTNN))
##                    ph  Hardness     Solids Chloramines   Sulfate Conductivity
## trungbinh    7.074194 196.36950 22014.0925    7.122277 333.60836    426.20511
## trungvi      7.036752 196.96763 20927.8336    7.130299 333.07355    421.88497
## dolechchuan  1.470040  32.87976  8768.5708    1.583085  36.14385     80.82406
## phanvi1      6.277673 176.85054 15666.6903    6.127421 317.09464    365.73441
## phanvi3      7.870050 216.66746 27332.7621    8.114887 350.38576    481.79230
## GTLN        14.000000 323.12400 61227.1960   13.127000 481.03064    753.34262
## GTNN         0.000000  47.43200   320.9426    0.352000 129.00000    181.48375
##             Organic_carbon Trihalomethanes Turbidity
## trungbinh        14.284970        66.40748 3.9667862
## trungvi          14.218338        66.62249 3.9550276
## dolechchuan       3.308162        15.76996 0.7803824
## phanvi1          12.065801        56.64766 3.4397109
## phanvi3          16.557652        76.66661 4.5003198
## GTLN             28.300000       124.00000 6.7390000
## GTNN              2.200000         0.73800 1.4500000
#Thống kê biến phân loại
table(water_potability$Potability)
## 
##    0    1 
## 1998 1278

Ta vẽ đồ thị cho các biến liên tục

#Gom 3 hình vào 1 trang
par(mfrow=c(1,3))
#Đồ thị Histogram 
#. ph
hist(water_potability$ph,
     main = "Histogram of pH",
     xlab = "pH",
     col = "#FFDFE5",
     border = "#2E0854",
     labels = TRUE)
#. Hardness
hist(water_potability$Hardness,
     main = "Histogram of Hardness",
     xlab = "Hardness",
     col = "#FFDFE5",
     border = "#2E0854",
     labels = TRUE)
#. Solids
hist(water_potability$Solids,
     main = "Histogram of Solids",
     xlab = "Solids",
     col = "#FFDFE5",
     border = "#2E0854",
     labels = TRUE)

#. Chloramines
hist(water_potability$Chloramines,
     main = "Histogram of Chloramines",
     xlab = "Chloramines",
     col = "#FFDFE5",
     border = "#2E0854",
     labels = TRUE)
#. ĐSulfate
hist(water_potability$Sulfate,
     main = "Histogram of Sulfate",
     xlab = "Sulfate",
     col = "#FFDFE5",
     border = "#2E0854",
     labels = TRUE)
#. Conductivity
hist(water_potability$Conductivity,
     main = "Histogram of Conductivity",
     xlab = "Conductivity",
     col = "#FFDFE5",
     border = "#2E0854",
     labels = TRUE)

#.  Organic_carbon
hist(water_potability$Organic_carbon,
     main = "Histogram of Organic_carbon",
     xlab = "Organic_carbon",
     col = "#FFDFE5",
     border = "#2E0854",
     labels = TRUE)
#. Trihalomethanes
hist(water_potability$Trihalomethanes,
     main = "Histogram of Trihalomethanes",
     xlab = "Trihalomethanes",
     col = "#FFDFE5",
     border = "#2E0854",
     labels = TRUE)
#. Turbidity
hist(water_potability$Turbidity,
     main = "Histogram of Turbidity",
     xlab = "Turbidity",
     col = "#FFDFE5",
     border = "#2E0854",
     labels = TRUE)

#Đồ thị Boxplot
#. ph
boxplot(ph~Potability,data=water_potability,
        main="Boxplot of pH for Potability", 
        col=c("#C6E7FF","#FFCF9D"), 
        border=c("#003161","#CC2B52"))
#. Hardness
boxplot(Hardness~Potability,data=water_potability,
        main="Boxplot of Hardness for Potability", 
        col=c("#C6E7FF","#FFCF9D"), 
        border=c("#003161","#CC2B52"))
#. Solids
boxplot(Solids~Potability,data=water_potability,
        main="Boxplot of Solids for Potability", 
        col=c("#C6E7FF","#FFCF9D"), 
        border=c("#003161","#CC2B52"))

#. Chloramines
boxplot(Chloramines~Potability,data=water_potability,
        main="Boxplot of Chloramines for Potability", 
        col=c("#C6E7FF","#FFCF9D"), 
        border=c("#003161","#CC2B52"))
#. Sulfate
boxplot(Sulfate~Potability,data=water_potability,
        main="Boxplot of Sulfate for Potability", 
        col=c("#C6E7FF","#FFCF9D"), 
        border=c("#003161","#CC2B52"))
#. Conductivity
boxplot(Conductivity~Potability,data=water_potability,
        main="Boxplot of Conductivity for Potability", 
        col=c("#C6E7FF","#FFCF9D"), 
        border=c("#003161","#CC2B52"))

#. Organic_carbon
boxplot(Organic_carbon~Potability,data=water_potability,
        main="Boxplot of Organic_carbon for Potability", 
        col=c("#C6E7FF","#FFCF9D"), 
        border=c("#003161","#CC2B52"))
#. Trihalomethanes
boxplot(Trihalomethanes~Potability,data=water_potability,
        main="Boxplot of Trihalomethanes for Potability", 
        col=c("#C6E7FF","#FFCF9D"), 
        border=c("#003161","#CC2B52"))
#. Turbidity
boxplot(Turbidity~Potability,data=water_potability,
        main="Boxplot of pH for Potability", 
        col=c("#C6E7FF","#FFCF9D"), 
        border=c("#003161","#CC2B52"))

  1. THỐNG KÊ SUY DIỄN Ta kiểm tra các biến liên tục có phụ thuộc vào nhau không
#Đồ thị corrplot
cor(cons_data)
##                           ph    Hardness       Solids  Chloramines      Sulfate
## ph               1.000000000  0.07576030 -0.082004177 -0.031740701  0.014178441
## Hardness         0.075760303  1.00000000 -0.046899365 -0.030054239 -0.092833198
## Solids          -0.082004177 -0.04689937  1.000000000 -0.070147580 -0.149747347
## Chloramines     -0.031740701 -0.03005424 -0.070147580  1.000000000  0.023761688
## Sulfate          0.014178441 -0.09283320 -0.149747347  0.023761688  1.000000000
## Conductivity     0.017465717 -0.02391460  0.013830898 -0.020486409 -0.014182379
## Organic_carbon   0.040240175  0.00361004  0.010242343 -0.012653471  0.027102173
## Trihalomethanes  0.003145084 -0.01270674 -0.008798626  0.016614101 -0.025657186
## Turbidity       -0.036106998 -0.01444913  0.019546144  0.002363321 -0.009767387
##                 Conductivity Organic_carbon Trihalomethanes    Turbidity
## ph               0.017465717     0.04024018     0.003145084 -0.036106998
## Hardness        -0.023914600     0.00361004    -0.012706744 -0.014449129
## Solids           0.013830898     0.01024234    -0.008798626  0.019546144
## Chloramines     -0.020486409    -0.01265347     0.016614101  0.002363321
## Sulfate         -0.014182379     0.02710217    -0.025657186 -0.009767387
## Conductivity     1.000000000     0.02096636     0.001184083  0.005798168
## Organic_carbon   0.020966361     1.00000000    -0.012958281 -0.027308113
## Trihalomethanes  0.001184083    -0.01295828     1.000000000 -0.021486733
## Turbidity        0.005798168    -0.02730811    -0.021486733  1.000000000
library(corrplot)
## corrplot 0.95 loaded
corrplot(cor(cons_data),
        method = "color",
        addCoef.col = TRUE,number.cex=0.7,
        type = "upper")

Kết luận các biến đôi một độc lập

  1. ANOVA 2 yếu tố

Ta sẽ xét ảnh hưởng của Turbidity và Sulfate lên Organic_carbon để xem các mối liên hệ hóa họ. Do phương pháp ANOVA yêu cầu các biến độc lập phải ở dạng biến phân loại, nên hai biến liên tục Turbidity và Sulfate được chuyển thành các nhóm (Low, Medium, High)

#Tạo 2 biến phân loại
water_potability$Turbidity_group <- cut(water_potability$Turbidity,
                                 breaks = c(-Inf, 3.5, 4.5, Inf),
                                 labels = c("Low", "Medium", "High"))
water_potability$Sulfate_group <- cut(water_potability$Sulfate,
                                      breaks = c(-Inf, 300, 340, Inf),
                                      labels = c("Low", "Medium", "High"))
#Kiểm tra phân bố số lượng 2 biến phân loại mới
table(water_potability$Turbidity_group)
## 
##    Low Medium   High 
##    900   1556    820
table(water_potability$Sulfate_group)
## 
##    Low Medium   High 
##    474   1747   1055
table(water_potability$Turbidity_group,water_potability$Sulfate_group)
##         
##          Low Medium High
##   Low    136    456  308
##   Medium 210    846  500
##   High   128    445  247

Kiểm tra phân phối chuẩn của của Organic_carbon dựa trên 2 biến Turbidity và Sulfate

by(water_potability$Organic_carbon, list(water_potability$Turbidity_group, water_potability$Sulfate_group), shapiro.test)
## : Low
## : Low
## 
##  Shapiro-Wilk normality test
## 
## data:  dd[x, ]
## W = 0.98935, p-value = 0.3842
## 
## ------------------------------------------------------------ 
## : Medium
## : Low
## 
##  Shapiro-Wilk normality test
## 
## data:  dd[x, ]
## W = 0.99359, p-value = 0.5014
## 
## ------------------------------------------------------------ 
## : High
## : Low
## 
##  Shapiro-Wilk normality test
## 
## data:  dd[x, ]
## W = 0.99421, p-value = 0.8832
## 
## ------------------------------------------------------------ 
## : Low
## : Medium
## 
##  Shapiro-Wilk normality test
## 
## data:  dd[x, ]
## W = 0.9954, p-value = 0.1981
## 
## ------------------------------------------------------------ 
## : Medium
## : Medium
## 
##  Shapiro-Wilk normality test
## 
## data:  dd[x, ]
## W = 0.99759, p-value = 0.2566
## 
## ------------------------------------------------------------ 
## : High
## : Medium
## 
##  Shapiro-Wilk normality test
## 
## data:  dd[x, ]
## W = 0.99683, p-value = 0.5376
## 
## ------------------------------------------------------------ 
## : Low
## : High
## 
##  Shapiro-Wilk normality test
## 
## data:  dd[x, ]
## W = 0.99479, p-value = 0.3817
## 
## ------------------------------------------------------------ 
## : Medium
## : High
## 
##  Shapiro-Wilk normality test
## 
## data:  dd[x, ]
## W = 0.99665, p-value = 0.3862
## 
## ------------------------------------------------------------ 
## : High
## : High
## 
##  Shapiro-Wilk normality test
## 
## data:  dd[x, ]
## W = 0.99185, p-value = 0.1886

Kết luận: Có phân phối chuẩn do tất cả các p_value>0.05

Đánh giá giả định phương sai bằng nhau

library(car)
## Loading required package: carData
leveneTest(Organic_carbon ~ Turbidity_group * Sulfate_group,
           data = water_potability)
## Levene's Test for Homogeneity of Variance (center = median)
##         Df F value Pr(>F)
## group    8  0.7569 0.6411
##       3267

Kết luận: thỏa mãn giả định phương sai bằng nhau

Tiến hành xây dựng mô hình ANOVA với biến phụ thuộc là Organic_carbon và 2 biến độc lập là Turbidity và Sulfate

anova_model <- aov(Organic_carbon ~ Turbidity_group * Sulfate_group,
                   data = water_potability)
summary(anova_model)
##                                 Df Sum Sq Mean Sq F value Pr(>F)  
## Turbidity_group                  2     66   32.99   3.021 0.0489 *
## Sulfate_group                    2     74   37.15   3.401 0.0334 *
## Turbidity_group:Sulfate_group    4     22    5.61   0.514 0.7258  
## Residuals                     3267  35679   10.92                 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Ta thấy cả 2 biến đều ảnh hưởng đến Organic_carbon nên tiến hành phân tích sâu cả 2 biến bằng TurkeyHSD

TukeyHSD(anova_model, "Turbidity_group")
##   Tukey multiple comparisons of means
##     95% family-wise confidence level
## 
## Fit: aov(formula = Organic_carbon ~ Turbidity_group * Sulfate_group, data = water_potability)
## 
## $Turbidity_group
##                   diff        lwr         upr     p adj
## Medium-Low   0.1246975 -0.1998054  0.44920030 0.6396857
## High-Low    -0.2257979 -0.5998796  0.14828373 0.3330530
## High-Medium -0.3504954 -0.6848766 -0.01611417 0.0373324
TukeyHSD(anova_model, "Sulfate_group")
##   Tukey multiple comparisons of means
##     95% family-wise confidence level
## 
## Fit: aov(formula = Organic_carbon ~ Turbidity_group * Sulfate_group, data = water_potability)
## 
## $Sulfate_group
##                     diff           lwr       upr     p adj
## Medium-Low  0.4277392433  0.0264393523 0.8290391 0.0334247
## High-Low    0.4282104085 -0.0002579225 0.8566787 0.0501786
## High-Medium 0.0004711652 -0.3016573865 0.3025997 0.9999926

Kết luận: p_value < 0.05 thì ảnh hưởng - Biến Turbidity: Organic_carbon thay đổi khi Turbidity thay đổi từ mức Medium tới High. 2 cái còn lại không ảnh hưởng - Biến Sulfate: Organic_carbon thay đổi khi Sulfate thay đổi từ mức Low tới Medium. 2 cái còn lại không ảnh hưởng

Ta tiến hành chia dữ liệu thành 2 phần theo tỉ lệ Thống kê:Kiểm tra = 7:3

#Cố định dữ liệu 
set.seed(8)
#Tạo tập tin thống kê và xuất số dòng ra màn hình
train_index <- sample(1:nrow(water_potability),0.7 * nrow(water_potability))
train_data <- water_potability[train_index,]
dim(train_data)
## [1] 2293   12
#Tạo tập tin kiểm tra
test_data <- water_potability[-train_index,]
dim(test_data)
## [1] 983  12

Thống kê tần số của biến Potability trong tập train

table(train_data$Potability)
## 
##    0    1 
## 1414  879

Kết quả cho thấy trong tập train, số lượng Potability = 0 (1414) lớn hơn Potability = 1 (879), cho thấy dữ liệu có mất cân bằng nhẹ giữa hai lớp. Để cải thiện khả năng dự đoán cho lớp thiểu số (Potability = 1), tiến hành gán trọng số lớn hơn cho lớp này. Cụ thể:

weights <- ifelse(train_data$Potability == 1, 1414/879, 1)

Mô hình hồi quy Logistic

logistic_model<-glm(Potability~ph+Hardness+Solids+Chloramines+Sulfate+Conductivity+Organic_carbon+Trihalomethanes+Turbidity,data=train_data,family="binomial", weights = weights)
## Warning in eval(family$initialize): non-integer #successes in a binomial glm!
summary(logistic_model)
## 
## Call:
## glm(formula = Potability ~ ph + Hardness + Solids + Chloramines + 
##     Sulfate + Conductivity + Organic_carbon + Trihalomethanes + 
##     Turbidity, family = "binomial", data = train_data, weights = weights)
## 
## Coefficients:
##                   Estimate Std. Error z value Pr(>|z|)    
## (Intercept)      4.500e-02  6.378e-01   0.071 0.943760    
## ph               1.556e-02  2.616e-02   0.595 0.551805    
## Hardness        -1.546e-03  1.161e-03  -1.332 0.182957    
## Solids           1.467e-05  4.419e-06   3.320 0.000899 ***
## Chloramines      4.022e-02  2.347e-02   1.713 0.086674 .  
## Sulfate         -7.537e-04  1.028e-03  -0.733 0.463629    
## Conductivity     3.173e-04  4.681e-04   0.678 0.497898    
## Organic_carbon  -2.319e-02  1.141e-02  -2.031 0.042212 *  
## Trihalomethanes  2.431e-04  2.389e-03   0.102 0.918946    
## Turbidity       -8.680e-03  4.759e-02  -0.182 0.855292    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 3920.4  on 2292  degrees of freedom
## Residual deviance: 3898.6  on 2283  degrees of freedom
## AIC: 4393.2
## 
## Number of Fisher Scoring iterations: 4

Lựa chọn mô hình phù hợp

goat_model<-glm(Potability~Solids+Organic_carbon,data=train_data,family="binomial", weights = weights)
## Warning in eval(family$initialize): non-integer #successes in a binomial glm!
summary(goat_model)
## 
## Call:
## glm(formula = Potability ~ Solids + Organic_carbon, family = "binomial", 
##     data = train_data, weights = weights)
## 
## Coefficients:
##                  Estimate Std. Error z value Pr(>|z|)    
## (Intercept)    -3.997e-03  1.888e-01  -0.021 0.983114    
## Solids          1.493e-05  4.315e-06   3.459 0.000542 ***
## Organic_carbon -2.293e-02  1.138e-02  -2.016 0.043842 *  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 3920.4  on 2292  degrees of freedom
## Residual deviance: 3904.7  on 2290  degrees of freedom
## AIC: 4385.7
## 
## Number of Fisher Scoring iterations: 4

Kết luận AIC nhỏ hơn mô hình ban đầu

Dự báo test_data

# Dự báo
predicted <- predict(goat_model, test_data, type = "response")
test_data$predicted <- ifelse(predicted > 0.5, 1, 0)
head(test_data, 10)
##           ph Hardness   Solids Chloramines  Sulfate Conductivity Organic_carbon
## 10 11.180284 227.2315 25484.51    9.077200 404.0416     563.8855      17.927806
## 12  7.974522 218.6933 18767.66    8.110385 333.0735     364.0982      14.525746
## 20  7.371050 214.4966 25630.32    4.432669 335.7544     469.9146      12.509164
## 22  6.660212 168.2837 30944.36    5.858769 310.9309     523.6713      17.884235
## 29  7.036752 266.4210 26362.97    7.700063 395.3895     364.4801      10.348951
## 36  5.115817 191.9527 19620.55    6.060713 323.8364     441.7484      10.966486
## 37  3.641630 183.9087 24752.07    5.538314 286.0596     456.8601       9.034067
## 41  7.036752 233.8590 11703.92    4.599388 309.0393     349.3996      18.338893
## 45  4.758439 183.3495 21568.43    4.731349 333.0735     403.9442      18.668229
## 46  5.702926 216.8505 35606.44    7.184351 333.0735     504.6383      16.140790
##    Trihalomethanes Turbidity Potability Turbidity_group Sulfate_group predicted
## 10        71.97660  4.370562          0          Medium          High         0
## 12        76.48591  4.011718          0          Medium        Medium         0
## 20        62.79728  2.560299          0             Low        Medium         1
## 22        77.04232  3.749701          0          Medium        Medium         1
## 29        53.00838  3.991564          0          Medium          High         1
## 36        49.23823  3.902089          0          Medium        Medium         1
## 37        73.59466  3.464353          0             Low           Low         1
## 41        42.67747  3.510004          0          Medium        Medium         0
## 45        66.91240  4.542801          0            High        Medium         0
## 46        77.53618  4.137739          0          Medium        Medium         1
#xuất kết quả dự báo
library(caret)
## Loading required package: ggplot2
## Loading required package: lattice
confusionMatrix(as.factor(test_data$predicted),as.factor(test_data$Potability),positive = "1")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction   0   1
##          0 297 221
##          1 287 178
##                                          
##                Accuracy : 0.4832         
##                  95% CI : (0.4516, 0.515)
##     No Information Rate : 0.5941         
##     P-Value [Acc > NIR] : 1.000000       
##                                          
##                   Kappa : -0.0442        
##                                          
##  Mcnemar's Test P-Value : 0.003928       
##                                          
##             Sensitivity : 0.4461         
##             Specificity : 0.5086         
##          Pos Pred Value : 0.3828         
##          Neg Pred Value : 0.5734         
##              Prevalence : 0.4059         
##          Detection Rate : 0.1811         
##    Detection Prevalence : 0.4730         
##       Balanced Accuracy : 0.4773         
##                                          
##        'Positive' Class : 1              
## 

Kết luận về Accuracy, Sensitivity, Specificity

Vẽ đường cong ROC

library(pROC)
## Type 'citation("pROC")' for a citation.
## 
## Attaching package: 'pROC'
## The following objects are masked from 'package:stats':
## 
##     cov, smooth, var
roc_curve <- roc(test_data$Potability, predicted)
## Setting levels: control = 0, case = 1
## Setting direction: controls > cases
plot(roc_curve, col="#5D3A9B", lwd=2, main="ROC Curve - Logistic Regression")
abline(a=0, b=1, lty=2, col="#F6A5A5")  

Kết luận về đường cong

Tính AUC

auc_value <- auc(roc_curve)
print(paste("AUC:", round(auc_value,3)))
## [1] "AUC: 0.523"

Kết luận về giá trị AUC

Kiểm tra các giả định khác

library(car)        # VIF
library(lmtest)     # bptest, dwtest
## Loading required package: zoo
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric

Kiểm tra hiện tượng đa cộng tuyến

vif(goat_model)
##         Solids Organic_carbon 
##       1.001055       1.001055
#. Biểu đồ Leverage và Residual
plot(goat_model, which = 5) #(which = 5 là loại biểu đồ Leverage và Residual)

Kết luận: không có đa cộng tuyến

Kiểm tra tuyến tính giữa biến Solids với log(odds) và Organic_carbon với log(odds)

#Solids
plot(train_data$Solids, 
     log(goat_model$fitted.values / (1 - goat_model$fitted.values)),
     main = "Linearity check: Solids vs log-odds",
     xlab = "Solids", ylab = "log-odds")

#Organic_carbon
plot(train_data$Organic_carbon, 
     log(goat_model$fitted.values / (1 - goat_model$fitted.values)),
     main = "Linearity check: Organic_carbon vs log-odds",
     xlab = "Organic_carbon", ylab = "log-odds")

Kết luận: Solids tuyến tính rõ ràng, Organic_carbon gần tuyến tính và không có dấu hiệu phi tuyến mạnh

  1. MỞ RỘNG

Mô hình Decision_Tree