Câu 1 (5 điểm) Sử dụng tập iris, dự đoán Petal.Length từ
Sepal.Length và Sepal.Width. Kiểm tra độ phù hợp của mô hình bằng hệ số
R bình phương hiệu chỉnh.
# Tải tập dữ liệu iris có sẵn
data(iris)
# Xây dựng mô hình hồi quy tuyến tính
# Công thức: Petal.Length phụ thuộc vào (~) Sepal.Length + Sepal.Width
model_iris <- lm(Petal.Length ~ Sepal.Length + Sepal.Width, data = iris)
# In tóm tắt kết quả của mô hình
summary_model <- summary(model_iris)
print(summary_model)
##
## Call:
## lm(formula = Petal.Length ~ Sepal.Length + Sepal.Width, data = iris)
##
## Residuals:
## Min 1Q Median 3Q Max
## -1.25582 -0.46922 -0.05741 0.45530 1.75599
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -2.52476 0.56344 -4.481 1.48e-05 ***
## Sepal.Length 1.77559 0.06441 27.569 < 2e-16 ***
## Sepal.Width -1.33862 0.12236 -10.940 < 2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.6465 on 147 degrees of freedom
## Multiple R-squared: 0.8677, Adjusted R-squared: 0.8659
## F-statistic: 482 on 2 and 147 DF, p-value: < 2.2e-16
# In riêng hệ số R bình phương hiệu chỉnh (Adjusted R-squared)
cat("Hệ số R bình phương hiệu chỉnh:", summary_model$adj.r.squared, "\n")
## Hệ số R bình phương hiệu chỉnh: 0.8658858
Câu 2 (5 điểm) Sử dụng tập Heart, chạy hồi quy logistic dự đoán bệnh
tim. Vẽ ROC curve.
library(pROC)
## Type 'citation("pROC")' for a citation.
##
## Attaching package: 'pROC'
## The following objects are masked from 'package:stats':
##
## cov, smooth, var
# 1. Tiền xử lý dữ liệu
df_heart <- read.csv("Heart.csv")
df_heart$AHD <- as.factor(df_heart$AHD)
# 2. Chia dữ liệu
set.seed(42)
sample_index <- sample(c(TRUE, FALSE), nrow(df_heart), replace = TRUE, prob = c(0.8, 0.2))
train_data <- df_heart[sample_index, ]
test_data <- df_heart[!sample_index, ]
# 3. Chạy mô hình
log_model <- glm(AHD ~ ., data = train_data, family = binomial)
# 4. Dự đoán
prob_pred <- predict(log_model, newdata = test_data, type = "response")
# 5. Tính toán và vẽ ROC
roc_curve <- roc(test_data$AHD, prob_pred)
## Setting levels: control = No, case = Yes
## Setting direction: controls < cases
cat("Chỉ số AUC (Area Under Curve):", auc(roc_curve), "\n")
## Chỉ số AUC (Area Under Curve): 0.926799
plot(roc_curve,
col = "darkorange",
lwd = 2,
main = "Đường cong ROC - Mô hình dự đoán bệnh tim",
print.auc = TRUE,
legacy.axes = TRUE)
