LeHuuHoang Lab Assignment
LeHuuHoang Lab Assignment
N <- 30
N_test <- 20
library(MASS)
x0 <- seq(-2, 7, length.out = 200) # Tạo tập giá trị x0 cho đồ thị
y0 <- rep(0, length(x0))
ytrue <- 5 * (x0 - 2) * (x0 - 3) * (x0 - 4) # Công thức mô hình
thật
for (i in 0:d) {
y0 <- y0 + w[i+1] * x0^i # Cộng các thành phần vào y0
}
library(ggplot2)
# Vẽ đồ thị
plot_results <- function(X, y, X_test, y_test, x0, y0, ytrue, w, d) {
# Chuyển đổi dữ liệu thành dataframe cho ggplot
df_train <- data.frame(X = X, y = y)
df_test <- data.frame(X_test = X_test, y_test = y_test)
df_model <- data.frame(x0 = x0, y0 = y0, ytrue = ytrue)
buildX(X, 4)1 buildX(X, 4)2 buildX(X, 4)3 buildX(X, 4)4 buildX(X, 4)5
-85.076154 149.622947 -88.308307 20.790457 -1.674414
fit8 <- myfit(X, y, 8) # Hồi quy bậc 8
plot_results(X, y, X_test, y_test, fit8$x0, fit8$y0, fit8$ytrue, w =
coef(lm(y ~ 0 + buildX(X, 8))), 8)
buildX(X, 8)1 buildX(X, 8)2 buildX(X, 8)3 buildX(X, 8)4 buildX(X, 8)5
-82.81991817 136.21659090 -70.39466198 13.81402962 -0.61054042
buildX(X, 8)6 buildX(X, 8)7 buildX(X, 8)8 buildX(X, 8)9
-1.41106981 0.95291875 -0.22265680 0.01727155
Running the Model with Degree 11
This code snippet fits the polynomial regression model with a degree of 11 and visualizes the
results using the plot_results function. A degree this high may lead to overfitting, which will
be reflected in the resulting plot.
• Bias đề cập đến các lỗi xảy ra khi chúng ta cố gắng điều chỉnh mô hình thống kê
trên dữ liệu thực tế mà không phù hợp hoàn toàn với một số mô hình toán học.
Nếu chúng ta sử dụng một mô hình quá đơn giản để điều chỉnh dữ liệu thì chúng ta
có nhiều khả năng phải đối mặt với tình huống Bias cao , tức là trường hợp mô
hình không thể học được các mẫu trong dữ liệu đang xét và do đó hoạt động kém.
• Phương sai có nghĩa là giá trị của lỗi khi chúng ta cố gắng đưa ra dự đoán bằng cách
sử dụng dữ liệu mà mô hình chưa từng thấy trước đó. Có một tình huống được gọi
là phương sai cao xảy ra khi mô hình học được nhiễu có trong dữ liệu.
install.packages("gridExtra")
library(ggplot2)
library(gridExtra)
data.frame(x = x, y = y)
}
ggplot() +
geom_polygon(data = circles[1:100, ], aes(x = x, y = y), color =
"blue", fill = NA) +
geom_polygon(data = circles[101:200, ], aes(x = x, y = y), color =
"blue", fill = NA) +
geom_polygon(data = circles[201:300, ], aes(x = x, y = y), color =
"blue", fill = NA) +
geom_polygon(data = circles[301:400, ], aes(x = x, y = y), color =
NA, fill = "yellow") +
geom_point(data = data, aes(x = x, y = y), color = "darkgreen",
size = 3) +
coord_fixed() +
theme_minimal() +
theme(
plot.title = element_text(hjust = 0.5, size = 16),
axis.title = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank(),
panel.grid = element_blank()
) +
xlim(-3.5, 3.5) +
ylim(-3.5, 3.5) +
ggtitle(title)
}
# Tạo 4 plots
p1 <- create_target_plot(low_bias_low_var, "Low Bias, Low Variance",
0.1)
p2 <- create_target_plot(low_bias_high_var, "Low Bias, High Variance",
0.5)
p3 <- create_target_plot(high_bias_low_var, "High Bias, Low Variance",
0.1)
p4 <- create_target_plot(high_bias_high_var, "High Bias, High
Variance", 0.5)
# Lưu plot
ggsave("bias_variance_tradeoff.png", combined_plot, width = 12, height
= 12, dpi = 300)
• Độ lệch (Bias) cao, phương sai (variance) thấp: Một mô hình có
độ lệch cao và phương sai thấp được coi là không phù hợp.
• Độ phương sai (variance) cao, độ lệch (Bias) thấ p: Một mô hình
có độ phương sai cao và độ lệch thấp được coi là quá khớp.
• Độ lệch (Bias) cao, phương sai (variance) cao: Một mô hình có độ
lệch cao và phương sai cao không thểnắ m bắt được các mô hình cơ bản
và quá nhạy cảm với những thay đổi dữ liệu đào tạo. Trung bình, mô
hình sẽ tạo ra các dự đoán không đáng tin cậy và không nhấ t quán.
• Độ lệch (Bias) thấp, phương sai (variance) thấp: Một mô hình có
độ lệch thấp và phương sai thấp có thểnắ m bắt các mẫu dữ liệu và xử
lý các biến thểtrong dữ liệu đào tạo. Đây là kịch bản hoàn hảo cho
một mô hình học máy, nơi nó có thểkhái quát hóa tố t với dữ liệu chưa
biết và đưa ra các dự đoán chính xác, nhất quán. Tuy nhiên, trên thực
tế, điều này không khả thi.
– Explore how to select the right model based on data and evaluation metrics.
3. Ridge Regression
– Apply Ridge Regression to reduce multicollinearity and improve model accuracy.
4. Grid Search
– Use Grid Search to optimize hyperparameters and enhance model performance.
Setup
In this section, you will set up the working environment and download the sample dataset.
Note:
Follow the step-by-step instructions in the lab document to complete the tasks and compare
prediction model results before and after refinement.
This dataset was hosted on IBM Cloud object. Click HERE for free storage.
you will need to download the dataset; if you are running locally, please comment out the
following
if (file.exists(filename)) {
message("File downloaded successfully!")
return(TRUE)
} else {
warning("Download failed - File does not exist")
return(FALSE)
}
}, error = function(e) {
warning(paste("Error downloading file:", e$message))
return(FALSE)
})
}
[1] FALSE
Warning message:
“File không tồn tại sau khi tải về
. Vui lòng kiể
m tra URL và thửlại.”
str(df)
install.packages("manipulate")
print(plot)
}
price
1 13495
2 16500
3 16500
4 13950
5 17450
6 15250
diesel gas
1 0 1
2 0 1
3 0 1
4 0 1
5 0 1
6 0 1
[1] 201 30
Now, we randomly split our data into training and testing data using the function
train_test_split.
set.seed(123)
[1] 181 30
[1] 20 30
The test_size parameter sets the proportion of data that is split into the testing set. In the above,
the testing set is 10% of the total dataset.
[1] 121 30
[1] 80 30
We create a Linear Regression object, fit the model using the feature "horsepower":
Call:
lm(formula = y_train ~ horsepower, data = x_train)
Residuals:
Min 1Q Median 3Q Max
-9606.3 -2149.7 -399.6 1808.0 17691.3
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -4989.523 1007.615 -4.952 1.69e-06 ***
horsepower 177.708 9.197 19.323 < 2e-16 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
# Dự đoán giá trị của y_test dựa trên mô hình đã huấn luyện
y_pred <- predict(lre, newdata = x_test)
We can see the R^2 is much smaller using the test data compared to the training data.
# Dự đoán giá trị của y_train dựa trên mô hình đã huấn luyện
y_train_pred <- predict(lre, newdata = x_train)
# Tính R^2 cho tập dữ liệu huấn luyện
SSE_train <- sum((y_train - y_train_pred)^2) # Tổng bình phương sai
số cho dữ liệu huấn luyện
SST_train <- sum((y_train - mean(y_train))^2) # Tổng bình phương
toàn phần cho dữ liệu huấn luyện
R_squared_train <- 1 - (SSE_train / SST_train)
library(dplyr)
select
filter, lag
# Chia dữ liệu
x_train1 <- x_data[training_index1, ]
x_test1 <- x_data[-training_index1, ]
y_train1 <- y_data[training_index1, ]
y_test1 <- y_data[-training_index1, ]
Sometimes you do not have sufficient testing data; as a result, you may want to perform cross-
validation. Let's go over several methods that you can use for cross-validation.
We input the object, the feature ("horsepower"), and the target data (y_data). The parameter 'cv'
determines the number of folds. In this case, it is 4.
The default scoring is R^2. Each element in the array has the average R^2 value for the fold:
# In kết quả
print(Rcross)
We can use negative squared error as a score by setting the parameter 'scoring' metric to
'neg_mean_squared_error'.
• sử dụng metric = "RMSE" trong hàm train(). RMSE (Root Mean Squared Error) là căn bậc
hai của MSE.
• Sau khi huấn luyện mô hình, lấy giá trị RMSE từ lm_model_mser e s a m p l e RMSE.
• Tiếp theo bình phương RMSE để có MSE: mse_results <- lm_model_mser e s a m p l e
RMSE^2.
• Sau đó, nhân MSE với -1 để có negative MSE: neg_mse_results <- -1 * mse_results.
# Lấy kết quả MSE (bình phương của RMSE)
mse_results <- lm_model$resample$RMSE^2
# In kết quả
print(neg_mse_results)
# Tính và in giá trị trung bình và độ lệch chuẩn của negative MSE
cat("The mean of the negative MSE is", mean(neg_mse_results),
"and the standard deviation is", sd(neg_mse_results), "\n")
[1] 0.6485768
You can also use the function 'cross_val_predict' to predict the output. The function splits up the
data into the specified number of folds, with one fold for testing and the other folds are used for
training. First, import the function:
We input the object, the feature "horsepower", and the target data y_data. The parameter 'cv'
determines the number of folds. In this case, it is 4. We can produce an output:
# Thiết lập kiểm soát cho cross-validation
ctrl <- trainControl(method = "cv", number = 4)
1 2 3 4 5
14514.77 14514.77 21918.64 12965.12 15203.50
Let's create Multiple Linear Regression objects and train the model using 'horsepower', 'curb-
weight', 'engine-size' and 'highway-mpg' as features.
Call:
lm(formula = price ~ horsepower + curb.weight + engine.size +
highway.mpg, data = data.frame(x_train, price = y_train))
Residuals:
Min 1Q Median 3Q Max
-9296.6 -1702.5 9.8 1266.9 13158.7
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -16827.622 4702.107 -3.579 0.000446 ***
horsepower 62.443 15.778 3.958 0.000110 ***
curb.weight 4.753 1.198 3.967 0.000106 ***
engine.size 78.146 14.624 5.344 2.79e-07 ***
highway.mpg 55.466 78.565 0.706 0.481125
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
2 3 4 5 6
13871.77 19527.75 10832.15 15625.03 13972.38
1 19 23 43 60
13871.772 5869.443 8979.082 9434.349 11182.010
Let's perform some model evaluation using our training and testing data separately. First, we
import the seaborn and matplotlib library for plotting.
library(ggplot2)
Let's examine the distribution of the predicted values of the training data.
cat("\nTest Data:\n")
cat("RMSE:", test_rmse, "\n")
cat("R-squared:", test_r2, "\n")
# Vẽ đồ thị so sánh dự đoán và giá trị thực tế trên tập test
library(ggplot2)
ggplot() +
geom_point(aes(x = y_test, y = y_test_pred), color = 'blue') +
geom_abline(slope = 1, intercept = 0, linetype = 'dashed', color =
'red') +
labs(x = 'Actual Price', y = 'Predicted Price',
title = 'Comparison between Predicted and Actual Values') +
theme_minimal()
Training Data:
RMSE: 3483.854
R-squared: 0.815763
Test Data:
RMSE: 3345.171
R-squared: 0.6761707
Warning message:
“Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
ℹ Please use `linewidth` instead.”
Figure 1: Plot of predicted values using the training data compared to the actual values of the
training data.
So far, the model seems to be doing well in learning from the training dataset. But what
happens when the model encounters new data from the testing dataset? When the model
generates new values from the test data, we see the distribution of the predicted values is much
different from the actual target values.
Figure 2: Plot of predicted value using the test data compared to the actual values of the test
data.
So sánh Hình 1 và Hình 2, rõ ràng là phân phối dữ liệu thử nghiệm trong Hình 1 phù hợp với dữ
liệu tốt hơn nhiều. Sự khác biệt này trong Hình 2 thể hiện rõ trong phạm vi từ 5000 đến 15.000.
Đây là nơi hình dạng của phân phối cực kỳ khác biệt. Chúng ta hãy xem liệu hồi quy đa thức có
biểu hiện giảm độ chính xác dự đoán khi phân tích tập dữ liệu thử nghiệm hay không.
Let's use 55 percent of the data for training and the test for testing:
install.packages("polycor")
# Tạo mô hình hồi quy tuyến tính với 55% dữ liệu training
lre_multi_55 <- lm(price ~ horsepower + curb.weight + engine.size +
highway.mpg, data = data.frame(x_train_55, price = y_train_55))
# Đánh giá mô hình trên 45% dữ liệu còn lại của training
train_remain_rmse <- sqrt(mean((y_train_remain -
y_train_remain_pred)^2))
train_remain_r2 <- 1 - sum((y_train_remain - y_train_remain_pred)^2) /
sum((y_train_remain - mean(y_train_remain))^2)
cat("\nTest Data:\n")
cat("RMSE:", test_rmse_55, "\n")
cat("R-squared:", test_r2_55, "\n")
Residuals:
Min 1Q Median 3Q Max
-8370.2 -1855.6 142.8 1462.6 11679.1
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -12550.540 7146.396 -1.756 0.08231 .
horsepower 73.915 23.387 3.161 0.00212 **
curb.weight 4.367 1.722 2.536 0.01287 *
engine.size 52.732 21.945 2.403 0.01823 *
highway.mpg 5.681 124.617 0.046 0.96374
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Test Data:
RMSE: 3242.91
R-squared: 0.6956667
We will perform a degree 3 polynomial transformation on the feature 'horsepower'.
# Thư viện
library(dplyr)
library(ggplot2)
# Đánh giá mô hình trên 45% dữ liệu còn lại của training
train_remain_poly_rmse <- sqrt(mean((y_train_remain -
y_train_remain_poly_pred)^2))
train_remain_poly_r2 <- 1 - sum((y_train_remain -
y_train_remain_poly_pred)^2) / sum((y_train_remain -
mean(y_train_remain))^2)
filter, lag
Call:
lm(formula = price ~ horsepower_poly + curb.weight + engine.size +
highway.mpg, data = data.frame(x_train_55_poly, price =
y_train_55))
Residuals:
Min 1Q Median 3Q Max
-10150.1 -1947.7 59.1 1354.9 12156.7
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -2.060e+03 5.930e+03 -0.347 0.72903
horsepower_poly 8.882e-04 2.892e-04 3.071 0.00279 **
curb.weight 4.742e+00 1.766e+00 2.686 0.00856 **
engine.size 4.935e+01 2.302e+01 2.144 0.03464 *
highway.mpg -1.519e+02 1.016e+02 -1.495 0.13819
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Now, let's create a Linear Regression model "poly" and train it.
We can see the output of our model using the method "predict." We assign the values to "yhat".
Let's take the first five predicted values and compare it to the actual targets.
install.packages("polycor")
# Đánh giá mô hình trên 45% dữ liệu còn lại của training
train_remain_poly_rmse <- sqrt(mean((y_train_remain -
y_train_remain_poly_pred)^2))
train_remain_poly_r2 <- 1 - sum((y_train_remain -
y_train_remain_poly_pred)^2) / sum((y_train_remain -
mean(y_train_remain))^2)
Call:
lm(formula = price ~ horsepower_poly, data =
data.frame(x_train_55_poly,
price = y_train_55))
Residuals:
Min 1Q Median 3Q Max
-8586.2 -2046.7 -383.6 1401.0 14575.8
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 1.010e+05 5.716e+04 1.767 0.0806 .
horsepower_poly1 -4.348e+03 2.375e+03 -1.831 0.0703 .
horsepower_poly2 7.412e+01 3.733e+01 1.986 0.0500 .
horsepower_poly3 -5.793e-01 2.778e-01 -2.086 0.0397 *
horsepower_poly4 2.146e-03 9.799e-04 2.190 0.0310 *
horsepower_poly5 -3.003e-06 1.313e-06 -2.287 0.0245 *
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
# Đánh giá mô hình trên 45% dữ liệu còn lại của training
train_remain_poly_11_rmse <- sqrt(mean((y_train_remain -
y_train_remain_poly_11_pred)^2))
train_remain_poly_11_r2 <- 1 - sum((y_train_remain -
y_train_remain_poly_11_pred)^2) / sum((y_train_remain -
mean(y_train_remain))^2)
Call:
lm(formula = price ~ horsepower_poly_11, data =
data.frame(x_train_55_poly_11,
price = y_train_55))
Residuals:
Min 1Q Median 3Q Max
-8947.1 -1637.1 -332.7 1230.0 16067.8
We see that the estimated function appears to track the data but around 200 horsepower, the
function begins to diverge from the data points.
We see the R^2 for the training data is 0.7744366 while the R^2 on the test data was -
0.9797472 . The lower the R^2, the worse the model. A negative R^2 is a sign of overfitting.
Let's see how the R^2 changes on the test data for different order polynomials and then plot the
results:
# Tính R^2
r_squared_values[degree] <- summary(model)$r.squared
}
We see the R^2 gradually increases until an order three polynomial is used. Then, the R^2
dramatically decreases at an order four polynomial.
Đánh Giá R²
1. Bậc 1 (R² = 0.6943):
– Mô hình hồi quy tuyến tính đơn giản với biến horsepower có thể giải thích
khoảng 69.43% phương sai của biến mục tiêu price. Đây là một R^2 tốt cho mô
hình đơn giản, nhưng có thể cải thiện.
2. Bậc 2 (R² = 0.6960):
– Việc thêm một bậc đa thức đã cải thiện nhẹ độ chính xác, với ( R^2 ) tăng lên
69.60%. Sự cải thiện là nhỏ nhưng cho thấy mô hình đang bắt đầu nắm bắt thêm
một số biến thể trong dữ liệu.
3. Bậc 3 (R² = 0.7019):
– Tăng thêm một bậc nữa dẫn đến việc giải thích khoảng 70.19% phương sai, cho
thấy mô hình có thể bắt đầu nắm bắt được các mối quan hệ phi tuyến tính giữa
horsepower và price.
4. Bậc 4 (R² = 0.7077):
– Với ( R^2 ) tăng lên 70.77%, mô hình tiếp tục cải thiện độ chính xác. Điều này cho
thấy rằng mối quan hệ giữa horsepower và price có thể phức tạp hơn và một
mô hình phi tuyến tính hơn là cần thiết.
5. Bậc 5 (R² = 0.7233):
– Mô hình với bậc 5 đã giải thích khoảng 72.33% phương sai, cho thấy một sự cải
thiện đáng kể. Điều này cho thấy mô hình đang bắt đầu nắm bắt được các xu
hướng quan trọng trong dữ liệu.
6. Bậc 6 (R² = 0.7240):
– Chỉ số này rất gần với bậc 5, cho thấy rằng việc thêm bậc thứ 6 không tạo ra sự cải
thiện đáng kể trong độ chính xác của mô hình.
7. Bậc 7 (R² = 0.7362):
– Với ( R^2 ) là 73.62%, mô hình bắt đầu cho thấy sự cải thiện lại. Điều này có thể
cho thấy rằng độ phức tạp của mô hình đang tạo ra lợi ích.
8. Bậc 8 (R² = 0.7424):
– Tăng nhẹ ( R^2 ) lên 74.24%, mô hình bắt đầu giải thích một phần lớn hơn của
phương sai trong price.
9. Bậc 9 (R² = 0.7438):
– R² chỉ tăng một chút (0.7438), cho thấy mô hình đang đạt đến giới hạn khả năng
giải thích của nó.
10. Bậc 10 (R² = 0.7438):
– Không có sự cải thiện so với bậc 9. Điều này có thể cho thấy mô hình đã đạt đến
một mức độ phức tạp tối ưu.
11. Bậc 11 (R² = 0.7445):
– Mặc dù có sự tăng nhẹ, nhưng mức tăng rất nhỏ. do đó khi thêm một bậc đa thức
nữa không cải thiện đáng kể độ chính xác và có thể dẫn đến hiện tượng
overfitting.
Kết Luận:
• Tăng Trưởng Đầu Tiên: Các bậc thấp (từ 1 đến 5) cho thấy sự cải thiện đáng kể về ( R^2 ).
Điều này cho thấy mô hình đang học hỏi từ dữ liệu và nắm bắt được các mối quan hệ
quan trọng.
• Khả Năng Tăng Trưởng Giảm Dần: Sau bậc 5, mặc dù có sự tăng trưởng trong ( R^2 ),
nhưng mức độ cải thiện bắt đầu giảm dần và trở nên không đáng kể.
• Overfitting: Các mô hình với bậc cao (trên 8) có thể dẫn đến hiện tượng overfitting, vì mô
hình học hỏi quá mức từ dữ liệu huấn luyện và không tổng quát tốt cho dữ liệu mới.
Recomment: Có thể cân nhắc sử dụng mô hình với bậc 5 hoặc 6, vì các mô hình này vẫn thể hiện
độ chính xác cao mà không quá phức tạp. Sử dụng các phương pháp kiểm định như k-fold cross-
validation để xác định độ chính xác của mô hình trên các tập dữ liệu khác nhau.
In this section, we will review Ridge Regression and see how the parameter alpha changes the
model. Just a note, here our test data will be used as validation data.
install.packages("MASS")
# Thư viện
library(MASS) # Thư viện cho hồi quy Ridge
library(ggplot2)
# In ra kết quả
cat("R^2 cho mo hinh hoi quy Ridge (bac 11) voi lambda =",
lambda_value, ":", r_squared_ridge, "\n")
ggplot(data) +
geom_density(aes(x = Actual, fill = "Actual"), alpha = 0.5) +
geom_density(aes(x = Predicted, fill = "Predicted"), alpha = 0.5)
+
labs(title = title, x = "Value", y = "Mat do") +
scale_fill_manual(name = "Tham so", values = c("Actual" = "blue",
"Predicted" = "orange")) +
theme_minimal()
}
select
R^2 cho mo hinh hoi quy Ridge (bac 11) voi lambda = 0.5 : 0.06512191
Chọn lamda tối ưu Sử dụng cross-validation thử nhiều giá trị lambda khác nhau tìm lamda tốt
nhất
# Thư viện
library(MASS) # Thư viện cho hồi quy Ridge
library(ggplot2)
# Thực hiện hồi quy Ridge với nhiều giá trị lambda
lambdas <- seq(0, 10, by = 0.1)
ridge_models <- lm.ridge(price ~ ., data = data.frame(x_train_poly,
price = y_train), lambda = lambdas)
# Chọn giá trị lambda tối ưu dựa trên GCV (Generalized Cross-
Validation)
optimal_lambda <- ridge_models$lambda[which.min(ridge_models$GCV)]
# In ra kết quả
cat("R^2 cho mo hinh hoi quy Ridge (bac 11) voi lambda =",
optimal_lambda, ":", r_squared_ridge, "\n")
ggplot(data) +
geom_density(aes(x = Actual, fill = "Actual"), alpha = 0.5) +
geom_density(aes(x = Predicted, fill = "Predicted"), alpha = 0.5)
+
labs(title = title, x = "Value", y = "Mat do") +
scale_fill_manual(name = "Tham so", values = c("Actual" = "blue",
"Predicted" = "orange")) +
theme_minimal()
}
Here the model is built and tested on the same data, so the training and test data are the same.
The red line in Figure 4 represents the R^2 of the training data. As alpha increases the R^2
decreases. Therefore, as alpha increases, the model performs worse on the training data
The blue line represents the R^2 on the validation data. As the value for alpha increases, the R^2
decreases and converges at a point.
install.packages("glmnet")
# In ra kết quả
cat("R^2 cho mo hinh hoi quy Ridge (bac 11) voi alpha = 10:",
r_squared_ridge, "\n")
ggplot(data) +
geom_density(aes(x = Actual, fill = "Actual"), alpha = 0.5) +
geom_density(aes(x = Predicted, fill = "Predicted"), alpha = 0.5)
+
labs(title = title, x = "Gia tri", y = "Mat do") +
scale_fill_manual(name = "Tham so", values = c("Actual" = "blue",
"Predicted" = "orange")) +
theme_minimal()
}
R^2 cho mo hinh hoi quy Ridge (bac 11) voi alpha = 10: 0.1167197
lambda tối ưu và R^2 tốt nhất (0.001,0.1,1, 10, 100, 1000, 10000, 100000, 100000)
# Huấn luyện mô hình hồi quy Ridge với lambda hiện tại
ridge_model <- lm.ridge(price ~ ., data = data.frame(x_train_poly,
price = y_train), lambda = lambda)
xây dựng mô hình Ridge Regression với lambda tối ưu là 1000 và đánh giá trên tập dữ liệu test
# Thư viện
library(MASS) # Thư viện cho hồi quy Ridge
library(ggplot2)
# Tạo các đặc trưng đa thức bậc 11 cho biến horsepower trong dữ liệu
train
x_train_poly <- data.frame(horsepower = x_train$horsepower)
x_train_poly <- cbind(x_train_poly, poly(x_train$horsepower, degree =
11, raw = TRUE))
# Tạo đặc trưng đa thức bậc 11 cho biến horsepower trong dữ liệu test
x_test_poly <- data.frame(horsepower = x_test$horsepower)
x_test_poly <- cbind(x_test_poly, poly(x_test$horsepower, degree = 11,
raw = TRUE))
# In ra kết quả R²
cat("R^2 cho mo hinh hoi quy Ridge (bac 11) voi lambda =",
lambda_value, ":", r_squared_ridge, "\n")
R^2 cho mo hinh hoi quy Ridge (bac 11) voi lambda = 1000 : 0.3296223