# =============================================================================
# HỆ SINH THÁI HỌC THUẬT TNSAI — SACHKTL.TNSAI.VN & VIETLOD.TNSAI.VN
# Khóa học : Khóa 4: Kinh tế lượng Bayes, SEM, học máy nhân quả và mô hình cấu trúc
# Buổi học : Buổi 03 — Nhóm 12.3 Học máy kinh tế lượng
# Bài giảng: B186 — Hồi quy rừng ngẫu nhiên Breiman và độ quan trọng biến hoán vị
# Tên quốc tế: Random Forest
# Mã mô hình : random_forest_regressor
# Phần mềm : R 4.x — Gói lệnh: randomForest
# Dữ liệu   : vietlod_random_forest_regressor_ecodata.csv
# Kiểm định : Sai số dự báo ngoài túi và $R^2$, độ quan trọng biến theo hoán vị ngoài mẫu, biểu đồ phụ thuộc riêng phần và cùng K-Fold
# =============================================================================

options(scipen = 999, digits = 4)

# 1. Nạp bộ dữ liệu thực hành chuẩn hóa
data_file <- "vietlod_random_forest_regressor_ecodata.csv"
if (!file.exists(data_file)) {
  data_file <- "https://sachktl.tnsai.vn/src/ecoaz/data/vietlod_random_forest_regressor_ecodata.csv"
}
df <- read.csv(data_file, stringsAsFactors = FALSE)
cat("Kich thuoc mau thuc hanh:", nrow(df), "quan sat,", ncol(df), "bien so\n")

# 2. Thực thi kịch bản ước lượng và kiểm định B186 — Hồi quy rừng ngẫu nhiên Breiman và độ quan trọng biến hoán vị
df <- read.csv('vietlod_random_forest_regressor_ecodata.csv')
summary(df)
# randomForest::randomForest(y ~ x1 + x2 + x3, data = df, ntree = 200, importance = TRUE)

cat("Hoan tat uoc luong mo hinh B186 (random_forest_regressor) tren R 4.x.\n")
