# Nạp dataset Iris có sẵn trong R
data(iris)

# Xem trước dữ liệu
head(iris)
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1          5.1         3.5          1.4         0.2  setosa
## 2          4.9         3.0          1.4         0.2  setosa
## 3          4.7         3.2          1.3         0.2  setosa
## 4          4.6         3.1          1.5         0.2  setosa
## 5          5.0         3.6          1.4         0.2  setosa
## 6          5.4         3.9          1.7         0.4  setosa
# Chọn biến đầu vào và đầu ra
X <- iris$Petal.Length  # Biến độc lập
y <- iris$Petal.Width   # Biến phụ thuộc
# Chạy mô hình hồi quy tuyến tính
model <- lm(y ~ X, data = iris)

# Hiển thị kết quả
summary(model)
## 
## Call:
## lm(formula = y ~ X, data = iris)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -0.56515 -0.12358 -0.01898  0.13288  0.64272 
## 
## Coefficients:
##              Estimate Std. Error t value Pr(>|t|)    
## (Intercept) -0.363076   0.039762  -9.131  4.7e-16 ***
## X            0.415755   0.009582  43.387  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.2065 on 148 degrees of freedom
## Multiple R-squared:  0.9271, Adjusted R-squared:  0.9266 
## F-statistic:  1882 on 1 and 148 DF,  p-value: < 2.2e-16
# Dự đoán giá trị
predictions <- predict(model)

# Tính MAE (Mean Absolute Error)
mae <- mean(abs(predictions - y))

# In kết quả MAE
print(paste("Mean Absolute Error (MAE):", mae))
## [1] "Mean Absolute Error (MAE): 0.156470513710141"
# Vẽ biểu đồ scatter plot
plot(X, y, main="Hồi quy Petal.Width ~ Petal.Length",
     xlab="Petal.Length", ylab="Petal.Width", pch=19, col="blue")

# Vẽ đường hồi quy
abline(model, col="red", lwd=2)

library(readr)

# Tải lại dữ liệu từ UCI
heart_data <- read_csv("https://archive.ics.uci.edu/ml/machine-learning-databases/heart-disease/processed.cleveland.data", 
                       col_names = FALSE, na = "?")  # Xử lý giá trị '?' thành NA
## Rows: 303 Columns: 14
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## dbl (14): X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X12, X13, X14
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
# Đặt tên cột chính xác theo mô tả của UCI
colnames(heart_data) <- c("age", "sex", "cp", "trestbps", "chol", "fbs", 
                          "restecg", "thalach", "exang", "oldpeak", "slope", 
                          "ca", "thal", "target")

# Chuyển các cột bị lỗi (ca, thal) về kiểu số
heart_data$ca <- as.numeric(heart_data$ca)
heart_data$thal <- as.numeric(heart_data$thal)

