# Cài đặt gói nếu chưa có
if (!require(MASS)) install.packages("MASS", dependencies = TRUE)
## Loading required package: MASS
library(MASS)

# Load dataset Boston
data(Boston)

# Xây dựng mô hình hồi quy tuyến tính
model_lm <- lm(medv ~ crim + indus, data = Boston)

# Hiển thị kết quả mô hình
summary(model_lm)
## 
## Call:
## lm(formula = medv ~ crim + indus, data = Boston)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -12.011  -4.876  -1.683   3.024  32.491 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 29.24829    0.67046  43.624  < 2e-16 ***
## crim        -0.24548    0.04434  -5.536 4.99e-08 ***
## indus       -0.52335    0.05559  -9.414  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 7.83 on 503 degrees of freedom
## Multiple R-squared:  0.278,  Adjusted R-squared:  0.2751 
## F-statistic: 96.83 on 2 and 503 DF,  p-value: < 2.2e-16
# Cài đặt gói nếu chưa có
if (!require(mlbench)) install.packages("mlbench", dependencies = TRUE)
## Loading required package: mlbench
## Warning: package 'mlbench' was built under R version 4.4.3
if (!require(caret)) install.packages("caret", dependencies = TRUE)
## Loading required package: caret
## Warning: package 'caret' was built under R version 4.4.3
## Loading required package: ggplot2
## Loading required package: lattice
library(mlbench)
library(caret)

# Load dataset
data(PimaIndiansDiabetes)
df <- PimaIndiansDiabetes

# Xây dựng mô hình hồi quy logistic
model_logit <- glm(diabetes ~ ., data = df, family = binomial)

# Dự đoán xác suất
predicted_probs <- predict(model_logit, type = "response")

# Hàm tính Precision và Recall theo ngưỡng phân loại
evaluate_threshold <- function(threshold) {
  predicted_classes <- ifelse(predicted_probs > threshold, "pos", "neg")
  conf_matrix <- confusionMatrix(as.factor(predicted_classes), as.factor(df$diabetes), positive = "pos")
  
  precision <- conf_matrix$byClass["Precision"]
  recall <- conf_matrix$byClass["Recall"]
  
  return(c(Threshold = threshold, Precision = precision, Recall = recall))
}

# Thử với các ngưỡng khác nhau
thresholds <- seq(0.1, 0.9, by = 0.1)
results <- t(sapply(thresholds, evaluate_threshold))

# Hiển thị kết quả
print(results)
##       Threshold Precision.Precision Recall.Recall
##  [1,]       0.1           0.4250814     0.9738806
##  [2,]       0.2           0.5206074     0.8955224
##  [3,]       0.3           0.6011236     0.7985075
##  [4,]       0.4           0.6666667     0.6716418
##  [5,]       0.5           0.7393365     0.5820896
##  [6,]       0.6           0.7630058     0.4925373
##  [7,]       0.7           0.8196721     0.3731343
##  [8,]       0.8           0.8630137     0.2350746
##  [9,]       0.9           0.8518519     0.0858209