install.packages(“caret”) ## Câu 1: Hồi quy tuyến tính dự đoán Ozone

library(datasets)
library(caret)
## Warning: package 'caret' was built under R version 4.4.3
## Loading required package: ggplot2
## Loading required package: lattice
data(airquality)

airquality <- na.omit(airquality) # Loại bỏ giá trị NA

# Chia dữ liệu thành tập huấn luyện (70%) và kiểm tra (30%)
set.seed(123)
trainIndex <- createDataPartition(airquality$Ozone, p = 0.7, list = FALSE)
trainData <- airquality[trainIndex, ]
testData <- airquality[-trainIndex, ]

# Xây dựng mô hình hồi quy tuyến tính
model_lm <- lm(Ozone ~ ., data = trainData)
summary(model_lm)
## 
## Call:
## lm(formula = Ozone ~ ., data = trainData)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -35.048 -14.838  -3.187   7.772  97.402 
## 
## Coefficients:
##              Estimate Std. Error t value Pr(>|t|)    
## (Intercept) -67.78926   30.68544  -2.209  0.03030 *  
## Solar.R       0.07939    0.03072   2.584  0.01176 *  
## Wind         -3.11882    0.77155  -4.042  0.00013 ***
## Temp          1.97319    0.34541   5.713 2.26e-07 ***
## Month        -3.91759    1.87925  -2.085  0.04060 *  
## Day           0.06430    0.28978   0.222  0.82502    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 21.85 on 73 degrees of freedom
## Multiple R-squared:  0.6247, Adjusted R-squared:  0.599 
## F-statistic:  24.3 on 5 and 73 DF,  p-value: 2.575e-14
# Dự đoán trên tập kiểm tra
predictions <- predict(model_lm, newdata = testData)

# Tính độ lỗi trung bình tuyệt đối (MAE)
mae <- mean(abs(predictions - testData$Ozone))
cat("MAE của mô hình hồi quy tuyến tính là:", mae, "\n")
## MAE của mô hình hồi quy tuyến tính là: 15.42387