# Câu 1: Hồi quy tuyến tính dự đoán Ozone trên tập airquality
# Tải dữ liệu và xử lý
data("airquality")
airquality <- na.omit(airquality)  # Xử lý missing data

# Chọn biến độc lập và biến mục tiêu
X <- airquality[, c("Wind", "Temp", "Solar.R", "Month")]  # Các biến độc lập
y <- airquality$Ozone  # Biến mục tiêu

# Xây dựng mô hình hồi quy tuyến tính
model <- lm(Ozone ~ Wind + Temp + Solar.R + Month, data = airquality)

# Tóm tắt kết quả mô hình
summary(model)
## 
## Call:
## lm(formula = Ozone ~ Wind + Temp + Solar.R + Month, data = airquality)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -35.870 -13.968  -2.671   9.553  97.918 
## 
## Coefficients:
##              Estimate Std. Error t value Pr(>|t|)    
## (Intercept) -58.05384   22.97114  -2.527   0.0130 *  
## Wind         -3.31651    0.64579  -5.136 1.29e-06 ***
## Temp          1.87087    0.27363   6.837 5.34e-10 ***
## Solar.R       0.04960    0.02346   2.114   0.0368 *  
## Month        -2.99163    1.51592  -1.973   0.0510 .  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 20.9 on 106 degrees of freedom
## Multiple R-squared:  0.6199, Adjusted R-squared:  0.6055 
## F-statistic: 43.21 on 4 and 106 DF,  p-value: < 2.2e-16
# Tính R bình phương hiệu chỉnh
r_squared_adj <- summary(model)$adj.r.squared
cat("R bình phương hiệu chỉnh: ", r_squared_adj)
## R bình phương hiệu chỉnh:  0.6055166
# Câu 2: Hồi quy logistic dự đoán diabetes trên tập PimaIndiansDiabetes
# Tải dữ liệu
url <- "https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes.data.csv"
column_names <- c("Pregnancies", "Glucose", "BloodPressure", "SkinThickness", "Insulin", "BMI", "DiabetesPedigreeFunction", "Age", "Outcome")
diabetes <- read.csv(url, header = FALSE, col.names = column_names)

# Xác định X và y
X <- diabetes[, -9]  # Các biến độc lập
y <- diabetes$Outcome  # Biến mục tiêu

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

# Dự đoán trên tập dữ liệu
pred <- predict(model_logistic, type = "response")
pred_class <- ifelse(pred > 0.5, 1, 0)

# Ma trận nhầm lẫn
conf_matrix <- table(Predicted = pred_class, Actual = y)
cat("Ma trận nhầm lẫn:\n")
## Ma trận nhầm lẫn:
print(conf_matrix)
##          Actual
## Predicted   0   1
##         0 445 112
##         1  55 156
# Đánh giá mô hình (Accuracy)
accuracy <- sum(pred_class == y) / length(y)
cat("Accuracy: ", accuracy)
## Accuracy:  0.7825521