# Kiểm tra dữ liệu
str(heart_data)
## spc_tbl_ [303 × 14] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
##  $ age     : num [1:303] 63 67 67 37 41 56 62 57 63 53 ...
##  $ sex     : num [1:303] 1 1 1 1 0 1 0 0 1 1 ...
##  $ cp      : num [1:303] 1 4 4 3 2 2 4 4 4 4 ...
##  $ trestbps: num [1:303] 145 160 120 130 130 120 140 120 130 140 ...
##  $ chol    : num [1:303] 233 286 229 250 204 236 268 354 254 203 ...
##  $ fbs     : num [1:303] 1 0 0 0 0 0 0 0 0 1 ...
##  $ restecg : num [1:303] 2 2 2 0 2 0 2 0 2 2 ...
##  $ thalach : num [1:303] 150 108 129 187 172 178 160 163 147 155 ...
##  $ exang   : num [1:303] 0 1 1 0 0 0 0 1 0 1 ...
##  $ oldpeak : num [1:303] 2.3 1.5 2.6 3.5 1.4 0.8 3.6 0.6 1.4 3.1 ...
##  $ slope   : num [1:303] 3 2 2 3 1 1 3 1 2 3 ...
##  $ ca      : num [1:303] 0 3 2 0 0 0 2 0 1 0 ...
##  $ thal    : num [1:303] 6 3 7 3 3 3 3 3 7 7 ...
##  $ target  : num [1:303] 0 2 1 0 0 0 3 0 2 1 ...
##  - attr(*, "spec")=
##   .. cols(
##   ..   X1 = col_double(),
##   ..   X2 = col_double(),
##   ..   X3 = col_double(),
##   ..   X4 = col_double(),
##   ..   X5 = col_double(),
##   ..   X6 = col_double(),
##   ..   X7 = col_double(),
##   ..   X8 = col_double(),
##   ..   X9 = col_double(),
##   ..   X10 = col_double(),
##   ..   X11 = col_double(),
##   ..   X12 = col_double(),
##   ..   X13 = col_double(),
##   ..   X14 = col_double()
##   .. )
##  - attr(*, "problems")=<externalptr>
summary(heart_data)
##       age             sex               cp           trestbps    
##  Min.   :29.00   Min.   :0.0000   Min.   :1.000   Min.   : 94.0  
##  1st Qu.:48.00   1st Qu.:0.0000   1st Qu.:3.000   1st Qu.:120.0  
##  Median :56.00   Median :1.0000   Median :3.000   Median :130.0  
##  Mean   :54.44   Mean   :0.6799   Mean   :3.158   Mean   :131.7  
##  3rd Qu.:61.00   3rd Qu.:1.0000   3rd Qu.:4.000   3rd Qu.:140.0  
##  Max.   :77.00   Max.   :1.0000   Max.   :4.000   Max.   :200.0  
##                                                                  
##       chol            fbs            restecg          thalach     
##  Min.   :126.0   Min.   :0.0000   Min.   :0.0000   Min.   : 71.0  
##  1st Qu.:211.0   1st Qu.:0.0000   1st Qu.:0.0000   1st Qu.:133.5  
##  Median :241.0   Median :0.0000   Median :1.0000   Median :153.0  
##  Mean   :246.7   Mean   :0.1485   Mean   :0.9901   Mean   :149.6  
##  3rd Qu.:275.0   3rd Qu.:0.0000   3rd Qu.:2.0000   3rd Qu.:166.0  
##  Max.   :564.0   Max.   :1.0000   Max.   :2.0000   Max.   :202.0  
##                                                                   
##      exang           oldpeak         slope             ca        
##  Min.   :0.0000   Min.   :0.00   Min.   :1.000   Min.   :0.0000  
##  1st Qu.:0.0000   1st Qu.:0.00   1st Qu.:1.000   1st Qu.:0.0000  
##  Median :0.0000   Median :0.80   Median :2.000   Median :0.0000  
##  Mean   :0.3267   Mean   :1.04   Mean   :1.601   Mean   :0.6722  
##  3rd Qu.:1.0000   3rd Qu.:1.60   3rd Qu.:2.000   3rd Qu.:1.0000  
##  Max.   :1.0000   Max.   :6.20   Max.   :3.000   Max.   :3.0000  
##                                                  NA's   :4       
##       thal           target      
##  Min.   :3.000   Min.   :0.0000  
##  1st Qu.:3.000   1st Qu.:0.0000  
##  Median :3.000   Median :0.0000  
##  Mean   :4.734   Mean   :0.9373  
##  3rd Qu.:7.000   3rd Qu.:2.0000  
##  Max.   :7.000   Max.   :4.0000  
##  NA's   :2
heart_data$target <- ifelse(heart_data$target > 0, 1, 0)

# Chuyển một số biến thành dạng factor (danh mục)
heart_data$sex <- as.factor(heart_data$sex)
heart_data$fbs <- as.factor(heart_data$fbs)
heart_data$exang <- as.factor(heart_data$exang)
heart_data$target <- as.factor(heart_data$target)

# Kiểm tra lại
table(heart_data$target)
## 
##   0   1 
## 164 139
set.seed(123)  # Đảm bảo kết quả có thể tái lập
library(caret)
## Loading required package: ggplot2
## Loading required package: lattice
# Chia dữ liệu (70% train, 30% test)
splitIndex <- createDataPartition(heart_data$target, p = 0.7, list = FALSE)
train_data <- heart_data[splitIndex, ]
test_data <- heart_data[-splitIndex, ]

