#Tải tập dữ liệu mtcars
data(mtcars)
# Xây dựng mô hình hồi quy tuyến tính
model <- lm(mpg ~ disp + qsec, data = mtcars)
# Hiển thị kết quả hồi quy
summary(model)
##
## Call:
## lm(formula = mpg ~ disp + qsec, data = mtcars)
##
## Residuals:
## Min 1Q Median 3Q Max
## -5.0316 -2.0491 -0.9206 1.8265 7.0070
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 25.504508 7.184094 3.550 0.00134 **
## disp -0.039888 0.005288 -7.543 2.58e-08 ***
## qsec 0.212288 0.366776 0.579 0.56720
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 3.288 on 29 degrees of freedom
## Multiple R-squared: 0.7216, Adjusted R-squared: 0.7024
## F-statistic: 37.58 on 2 and 29 DF, p-value: 8.884e-09
# Lấy hệ số R bình phương hiệu chỉnh
r2 <- summary(model)$adj.r.squared
cat("Hệ số R bình phương hiệu chỉnh:", r2, "\n")
## Hệ số R bình phương hiệu chỉnh: 0.7023571
# 1. Load thư viện và chuẩn bị dữ liệu
library(pROC) # Để vẽ ROC và tính AUC
## Warning: package 'pROC' was built under R version 4.4.3
## Type 'citation("pROC")' for a citation.
##
## Attaching package: 'pROC'
## The following objects are masked from 'package:stats':
##
## cov, smooth, var
data(iris)
# Lọc dữ liệu chỉ giữ lại 2 loài: versicolor và virginica
data <- subset(iris, Species %in% c("versicolor", "virginica"))
data$Species <- droplevels(data$Species) # Loại bỏ level thừa (setosa)
# 2. Chuyển đổi Species sang dạng nhị phân (0 và 1)
# 0: versicolor, 1: virginica
data$Species <- ifelse(data$Species == "virginica", 1, 0)
# 3. Xây dựng mô hình hồi quy logistic
model <- glm(Species ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width,
data = data,
family = binomial)
# 4. Dự đoán xác suất thuộc lớp virginica
data$pred_prob <- predict(model, type = "response") # Xác suất dự đoán
# 5. Vẽ đường ROC và tính AUC
roc_obj <- roc(response = data$Species, predictor = data$pred_prob)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
plot(roc_obj, main = "ROC Curve", col = "blue", print.auc = TRUE)

auc_value <- auc(roc_obj)
cat("AUC:", auc_value, "\n")
## AUC: 0.9972