# Kiểm tra kích thước
dim(train_data)
## [1] 213  14
dim(test_data)
## [1] 90 14
# Huấn luyện mô hình logistic regression
logistic_model <- glm(target ~ age + sex + cp + trestbps + chol + fbs + restecg + 
                      thalach + exang + oldpeak + slope + ca + thal, 
                      data = train_data, family = binomial)

# Xem tóm tắt kết quả
summary(logistic_model)
## 
## Call:
## glm(formula = target ~ age + sex + cp + trestbps + chol + fbs + 
##     restecg + thalach + exang + oldpeak + slope + ca + thal, 
##     family = binomial, data = train_data)
## 
## Coefficients:
##              Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -7.463796   3.536881  -2.110 0.034835 *  
## age         -0.033729   0.029440  -1.146 0.251919    
## sex1         1.713848   0.610069   2.809 0.004965 ** 
## cp           0.705054   0.244106   2.888 0.003873 ** 
## trestbps     0.036558   0.013662   2.676 0.007452 ** 
## chol         0.002687   0.004626   0.581 0.561345    
## fbs1        -1.271535   0.779437  -1.631 0.102817    
## restecg      0.439819   0.232949   1.888 0.059019 .  
## thalach     -0.025500   0.012471  -2.045 0.040886 *  
## exang1       0.693243   0.489613   1.416 0.156804    
## oldpeak      0.365979   0.283919   1.289 0.197389    
## slope        0.642780   0.449848   1.429 0.153038    
## ca           1.267803   0.343426   3.692 0.000223 ***
## thal         0.302290   0.120362   2.512 0.012022 *  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 289.90  on 209  degrees of freedom
## Residual deviance: 137.99  on 196  degrees of freedom
##   (3 observations deleted due to missingness)
## AIC: 165.99
## 
## Number of Fisher Scoring iterations: 6
# Dự đoán xác suất (Probabilities)
pred_prob <- predict(logistic_model, newdata = test_data, type = "response")

# Chuyển thành nhãn 0 hoặc 1 (ngưỡng 0.5)
pred_class <- ifelse(pred_prob > 0.5, 1, 0)

# Chuyển sang dạng factor để so sánh với thực tế
pred_class <- as.factor(pred_class)
test_data$target <- as.factor(test_data$target)
# Tạo ma trận nhầm lẫn
conf_matrix <- confusionMatrix(pred_class, test_data$target)
print(conf_matrix)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  0  1
##          0 40  7
##          1  7 33
##                                           
##                Accuracy : 0.8391          
##                  95% CI : (0.7448, 0.9091)
##     No Information Rate : 0.5402          
##     P-Value [Acc > NIR] : 3.92e-09        
##                                           
##                   Kappa : 0.6761          
##                                           
##  Mcnemar's Test P-Value : 1               
##                                           
##             Sensitivity : 0.8511          
##             Specificity : 0.8250          
##          Pos Pred Value : 0.8511          
##          Neg Pred Value : 0.8250          
##              Prevalence : 0.5402          
##          Detection Rate : 0.4598          
##    Detection Prevalence : 0.5402          
##       Balanced Accuracy : 0.8380          
##                                           
##        'Positive' Class : 0               
## 
# Accuracy (Độ chính xác tổng thể)
accuracy <- conf_matrix$overall["Accuracy"]

# Precision (Độ chính xác khi dự đoán có bệnh)
precision <- conf_matrix$byClass["Precision"]

# Recall (Khả năng phát hiện đúng người bệnh)
recall <- conf_matrix$byClass["Recall"]

# Hiển thị kết quả
cat("Accuracy:", accuracy, "\n")
## Accuracy: 0.8390805
cat("Precision:", precision, "\n")
## Precision: 0.8510638
cat("Recall:", recall, "\n")
## Recall: 0.8510638
library(pROC)
## Type 'citation("pROC")' for a citation.
## 
## Attaching package: 'pROC'
## 
## The following objects are masked from 'package:stats':
## 
##     cov, smooth, var
# Tính ROC curve
roc_curve <- roc(test_data$target, pred_prob)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
# Vẽ đường ROC
plot(roc_curve, col = "blue", main = "ROC Curve for Logistic Regression")

auc_value <- auc(roc_curve)

# In giá trị AUC
cat("AUC:", auc_value, "\n")
## AUC: 0.8930851