# install.packages(c(
# "tidyverse",
# "tidymodels",
# "glmnet",
# "MASS",
# "broom",
# "patchwork",
# "performance",
# "knitr",
# "rmarkdown"
# "caret"
# ))Variable Selection in Predictive Modeling
Filtering · Wrapper · Embedded · Advanced Variable Selection
Tidak semua prediktor harus masuk ke model. Pada praktikum ini kita mempelajari cara memilih prediktor melalui data simulasi, kemudian memperluasnya pada data empiris birthwt.Not every predictor needs to enter a model. In this practicum we learn variable selection using simulated data, then extend the analysis to the empirical birthwt dataset.
Jalankan kode RStudio secara berurutan dalam setiap bagian. Bagian I membandingkan seleksi variabel pada regresi simulasi; Bagian II memperluas ukuran relevansi dan teknik seleksi untuk respons numerik serta kategorik. Perhatikan bahwa hasil seleksi dan hasil prediksi tidak selalu sejalan.Run the RStudio code in sequence within each part. Part I compares variable selection for simulated regression; Part II expands relevance measures and selection methods for numerical and categorical responses. Selection and predictive performance need not agree.
I · PackageI · Packages
Siapkan lingkungan kerja R. Paket yang dipanggil di bagian ini digunakan untuk simulasi, pemodelan regresi, dan evaluasi prediksi.Prepare the R environment for simulation, regression and predictive evaluation.
Install packages
Berikut daftar package untuk seluruh alur praktikum, termasuk eksplorasi data, visualisasi, pemodelan, evaluasi model
| Package | Fungsi |
|---|---|
tidyverse |
Manipulasi data, ringkasan, dan visualisasi dengan dplyr, tidyr, dan ggplot2 |
tidymodels |
Pembagian data dan evaluasi model, terutama fungsi dari rsample dan yardstick |
glmnet |
LASSO, regularization path, dan cross-validation |
MASS |
Stepwise variable selection menggunakan stepAIC() |
broom |
Mengubah output model menjadi tabel yang mudah dianalisis |
patchwork |
Menggabungkan beberapa grafik |
performance |
Pemeriksaan multikolinearitas, termasuk VIF |
knitr |
Pengaturan code chunk serta pembuatan tabel output |
rmarkdown |
Menghasilkan modul HTML dari dokumen R Markdown |
Load packages
library(tidyverse)
library(tidymodels)
library(glmnet)
library(broom)
library(patchwork)
tidymodels_prefer()Package Installation
The following packages are used throughout this practical session for data exploration, visualization, predictive modeling, variable selection, and model evaluation.
Install the packages only if they are not already available.
# Run only if the packages are not installed
# install.packages(c(
# "tidyverse",
# "tidymodels",
# "glmnet",
# "MASS",
# "broom",
# "patchwork",
# "performance",
# "knitr",
# "rmarkdown",
# "caret",
# "ISLR2"
# ))| Package | Purpose |
|---|---|
tidyverse |
Data manipulation, descriptive summaries, and visualization using dplyr, tidyr, and ggplot2 |
tidymodels |
Data splitting and model evaluation, particularly through rsample and yardstick |
glmnet |
LASSO regression, regularization paths, and cross-validation |
MASS |
Stepwise variable selection using stepAIC() |
broom |
Converting statistical model outputs into structured tables |
patchwork |
Combining multiple visualizations |
performance |
Model diagnostics, including multicollinearity assessment |
knitr |
Managing R code chunks and generating output tables |
rmarkdown |
Supporting the rendering of R Markdown documents |
caret |
Recursive Feature Elimination (RFE) and cross-validation |
ISLR2 |
Providing the empirical dataset for the independent assignment |
Loading Packages
library(tidyverse)
library(tidymodels)
library(glmnet)
library(broom)
library(patchwork)
tidymodels_prefer()I · DataI · Data
Data simulasi memungkinkan kita mengetahui prediktor yang benar-benar membentuk respons. Periksa korelasi dan noise sebelum membandingkan prosedur seleksi.Simulated data allow us to know the predictors that generate the response. Check correlation and noise before comparing selection procedures.
Praktikum ini menggunakan data simulasi untuk mempelajari seleksi variabel dalam pemodelan prediktif. Simulasi dirancang dengan beberapa karakteristik yang dapat memengaruhi proses seleksi, yaitu hubungan linear dan nonlinear, korelasi antarprediktor, serta keberadaan prediktor yang tidak relevan terhadap respons.
Data terdiri atas 300 observasi dengan satu variabel respons numerik dan 18 prediktor. Dua skenario dibentuk untuk merepresentasikan kondisi multikolinearitas dan tingkat noise yang berbeda.
Rancangan Pembangkitan Data
1. Pembentukan prediktor
Prediktor dasar dibangkitkan dari distribusi normal standar:
\[X_1,X_3,X_4 \sim N(0,1)\]
Ketiga variabel dibangkitkan secara independen. Variabel X1 dan X4 digunakan untuk membentuk hubungan linear dengan respons, sedangkan X3 digunakan untuk membentuk hubungan nonlinear melalui transformasi kuadrat:
\[X_{3,\mathrm{sq}}=X_3^2\]
Untuk menghasilkan korelasi antarprediktor, dibentuk dua variabel tambahan:
\[X_2=\rho_{12}X_1+\sqrt{1-\rho_{12}^2}\,U_2\]
\[X_5=\rho_{45}X_4+\sqrt{1-\rho_{45}^2}\,U_5\]
dengan:
\[U_2,U_5\sim N(0,1)\]
Komponen acak tersebut dibangkitkan secara independen dari prediktor dasar. Dengan konstruksi ini, korelasi populasi antara X1 dan X2 adalah \(\rho_{12}\), sedangkan korelasi antara X4 dan X5 adalah \(\rho_{45}\).
Selanjutnya, 12 prediktor tambahan dibangkitkan sebagai variabel yang tidak berkontribusi terhadap persamaan respons:
\[Z_j\sim N(0,1),\qquad j=1,2,\ldots,12\]
Seluruh prediktor Z1 hingga Z12 dibangkitkan secara independen dari prediktor dasar dan komponen galat.
2. Pembentukan variabel respons
Variabel respons dibangkitkan berdasarkan model regresi:
\[Y=f(\mathbf{X})+\varepsilon\]
dengan fungsi hubungan:
\[f(\mathbf{X}) = 3+2.2X_1+1.8X_3^2+1.4X_4\]
dan komponen galat:
\[\varepsilon\sim N(0,\sigma^2)\]
Komponen galat dibangkitkan secara independen dari seluruh prediktor.
Dalam persamaan tersebut, X1 dan X4 memiliki kontribusi linear terhadap respons, sedangkan X3 berkontribusi melalui bentuk kuadratik. Variabel X2 dan X5 tidak masuk langsung dalam persamaan respons, tetapi dapat mengandung informasi prediktif karena berkorelasi dengan X1 dan X4.
Sementara itu, Z1 hingga Z12 tidak berkontribusi terhadap pembentukan respons. Keberadaan prediktor tersebut memungkinkan pemeriksaan kemampuan metode seleksi dalam membedakan variabel relevan dan tidak relevan.
3. Penentuan skenario simulasi
Dua skenario dibentuk dengan mempertahankan persamaan respons yang sama, tetapi membedakan kekuatan korelasi antarprediktor dan varians galat.
| Parameter | Skenario awal | Skenario tambahan |
|---|---|---|
| Jumlah observasi | 300 | 300 |
| Jumlah prediktor | 18 | 18 |
| Korelasi populasi X1–X2 | 0.90 | 0.97 |
| Korelasi populasi X4–X5 | 0.85 | 0.97 |
| Simpangan baku galat | 1.2 | 2.4 |
| Varians galat | 1.44 | 5.76 |
Skenario awal digunakan sebagai kondisi pembanding, sedangkan skenario tambahan dirancang untuk memberikan tantangan yang lebih besar dalam seleksi variabel melalui peningkatan multikolinearitas dan noise.
4. Dasar penentuan tingkat multikolinearitas
Multikolinearitas terjadi ketika suatu prediktor memiliki hubungan linear yang kuat dengan satu atau lebih prediktor lainnya.
Salah satu ukuran yang dapat digunakan untuk mengevaluasi multikolinearitas adalah Variance Inflation Factor (VIF):
\[VIF_j=\frac{1}{1-R_j^2}\]
dengan \(R_j^2\) merupakan koefisien determinasi dari regresi prediktor ke-\(j\) terhadap prediktor lainnya.
Dalam kasus sederhana yang melibatkan dua prediktor dengan korelasi \(\rho\), persamaan tersebut menjadi:
\[VIF=\frac{1}{1-\rho^2}\]
Untuk korelasi populasi sebesar 0.97, diperoleh:
\[VIF=\frac{1}{1-0.97^2}\approx16.92\]
Nilai ini menunjukkan potensi multikolinearitas yang tinggi. Namun, VIF aktual pada data simulasi tetap perlu diperiksa karena hasil sampel dapat berbeda dari nilai teoretis.
5. Dasar penentuan tingkat noise
Tingkat noise ditentukan melalui varians galat \(\sigma^2\). Semakin besar varians galat, semakin besar pula variasi respons yang tidak dapat dijelaskan oleh fungsi \(f(\mathbf{X})\).
Pada skenario awal, digunakan:
\[\sigma^2=1.2^2=1.44\]
Pada skenario tambahan, digunakan:
\[\sigma^2=2.4^2=5.76\]
Dengan demikian, varians galat pada skenario tambahan menjadi empat kali lebih besar dibandingkan skenario awal.
Besarnya noise dipilih dengan mempertimbangkan varians sinyal yang dihasilkan oleh fungsi \(f(\mathbf{X})\). Perubahan ini dimaksudkan untuk mengurangi proporsi variasi respons yang dapat dijelaskan oleh prediktor dan meningkatkan tantangan dalam pemodelan.
Pembangkitan Data Simulasi
set.seed(2045)
n <- 300
# ==========================================================
# A. PEMBANGKITAN PREDIKTOR DASAR
# ==========================================================
# Prediktor linear pertama
X1 <- rnorm(n)
# Prediktor yang berkorelasi dengan X1
rho12 <- 0.90
X2 <- rho12 * X1 +
sqrt(1 - rho12^2) * rnorm(n)
# Prediktor dengan hubungan kuadratik
X3 <- rnorm(n)
X3_sq <- X3^2
# Prediktor linear kedua
X4 <- rnorm(n)
# Prediktor yang berkorelasi dengan X4
rho45 <- 0.85
X5 <- rho45 * X4 +
sqrt(1 - rho45^2) * rnorm(n)
# Dua belas prediktor noise
Z <- replicate(12, rnorm(n))
colnames(Z) <- paste0("Z", 1:12)
# ==========================================================
# B. FUNGSI PEMBENTUK RESPONS
# ==========================================================
f_true <- 3 +
2.2 * X1 +
1.8 * X3_sq +
1.4 * X4
# ==========================================================
# C. SKENARIO AWAL
# ==========================================================
sigma_base <- 1.2
epsilon <- rnorm(
n,
mean = 0,
sd = sigma_base
)
Y <- f_true + epsilon
sim_data <- data.frame(
Y = Y,
X1 = X1,
X2 = X2,
X3 = X3,
X3_sq = X3_sq,
X4 = X4,
X5 = X5,
Z
) %>%
as_tibble()
# ==========================================================
# D. SKENARIO MULTIKOLINEARITAS DAN NOISE TINGGI
# ==========================================================
rho_high <- 0.97
sigma_high <- 2.4
# Mempertahankan komponen acak dari skenario awal
u2 <- (X2 - rho12 * X1) /
sqrt(1 - rho12^2)
u5 <- (X5 - rho45 * X4) /
sqrt(1 - rho45^2)
# Membentuk korelasi antarprediktor yang lebih tinggi
X2_high <- rho_high * X1 +
sqrt(1 - rho_high^2) * u2
X5_high <- rho_high * X4 +
sqrt(1 - rho_high^2) * u5
# Meningkatkan simpangan baku galat
epsilon_high <- (sigma_high / sigma_base) * epsilon
# Membentuk respons skenario tambahan
Y_high <- f_true + epsilon_high
sim_data_high <- data.frame(
Y = Y_high,
X1 = X1,
X2 = X2_high,
X3 = X3,
X3_sq = X3_sq,
X4 = X4,
X5 = X5_high,
Z
) %>%
as_tibble()Menyimpan Data dalam Format CSV
# Membuat folder data jika belum tersedia
dir.create(
"data",
showWarnings = FALSE,
recursive = TRUE
)
# Menyimpan skenario awal
readr::write_csv(
sim_data,
file = "data/sim_data_baseline.csv"
)
# Menyimpan skenario tambahan
readr::write_csv(
sim_data_high,
file = "data/sim_data_high_noise_multicol.csv"
)getwd() #Untuk memeriksa lokasi data#> [1] "D:/Sains Data 2026"
Sebelum melanjutkan analisis, lakukan pemeriksaan sederhana.
# Dimensi kedua dataset
dim(sim_data)#> [1] 300 19
dim(sim_data_high)#> [1] 300 19
# Memastikan struktur variabel sama
identical(
names(sim_data),
names(sim_data_high)
)#> [1] TRUE
# Memastikan file CSV tersedia
file.exists(
"data/sim_data_baseline.csv"
)#> [1] TRUE
file.exists(
"data/sim_data_high_noise_multicol.csv"
)#> [1] TRUE
Validasi Multikolinearitas
Korelasi Pearson menunjukkan kekuatan hubungan linear antara dua prediktor. Namun, dalam regresi berganda, multikolinearitas dapat melibatkan hubungan suatu prediktor dengan beberapa prediktor lainnya.
Oleh karena itu, tingkat multikolinearitas diperiksa menggunakan Variance Inflation Factor (VIF).
VIF untuk prediktor ke-\(j\) didefinisikan sebagai:
\[\mathrm{VIF}_j = \frac{1}{1-R_j^2}\]
dengan \(R_j^2\) merupakan koefisien determinasi dari regresi prediktor ke-\(j\) terhadap seluruh prediktor lainnya.
Regresi pembantu tersebut dapat dituliskan sebagai:
\[X_j = \alpha_0 + \sum_{\substack{k=1 \\ k\neq j}}^{p} \alpha_k X_k + u_j\]
Semakin besar nilai \(R_j^2\), semakin besar nilai VIF. Nilai VIF yang tinggi menunjukkan bahwa suatu prediktor dapat dijelaskan dengan baik oleh kombinasi prediktor lainnya.
Pada data simulasi, VIF dihitung untuk seluruh prediktor pada kedua skenario.
# Fungsi untuk menghitung VIF
hitung_vif <- function(data) {
# Mengambil seluruh prediktor
x_data <- data %>%
select(-Y) %>%
as.data.frame()
nama_prediktor <- names(x_data)
# Menghitung VIF setiap prediktor
nilai_vif <- vapply(
nama_prediktor,
function(var) {
prediktor_lain <- setdiff(
nama_prediktor,
var
)
model_bantu <- lm(
reformulate(
prediktor_lain,
response = var
),
data = x_data
)
r_squared <- summary(model_bantu)$r.squared
1 / (1 - r_squared)
},
numeric(1)
)
tibble(
Prediktor = names(nilai_vif),
VIF = as.numeric(nilai_vif)
)
}
# Menghitung VIF skenario awal
vif_awal <- hitung_vif(sim_data) %>%
rename(VIF_Awal = VIF)
# Menghitung VIF skenario tambahan
vif_tinggi <- hitung_vif(sim_data_high) %>%
rename(VIF_Tinggi = VIF)
# Menggabungkan hasil kedua skenario
vif_validation <- vif_awal %>%
left_join(
vif_tinggi,
by = "Prediktor"
) %>%
mutate(
across(
starts_with("VIF"),
~ round(.x, 2)
)
) %>%
arrange(desc(VIF_Tinggi))
vif_validation| Prediktor | VIF_Awal | VIF_Tinggi |
|---|---|---|
| X4 | 4.00 | 18.28 |
| X5 | 3.92 | 18.03 |
| X2 | 5.30 | 17.11 |
| X1 | 5.25 | 17.06 |
| Z2 | 1.16 | 1.16 |
| Z7 | 1.14 | 1.14 |
| Z11 | 1.10 | 1.10 |
| Z6 | 1.08 | 1.08 |
| Z10 | 1.08 | 1.08 |
| X3 | 1.07 | 1.07 |
| X3_sq | 1.07 | 1.07 |
| Z3 | 1.07 | 1.07 |
| Z5 | 1.07 | 1.07 |
| Z9 | 1.07 | 1.07 |
| Z1 | 1.06 | 1.06 |
| Z4 | 1.06 | 1.06 |
| Z8 | 1.06 | 1.06 |
| Z12 | 1.05 | 1.05 |
Untuk memfokuskan pemeriksaan pada pasangan prediktor yang sengaja dibentuk dengan korelasi tinggi, tampilkan nilai VIF dari X1, X2, X4, dan X5.
vif_validation %>%
filter(
Prediktor %in% c(
"X1", "X2", "X4", "X5"
)
)| Prediktor | VIF_Awal | VIF_Tinggi |
|---|---|---|
| X4 | 4.00 | 18.28 |
| X5 | 3.92 | 18.03 |
| X2 | 5.30 | 17.11 |
| X1 | 5.25 | 17.06 |
Hasil pemeriksaan VIF menunjukkan adanya perbedaan tingkat multikolinearitas antara kedua skenario. Pada skenario awal, nilai VIF untuk X1 dan X2 masing-masing sebesar 5,25 dan 5,30, sedangkan X4 dan X5 memiliki VIF sebesar 4,00 dan 3,92. Nilai tersebut menunjukkan adanya hubungan linear yang cukup kuat pada kedua pasangan prediktor.
Pada skenario tambahan, VIF meningkat menjadi 17,06 untuk X1, 17,11 untuk X2, 18,28 untuk X4, dan 18,03 untuk X5. Seluruh nilai tersebut melampaui 10, yang sering digunakan sebagai indikasi multikolinearitas tinggi.
Sebaliknya, prediktor lainnya memiliki VIF yang relatif mendekati 1. Prediktor Z1 hingga Z12 memiliki VIF antara 1,05 dan 1,16. Variabel X3 dan X3_sq juga mempunyai VIF sebesar 1,07.
Hasil ini memperlihatkan bahwa peningkatan multikolinearitas terutama terjadi pada pasangan prediktor yang memang dirancang memiliki korelasi tinggi. Sementara itu, hubungan linear prediktor lainnya relatif rendah.
Dengan demikian, karakteristik multikolinearitas pada kedua skenario telah terbentuk sesuai tujuan simulasi. Namun, VIF tidak mengukur seberapa penting suatu prediktor dalam menjelaskan respons. Prediktor dengan VIF rendah belum tentu relevan, sedangkan prediktor dengan VIF tinggi belum tentu harus dikeluarkan dari model.
Validasi Noise Respons
Pada pembangkitan data, variabel respons dibentuk dari fungsi hubungan prediktor dan komponen galat acak:
\[Y_i=f(\mathbf{X}_i)+\varepsilon_i\]
dengan:
\[f(\mathbf{X}_i) = 3+2.2X_{1i}+1.8X_{3i}^2+1.4X_{4i}\]
Komponen galat mengikuti distribusi normal dengan rata-rata nol dan varians tertentu:
\[\varepsilon_i\sim N(0,\sigma^2)\]
Pada skenario awal, simpangan baku galat ditetapkan sebesar 1,2, sedangkan pada skenario tambahan ditingkatkan menjadi 2,4.
Karena fungsi pembangkit respons diketahui, galat dapat diperoleh kembali melalui:
\[\varepsilon_i=Y_i-f(\mathbf{X}_i)\]
Simpangan baku dan varians galat hasil simulasi kemudian dibandingkan dengan nilai parameter yang telah ditentukan.
# Fungsi pembangkit respons yang diketahui
fungsi_respons <- function(data) {
3 +
2.2 * data$X1 +
1.8 * data$X3_sq +
1.4 * data$X4
}
# Menghitung galat skenario awal
error_awal <- sim_data$Y -
fungsi_respons(sim_data)
# Menghitung galat skenario tambahan
error_tinggi <- sim_data_high$Y -
fungsi_respons(sim_data_high)
# Membandingkan parameter dan hasil simulasi
noise_validation <- tibble(
Skenario = c(
"Awal",
"Noise tinggi"
),
SD_Target = c(
1.2,
2.4
),
SD_Aktual = c(
sd(error_awal),
sd(error_tinggi)
),
Varians_Target = c(
1.2^2,
2.4^2
),
Varians_Aktual = c(
var(error_awal),
var(error_tinggi)
),
Mean_Error = c(
mean(error_awal),
mean(error_tinggi)
)
) %>%
mutate(
across(
where(is.numeric),
~ round(.x, 3)
)
)
noise_validation| Skenario | SD_Target | SD_Aktual | Varians_Target | Varians_Aktual | Mean_Error |
|---|---|---|---|---|---|
| Awal | 1.2 | 1.196 | 1.44 | 1.431 | -0.07 |
| Noise tinggi | 2.4 | 2.392 | 5.76 | 5.723 | -0.14 |
Hasil validasi menunjukkan bahwa karakteristik galat pada kedua skenario mendekati parameter yang ditetapkan. Pada skenario awal, simpangan baku galat sebesar 1,196 mendekati target 1,2, dengan varians sebesar 1,431 mendekati target 1,44.
Pada skenario noise tinggi, simpangan baku meningkat menjadi 2,392, mendekati target 2,4. Varians galat juga meningkat menjadi 5,723, mendekati target 5,76.
Rata-rata galat pada kedua skenario masing-masing sebesar -0,070 dan -0,140. Kedua nilai tersebut relatif dekat dengan nol. Perbedaan dari nilai teoretis merupakan variasi sampel karena data dibangkitkan menggunakan 300 observasi.
Peningkatan simpangan baku galat dapat diperiksa melalui rasio:
\[\frac{s_{\varepsilon,\mathrm{tinggi}}} {s_{\varepsilon,\mathrm{awal}}} = \frac{2.392}{1.196} = 2\]
Sementara itu, rasio varians sampel adalah:
\[\frac{s_{\varepsilon,\mathrm{tinggi}}^2} {s_{\varepsilon,\mathrm{awal}}^2} = \frac{5.723}{1.431} \approx 4\]
Hasil tersebut menunjukkan bahwa skenario tambahan memiliki simpangan baku galat dua kali lebih besar dan varians galat sekitar empat kali lebih besar dibandingkan skenario awal.
Dengan demikian, tingkat noise respons pada kedua skenario telah terbentuk sesuai rancangan simulasi.
Validasi Data Simulasi
Validasi dilakukan untuk memastikan bahwa data yang dibangkitkan memiliki karakteristik yang sesuai dengan rancangan simulasi. Pemeriksaan difokuskan pada struktur data, korelasi antarprediktor, multikolinearitas, dan distribusi galat acak.
Data dibangkitkan berdasarkan model:
\[Y_i = f(\mathbf{X}_i) + \varepsilon_i\]
dengan fungsi sistematis:
\[f(\mathbf{X}_i) = 3 + 2.2X_{1i} + 1.8X_{3i}^{2} + 1.4X_{4i}\]
dan galat acak:
\[\varepsilon_i \sim N(0,\sigma_{\varepsilon}^{2})\]
Dua skenario digunakan untuk memperlihatkan pengaruh perubahan karakteristik data terhadap pemodelan prediktif:
- Skenario awal: korelasi antarprediktor relatif tinggi dengan simpangan baku galat sebesar 1,20.
- Skenario multikolinearitas dan noise tinggi: korelasi pasangan prediktor ditingkatkan menjadi 0,97 dan simpangan baku galat menjadi 2,40.
Peningkatan simpangan baku galat dari 1,20 menjadi 2,40 menyebabkan varians teoretis meningkat empat kali lipat:
\[\frac{\operatorname{Var}(\varepsilon_{\text{tinggi}})} {\operatorname{Var}(\varepsilon_{\text{awal}})} = \frac{2.4^2}{1.2^2} = 4\]
Hasil pemeriksaan menunjukkan bahwa karakteristik sampel sesuai dengan rancangan simulasi. Pada skenario awal, korelasi aktual antara X1 dan X2 sebesar 0,891, sedangkan korelasi antara X4 dan X5 sebesar 0,848. Nilai tersebut mendekati korelasi yang ditetapkan dalam proses pembangkitan.
Pada skenario multikolinearitas tinggi, nilai Variance Inflation Factor (VIF) untuk pasangan prediktor yang berkorelasi meningkat hingga sekitar 17–18. Hasil ini menunjukkan bahwa skenario kedua berhasil menghasilkan kondisi multikolinearitas yang lebih kuat.
Validasi galat juga memperlihatkan kesesuaian antara parameter teoretis dan statistik sampel.
| Skenario | SD Target | SD Aktual | Varians Target | Varians Aktual |
|---|---|---|---|---|
| Awal | 1.200 | 1.196 | 1.440 | 1.431 |
| Noise tinggi | 2.400 | 2.392 | 5.760 | 5.723 |
Perbedaan kecil antara nilai target dan nilai aktual merupakan konsekuensi dari variasi pengambilan sampel acak. Perbedaan tersebut tidak menunjukkan kesalahan dalam pembangkitan data.
Dengan demikian, kedua dataset telah memenuhi karakteristik yang dirancang dan dapat digunakan pada tahap pemodelan prediktif serta seleksi variabel.
Untuk analisis utama, digunakan dataset dengan multikolinearitas dan noise tinggi karena kondisi tersebut memberikan tantangan yang lebih besar dalam mengidentifikasi prediktor relevan. Dataset skenario awal dipertahankan sebagai pembanding karakteristik data.
This practical session uses simulated data to investigate variable selection in predictive modeling. The simulation is designed to incorporate several characteristics that may affect variable selection, including linear and nonlinear relationships, correlations among predictors, and predictors that are irrelevant to the response.
The dataset consists of 300 observations, one numerical response variable, and 18 predictors. Two scenarios are constructed to represent different levels of multicollinearity and noise.
Simulation Design
1. Predictor generation
The basic predictors are independently generated from a standard normal distribution:
\[X_1,X_3,X_4 \sim N(0,1)\]
Variables X1 and X4 are used to construct linear relationships with the response, whereas X3 contributes through a quadratic relationship represented by:
\[X_{3,\mathrm{sq}} = X_3^2\]
To introduce correlations among predictors, two additional variables are constructed:
\[X_2 = \rho_{12}X_1 + \sqrt{1-\rho_{12}^2}\,U_2\]
\[X_5 = \rho_{45}X_4 + \sqrt{1-\rho_{45}^2}\,U_5\]
where:
\[U_2,U_5\sim N(0,1)\]
The random components are generated independently of the basic predictors.
Under this construction, the population correlation between X1 and X2 is \(\rho_{12}\), whereas the population correlation between X4 and X5 is \(\rho_{45}\).
In addition, 12 predictors that do not contribute to the response-generating equation are generated as:
\[Z_j\sim N(0,1), \qquad j=1,2,\ldots,12\]
All predictors Z1 through Z12 are generated independently of the basic predictors and the random error component.
2. Response generation
The response variable is generated according to:
\[Y=f(\mathbf{X})+\varepsilon\]
with the systematic component:
\[f(\mathbf{X}) = 3+2.2X_1+1.8X_3^2+1.4X_4\]
and the random error:
\[\varepsilon\sim N(0,\sigma^2)\]
The error component is generated independently of all predictors.
In this equation, X1 and X4 have direct linear contributions to the response, whereas X3 contributes through its squared term.
Variables X2 and X5 are not directly included in the response-generating equation. However, they may contain predictive information because they are strongly correlated with X1 and X4, respectively.
Meanwhile, Z1 through Z12 have no direct contribution to the response-generating mechanism. These predictors allow us to examine whether variable selection methods can distinguish relevant from irrelevant predictors.
3. Simulation scenarios
Two simulation scenarios are constructed using the same systematic response function while varying the strength of correlations among predictors and the error variance.
| Parameter | Baseline scenario | High multicollinearity and noise scenario |
|---|---|---|
| Number of observations | 300 | 300 |
| Number of predictors | 18 | 18 |
| Population correlation X1–X2 | 0.90 | 0.97 |
| Population correlation X4–X5 | 0.85 | 0.97 |
| Error standard deviation | 1.2 | 2.4 |
| Error variance | 1.44 | 5.76 |
The baseline scenario serves as a reference condition. The second scenario introduces stronger multicollinearity and a higher noise level to create a more challenging setting for variable selection.
4. Multicollinearity specification
Multicollinearity occurs when a predictor has a strong linear relationship with one or more other predictors.
One measure commonly used to assess multicollinearity is the Variance Inflation Factor (VIF):
\[\mathrm{VIF}_j = \frac{1}{1-R_j^2}\]
where \(R_j^2\) is the coefficient of determination obtained by regressing the \(j\)-th predictor on the remaining predictors.
In the simple case involving two correlated predictors with correlation \(\rho\), the expression becomes:
\[\mathrm{VIF} = \frac{1}{1-\rho^2}\]
For a population correlation of 0.97:
\[\mathrm{VIF} = \frac{1}{1-0.97^2} \approx 16.92\]
This value indicates substantial potential multicollinearity.
However, the actual VIF calculated from the simulated sample may differ from the theoretical value because of sampling variation and relationships with other predictors.
5. Noise specification
The noise level is controlled through the error variance \(\sigma^2\). A larger error variance produces greater variation in the response that cannot be explained by the systematic function \(f(\mathbf{X})\).
For the baseline scenario:
\[\sigma^2=1.2^2=1.44\]
For the high-noise scenario:
\[\sigma^2=2.4^2=5.76\]
Therefore, the theoretical error variance in the second scenario is four times that of the baseline scenario.
The selected noise levels are considered relative to the variance of the systematic signal generated by \(f(\mathbf{X})\). Increasing the error variance reduces the proportion of response variation attributable to the systematic component and introduces a greater challenge for predictive modeling.
Generating Simulated Data
set.seed(2045)
n <- 300
# ==========================================================
# A. GENERATING BASIC PREDICTORS
# ==========================================================
# First direct linear predictor
X1 <- rnorm(n)
# Predictor correlated with X1
rho12 <- 0.90
X2 <- rho12 * X1 +
sqrt(1 - rho12^2) * rnorm(n)
# Predictor with a quadratic relationship
X3 <- rnorm(n)
X3_sq <- X3^2
# Second direct linear predictor
X4 <- rnorm(n)
# Predictor correlated with X4
rho45 <- 0.85
X5 <- rho45 * X4 +
sqrt(1 - rho45^2) * rnorm(n)
# Twelve irrelevant predictors
Z <- replicate(12, rnorm(n))
colnames(Z) <- paste0("Z", 1:12)
# ==========================================================
# B. SYSTEMATIC RESPONSE FUNCTION
# ==========================================================
f_true <- 3 +
2.2 * X1 +
1.8 * X3_sq +
1.4 * X4
# ==========================================================
# C. BASELINE SCENARIO
# ==========================================================
sigma_base <- 1.2
epsilon <- rnorm(
n,
mean = 0,
sd = sigma_base
)
Y <- f_true + epsilon
sim_data <- data.frame(
Y = Y,
X1 = X1,
X2 = X2,
X3 = X3,
X3_sq = X3_sq,
X4 = X4,
X5 = X5,
Z
) %>%
as_tibble()
# ==========================================================
# D. HIGH MULTICOLLINEARITY AND NOISE SCENARIO
# ==========================================================
rho_high <- 0.97
sigma_high <- 2.4
# Recover the random components from the baseline scenario
u2 <- (X2 - rho12 * X1) /
sqrt(1 - rho12^2)
u5 <- (X5 - rho45 * X4) /
sqrt(1 - rho45^2)
# Construct predictors with stronger correlations
X2_high <- rho_high * X1 +
sqrt(1 - rho_high^2) * u2
X5_high <- rho_high * X4 +
sqrt(1 - rho_high^2) * u5
# Increase the error standard deviation
epsilon_high <- (sigma_high / sigma_base) * epsilon
# Generate the response for the second scenario
Y_high <- f_true + epsilon_high
sim_data_high <- data.frame(
Y = Y_high,
X1 = X1,
X2 = X2_high,
X3 = X3,
X3_sq = X3_sq,
X4 = X4,
X5 = X5_high,
Z
) %>%
as_tibble()Saving the Simulated Datasets as CSV Files
Both datasets are saved in CSV format so that they can be reused without repeating the simulation.
# Create a data directory if it does not exist
dir.create(
"data",
showWarnings = FALSE,
recursive = TRUE
)
# Save the baseline scenario
readr::write_csv(
sim_data,
file = "data/sim_data_baseline.csv"
)
# Save the high multicollinearity and noise scenario
readr::write_csv(
sim_data_high,
file = "data/sim_data_high_noise_multicol.csv"
)Check the working directory to identify where the files have been saved.
getwd()#> [1] "D:/Sains Data 2026"
Before proceeding, verify the dimensions, variable names, and file availability.
# Dataset dimensions
dim(sim_data)#> [1] 300 19
dim(sim_data_high)#> [1] 300 19
# Check whether both datasets have identical variable names
identical(
names(sim_data),
names(sim_data_high)
)#> [1] TRUE
# Verify that the CSV files exist
file.exists(
"data/sim_data_baseline.csv"
)#> [1] TRUE
file.exists(
"data/sim_data_high_noise_multicol.csv"
)#> [1] TRUE
Each dataset should contain 300 observations and 19 columns, consisting of one response variable and 18 predictors.
Multicollinearity Validation
Pearson correlation measures the strength of a linear relationship between two variables. However, in multiple regression, multicollinearity may involve the relationship between one predictor and several other predictors.
Therefore, multicollinearity is assessed using the Variance Inflation Factor (VIF).
For the \(j\)-th predictor, VIF is defined as:
\[\mathrm{VIF}_j = \frac{1}{1-R_j^2}\]
where \(R_j^2\) represents the coefficient of determination obtained by regressing the \(j\)-th predictor on all remaining predictors.
The corresponding auxiliary regression can be expressed as:
\[X_j = \alpha_0 + \sum_{\substack{k=1 \\ k\neq j}}^{p} \alpha_kX_k + u_j\]
A larger \(R_j^2\) produces a larger VIF. A high VIF indicates that a predictor can be explained to a considerable extent by a linear combination of other predictors.
VIF values are calculated for all predictors under both simulation scenarios.
# Function to calculate VIF
hitung_vif <- function(data) {
# Extract all predictors
x_data <- data %>%
select(-Y) %>%
as.data.frame()
nama_prediktor <- names(x_data)
# Calculate VIF for each predictor
nilai_vif <- vapply(
nama_prediktor,
function(var) {
prediktor_lain <- setdiff(
nama_prediktor,
var
)
model_bantu <- lm(
reformulate(
prediktor_lain,
response = var
),
data = x_data
)
r_squared <- summary(model_bantu)$r.squared
1 / (1 - r_squared)
},
numeric(1)
)
tibble(
Prediktor = names(nilai_vif),
VIF = as.numeric(nilai_vif)
)
}
# Calculate VIF for the baseline scenario
vif_awal <- hitung_vif(sim_data) %>%
rename(VIF_Awal = VIF)
# Calculate VIF for the high multicollinearity scenario
vif_tinggi <- hitung_vif(sim_data_high) %>%
rename(VIF_Tinggi = VIF)
# Combine VIF results
vif_validation <- vif_awal %>%
left_join(
vif_tinggi,
by = "Prediktor"
) %>%
mutate(
across(
starts_with("VIF"),
~ round(.x, 2)
)
) %>%
arrange(desc(VIF_Tinggi))
vif_validation| Prediktor | VIF_Awal | VIF_Tinggi |
|---|---|---|
| X4 | 4.00 | 18.28 |
| X5 | 3.92 | 18.03 |
| X2 | 5.30 | 17.11 |
| X1 | 5.25 | 17.06 |
| Z2 | 1.16 | 1.16 |
| Z7 | 1.14 | 1.14 |
| Z11 | 1.10 | 1.10 |
| Z6 | 1.08 | 1.08 |
| Z10 | 1.08 | 1.08 |
| X3 | 1.07 | 1.07 |
| X3_sq | 1.07 | 1.07 |
| Z3 | 1.07 | 1.07 |
| Z5 | 1.07 | 1.07 |
| Z9 | 1.07 | 1.07 |
| Z1 | 1.06 | 1.06 |
| Z4 | 1.06 | 1.06 |
| Z8 | 1.06 | 1.06 |
| Z12 | 1.05 | 1.05 |
To focus on the predictors that were deliberately constructed with strong correlations, display the VIF values for X1, X2, X4, and X5.
vif_validation %>%
filter(
Prediktor %in% c(
"X1", "X2", "X4", "X5"
)
)| Prediktor | VIF_Awal | VIF_Tinggi |
|---|---|---|
| X4 | 4.00 | 18.28 |
| X5 | 3.92 | 18.03 |
| X2 | 5.30 | 17.11 |
| X1 | 5.25 | 17.06 |
The VIF results indicate different levels of multicollinearity between the two simulation scenarios.
In the baseline scenario, the VIF values for X1 and X2 are 5.25 and 5.30, respectively, whereas X4 and X5 have VIF values of 4.00 and 3.92. These values indicate relatively strong linear relationships within the two predictor pairs.
In the high multicollinearity scenario, VIF increases to 17.06 for X1, 17.11 for X2, 18.28 for X4, and 18.03 for X5. All four values exceed 10, a threshold commonly used as an indication of substantial multicollinearity.
In contrast, the remaining predictors have VIF values relatively close to 1. Predictors Z1 through Z12 have VIF values ranging from 1.05 to 1.16. Variables X3 and X3_sq also have VIF values of approximately 1.07.
These results indicate that the increase in multicollinearity is concentrated in the predictor pairs deliberately constructed with strong correlations, while the remaining predictors exhibit relatively weak linear dependencies.
Thus, the multicollinearity characteristics of both scenarios are consistent with the simulation design.
However, VIF does not measure the importance of a predictor in explaining the response. A predictor with a low VIF is not necessarily relevant, and a predictor with a high VIF does not necessarily need to be removed from the model.
Response Noise Validation
In the simulation, the response variable is generated from a systematic predictor function and a random error component:
\[Y_i=f(\mathbf{X}_i)+\varepsilon_i\]
where:
\[f(\mathbf{X}_i) = 3+2.2X_{1i}+1.8X_{3i}^2+1.4X_{4i}\]
The random error follows a normal distribution with mean zero and variance \(\sigma^2\):
\[\varepsilon_i\sim N(0,\sigma^2)\]
The error standard deviation is set to 1.2 in the baseline scenario and increased to 2.4 in the second scenario.
Since the true response-generating function is known, the error component can be recovered as:
\[\varepsilon_i = Y_i-f(\mathbf{X}_i)\]
The sample standard deviation and variance of the generated errors are then compared with the specified parameters.
# Known response-generating function
fungsi_respons <- function(data) {
3 +
2.2 * data$X1 +
1.8 * data$X3_sq +
1.4 * data$X4
}
# Recover errors from the baseline scenario
error_awal <- sim_data$Y -
fungsi_respons(sim_data)
# Recover errors from the high-noise scenario
error_tinggi <- sim_data_high$Y -
fungsi_respons(sim_data_high)
# Compare specified parameters and simulated values
noise_validation <- tibble(
Scenario = c(
"Baseline",
"High noise"
),
SD_Target = c(
1.2,
2.4
),
SD_Actual = c(
sd(error_awal),
sd(error_tinggi)
),
Variance_Target = c(
1.2^2,
2.4^2
),
Variance_Actual = c(
var(error_awal),
var(error_tinggi)
),
Mean_Error = c(
mean(error_awal),
mean(error_tinggi)
)
) %>%
mutate(
across(
where(is.numeric),
~ round(.x, 3)
)
)
noise_validation| Scenario | SD_Target | SD_Actual | Variance_Target | Variance_Actual | Mean_Error |
|---|---|---|---|---|---|
| Baseline | 1.2 | 1.196 | 1.44 | 1.431 | -0.07 |
| High noise | 2.4 | 2.392 | 5.76 | 5.723 | -0.14 |
The validation results indicate that the error characteristics of both scenarios are close to the specified parameters.
In the baseline scenario, the sample error standard deviation is 1.196, close to the target of 1.2. The sample error variance is 1.431, compared with the theoretical value of 1.44.
In the high-noise scenario, the standard deviation increases to 2.392, close to the target of 2.4. The sample variance increases to 5.723, compared with the target of 5.76.
The mean errors are -0.070 and -0.140 for the baseline and high-noise scenarios, respectively. Both values are relatively close to zero. The differences from the theoretical parameters arise from sampling variation in the 300 simulated observations.
The increase in the sample error standard deviation can be examined through the ratio:
\[\frac{s_{\varepsilon,\mathrm{high}}} {s_{\varepsilon,\mathrm{baseline}}} = \frac{2.392}{1.196} = 2\]
Similarly, the ratio of sample error variances is approximately:
\[\frac{s_{\varepsilon,\mathrm{high}}^2} {s_{\varepsilon,\mathrm{baseline}}^2} = \frac{5.723}{1.431} \approx 4\]
These results indicate that the high-noise scenario has twice the error standard deviation and approximately four times the error variance of the baseline scenario.
Therefore, the simulated response noise is consistent with the intended simulation design.
Summary of Simulation Validation
The simulation validation is intended to ensure that the generated datasets exhibit the characteristics specified in the simulation design.
The validation focuses on the data structure, correlations among predictors, multicollinearity, and the random error component.
The response is generated according to:
\[Y_i=f(\mathbf{X}_i)+\varepsilon_i\]
with the systematic function:
\[f(\mathbf{X}_i) = 3+2.2X_{1i}+1.8X_{3i}^2+1.4X_{4i}\]
and random error:
\[\varepsilon_i\sim N(0,\sigma_{\varepsilon}^2)\]
The increase in the theoretical error variance is expressed as:
\[\frac{ \operatorname{Var}(\varepsilon_{\mathrm{high}}) }{ \operatorname{Var}(\varepsilon_{\mathrm{baseline}}) } = \frac{2.4^2}{1.2^2} = 4\]
The validation results show that the simulated data are consistent with the specified characteristics.
In the baseline scenario, the observed correlation between X1 and X2 is 0.891, while the correlation between X4 and X5 is 0.848. Both values are close to their specified population correlations.
In the high multicollinearity scenario, the VIF values for the correlated predictor pairs increase to approximately 17–18, confirming stronger linear dependencies.
The error validation also shows close agreement between the theoretical parameters and the sample statistics.
| Scenario | Target SD | Actual SD | Target Variance | Actual Variance |
|---|---|---|---|---|
| Baseline | 1.200 | 1.196 | 1.440 | 1.431 |
| High noise | 2.400 | 2.392 | 5.760 | 5.723 |
Small differences between the target and observed values are expected because of random sampling. These differences do not indicate errors in the data generation process.
Therefore, both datasets exhibit the intended simulation characteristics and can be used for predictive modeling and variable selection.
For the main analysis, the dataset with high multicollinearity and noise is used because it provides a more challenging setting for identifying relevant predictors. The baseline dataset is retained as a reference for comparing data characteristics.
I · A. Pemodelan PrediktifI · A. Predictive Modeling
Bangun model penuh pada data latih sebagai pembanding; hubungan marginal tidak selalu sama dengan kontribusi setelah prediktor lain masuk.Fit a full training-set model as a reference; marginal relationships do not necessarily reflect conditional contributions.
Pembagian Data Latih dan Data Uji
Pemodelan prediktif bertujuan membangun fungsi yang mampu memperkirakan nilai respons berdasarkan informasi dari sejumlah prediktor.
Secara umum, hubungan antara respons dan prediktor dinyatakan sebagai:
\[Y_i = f(\mathbf{X}_i) + \varepsilon_i\]
dengan \(f(\mathbf{X}_i)\) merupakan komponen sistematis yang ingin diestimasi dan \(\varepsilon_i\) merupakan galat acak.
Dalam praktikum ini, data dibagi menjadi data latih sebesar 80% dan data uji sebesar 20%. Data latih digunakan untuk pembangunan model dan seleksi variabel, sedangkan data uji disimpan untuk evaluasi akhir.
# Membaca data simulasi
data_sim <- readr::read_csv(
"data/sim_data_high_noise_multicol.csv",
show_col_types = FALSE
)
# Membagi data menjadi training dan testing
set.seed(2026)
split_data <- rsample::initial_split(
data_sim,
prop = 0.80
)
data_train <- rsample::training(split_data)
data_test <- rsample::testing(split_data)
# Menampilkan ukuran masing-masing dataset
tibble::tibble(
Dataset = c("Data keseluruhan", "Data latih", "Data uji"),
Observasi = c(
nrow(data_sim),
nrow(data_train),
nrow(data_test)
),
Peubah = c(
ncol(data_sim),
ncol(data_train),
ncol(data_test)
)
)| Dataset | Observasi | Peubah |
|---|---|---|
| Data keseluruhan | 300 | 19 |
| Data latih | 240 | 19 |
| Data uji | 60 | 19 |
Mengapa pembagian ini penting untuk seleksi variabel?
Kita nantinya akan membandingkan empat model:
Regresi linear dengan seluruh prediktor (full model).
Regresi linear setelah Filtering.
Regresi linear setelah Wrapper menggunakan stepwise selection.
Regresi terpenalisasi menggunakan LASSO (Embedded).
Keempat model harus menggunakan data latih dan data uji yang sama. Dengan begitu, perbedaan hasil prediksi dapat dibandingkan secara adil.
Kita juga akan menggunakan data latih saja untuk menghitung korelasi pada Filtering, menentukan variabel melalui Wrapper, serta memilih parameter penalti LASSO melalui validasi silang. Data uji baru digunakan pada bagian E.
Eksplorasi Hubungan Prediktor dan Respons
Sebelum membangun model, hubungan antara respons dan beberapa prediktor diamati melalui diagram pencar (scatter plot). Eksplorasi ini bertujuan memperlihatkan bahwa hubungan prediktor dengan respons tidak selalu berbentuk linear.
Enam prediktor dipilih untuk mewakili karakteristik yang berbeda:
X1: prediktor yang memiliki pengaruh linear langsung terhadapY.X2: prediktor yang berkorelasi kuat denganX1, tetapi tidak memiliki pengaruh langsung dalam persamaan pembangkitan respons.X3: prediktor yang berkontribusi melalui hubungan kuadratik.X3_sq: hasil transformasi kuadrat dariX3.X4: prediktor dengan pengaruh linear langsung.Z1: prediktor yang tidak memiliki pengaruh dalam persamaan pembangkitan respons.
# Menyiapkan data untuk visualisasi
data_plot <- data_train %>%
dplyr::select(Y, X1, X2, X3, X3_sq, X4, Z1) %>%
tidyr::pivot_longer(
cols = -Y,
names_to = "Prediktor",
values_to = "Nilai"
)
# Visualisasi hubungan prediktor dan respons
ggplot(data_plot, aes(x = Nilai, y = Y)) +
geom_point(
color = "#64748B",
alpha = 0.45,
size = 1.4
) +
geom_smooth(
method = "loess",
formula = y ~ x,
se = FALSE,
span = 0.9,
color = "#1D4ED8",
linewidth = 1
) +
facet_wrap(
~ Prediktor,
scales = "free_x",
ncol = 3
) +
labs(
x = "Nilai Prediktor",
y = "Respons (Y)"
) +
theme_minimal(base_size = 12) +
theme(
strip.text = element_text(face = "bold"),
panel.grid.minor = element_blank()
)Visualisasi menunjukkan bahwa hubungan prediktor dengan respons memiliki karakteristik yang berbeda. X1 dan X4 memperlihatkan kecenderungan positif, sedangkan X2 juga menunjukkan hubungan dengan Y karena berkorelasi kuat dengan X1. Pada X3 terlihat pola kuadratik yang menjadi lebih jelas setelah direpresentasikan melalui X3_sq. Sebaliknya, Z1 tidak memperlihatkan pola hubungan yang kuat.
Perbedaan tersebut menunjukkan bahwa kekuatan hubungan marginal antara prediktor dan respons tidak selalu mencerminkan pengaruh langsung prediktor dalam mekanisme pembangkitan data. Kondisi ini menjadi pertimbangan penting dalam penerapan metode seleksi variabel.
Regresi Linear dengan Seluruh Prediktor
Model awal dibangun menggunakan regresi linear berganda dengan memasukkan seluruh prediktor yang tersedia. Pendekatan ini disebut full model, yaitu model yang belum menerapkan seleksi variabel.
Secara umum, model regresi linear berganda dinyatakan sebagai:
\[Y_i = \beta_0 + \sum_{j=1}^{p}\beta_j X_{ij} + \varepsilon_i\]
dengan \(p\) merupakan jumlah prediktor, \(\beta_0\) adalah intersep, dan \(\beta_j\) merupakan koefisien regresi untuk prediktor ke-\(j\).
Pada praktikum ini, model awal menggunakan seluruh 18 prediktor. Estimasi parameter dilakukan hanya menggunakan data latih.
# Membangun model dengan seluruh prediktor
model_full <- lm(
Y ~ .,
data = data_train
)
# Menampilkan hasil model
summary(model_full)#>
#> Call:
#> lm(formula = Y ~ ., data = data_train)
#>
#> Residuals:
#> Min 1Q Median 3Q Max
#> -8.6481 -1.5280 -0.1829 1.6296 5.5402
#>
#> Coefficients:
#> Estimate Std. Error t value Pr(>|t|)
#> (Intercept) 2.5833199 0.2088869 12.367 < 2e-16 ***
#> X1 1.8246134 0.6816523 2.677 0.00799 **
#> X2 0.4066370 0.6949691 0.585 0.55907
#> X3 0.0038032 0.1587809 0.024 0.98091
#> X3_sq 1.9567815 0.1236434 15.826 < 2e-16 ***
#> X4 1.9743453 0.6646984 2.970 0.00330 **
#> X5 -0.8205646 0.6598049 -1.244 0.21495
#> Z1 -0.0275349 0.1706883 -0.161 0.87199
#> Z2 0.0003536 0.1802335 0.002 0.99844
#> Z3 -0.1417554 0.1616025 -0.877 0.38134
#> Z4 -0.1452449 0.1669707 -0.870 0.38531
#> Z5 -0.1558452 0.1577120 -0.988 0.32415
#> Z6 0.0557960 0.1715204 0.325 0.74526
#> Z7 0.2137552 0.1647574 1.297 0.19585
#> Z8 0.0695075 0.1562923 0.445 0.65695
#> Z9 -0.2109267 0.1561169 -1.351 0.17805
#> Z10 0.1098394 0.1690347 0.650 0.51649
#> Z11 0.1567065 0.1578480 0.993 0.32191
#> Z12 0.0856139 0.1627829 0.526 0.59946
#> ---
#> Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#>
#> Residual standard error: 2.425 on 221 degrees of freedom
#> Multiple R-squared: 0.6779, Adjusted R-squared: 0.6517
#> F-statistic: 25.84 on 18 and 221 DF, p-value: < 2.2e-16
Model regresi linear dengan seluruh 18 prediktor menghasilkan R-squared sebesar 0,6779 dan adjusted R-squared sebesar 0,6517 pada data latih. Artinya, model mampu menjelaskan sekitar 67,79% variasi respons dalam data yang digunakan untuk estimasi. Namun, nilai tersebut belum menunjukkan kemampuan prediksi pada data baru.
Dari seluruh prediktor yang dimasukkan, X1, X3_sq, dan X4 memiliki koefisien yang signifikan pada taraf 5%. Ketiganya sesuai dengan komponen yang digunakan dalam persamaan pembangkitan respons. Sementara itu, X3 tidak signifikan karena pengaruhnya terhadap Y direpresentasikan melalui X3_sq, bukan melalui hubungan linear langsung.
X2 dan X5 juga tidak signifikan meskipun memiliki korelasi kuat dengan X1 dan X4. Kondisi multikolinearitas ini dapat menyulitkan pemisahan kontribusi masing-masing prediktor dan menyebabkan estimasi koefisien menjadi kurang presisi. Seluruh prediktor Z1–Z12 tidak signifikan, sesuai dengan perannya sebagai peubah yang tidak relevan dalam rancangan simulasi.
Hasil tersebut menunjukkan bahwa model lengkap memuat sejumlah prediktor yang tidak memberikan informasi langsung dalam mekanisme pembangkitan respons. Meski demikian, signifikansi koefisien bukan satu-satunya dasar untuk menentukan prediktor yang perlu dipertahankan dalam pemodelan prediktif. Oleh karena itu, tahap berikutnya menerapkan metode seleksi variabel untuk memperoleh model yang lebih sederhana dan membandingkan kemampuan prediksinya dengan model lengkap.
Splitting the Data into Training and Test Sets
Predictive modeling aims to estimate a function that can predict a response variable using information from a set of predictors.
In general, the relationship between the response and predictors is expressed as:
\[Y_i=f(\mathbf{X}_i)+\varepsilon_i\]
where \(f(\mathbf{X}_i)\) represents the systematic component to be estimated and \(\varepsilon_i\) is the random error.
In this practical session, the dataset is divided into 80% training data and 20% test data.
The training set is used for model development and variable selection, while the test set is reserved for final predictive evaluation.
# Import the simulated dataset
data_sim <- readr::read_csv(
"data/sim_data_high_noise_multicol.csv",
show_col_types = FALSE
)
# Split the data into training and test sets
set.seed(2026)
split_data <- rsample::initial_split(
data_sim,
prop = 0.80
)
data_train <- rsample::training(split_data)
data_test <- rsample::testing(split_data)
# Display dataset dimensions
tibble::tibble(
Dataset = c(
"Complete dataset",
"Training set",
"Test set"
),
Observations = c(
nrow(data_sim),
nrow(data_train),
nrow(data_test)
),
Variables = c(
ncol(data_sim),
ncol(data_train),
ncol(data_test)
)
)| Dataset | Observations | Variables |
|---|---|---|
| Complete dataset | 300 | 19 |
| Training set | 240 | 19 |
| Test set | 60 | 19 |
Why is data splitting important for variable selection?
Five main models will be compared:
- Multiple linear regression using all predictors (Full Model).
- Linear regression after Pearson correlation-based Filtering.
- Linear regression after Stepwise Wrapper selection.
- Linear regression after Recursive Feature Elimination (RFE).
- Penalized regression using LASSO (Embedded).
All models must use the same training and test sets to ensure a consistent basis for comparison.
Only the training set is used to calculate correlations for Filtering, select variables using Wrapper methods, and determine the LASSO penalty through cross-validation.
The test set is used only for the final evaluation in Section E.
Exploring Predictor–Response Relationships
Before fitting the models, relationships between the response and selected predictors are explored using scatter plots.
This exploration illustrates that relationships between predictors and the response are not necessarily linear.
Six predictors are selected to represent different characteristics:
X1: a predictor with a direct linear contribution toY.X2: a predictor strongly correlated withX1, but without a direct contribution in the response-generating equation.X3: a predictor contributing through a quadratic relationship.X3_sq: the squared transformation ofX3.X4: a predictor with a direct linear contribution.Z1: a predictor with no direct contribution to the response-generating equation.
# Prepare data for visualization
data_plot <- data_train %>%
dplyr::select(Y, X1, X2, X3, X3_sq, X4, Z1) %>%
tidyr::pivot_longer(
cols = -Y,
names_to = "Predictor",
values_to = "Value"
)
# Visualize predictor-response relationships
ggplot(data_plot, aes(x = Value, y = Y)) +
geom_point(
color = "#64748B",
alpha = 0.45,
size = 1.4
) +
geom_smooth(
method = "loess",
formula = y ~ x,
se = FALSE,
span = 0.9,
color = "#1D4ED8",
linewidth = 1
) +
facet_wrap(
~ Predictor,
scales = "free_x",
ncol = 3
) +
labs(
x = "Predictor Value",
y = "Response (Y)"
) +
theme_minimal(base_size = 12) +
theme(
strip.text = element_text(face = "bold"),
panel.grid.minor = element_blank()
)The visualizations show different patterns of association between the predictors and the response.
Variables X1 and X4 exhibit positive trends, while X2 also shows a positive association with Y because it is strongly correlated with X1.
Variable X3 displays a quadratic pattern that becomes more clearly represented by X3_sq. In contrast, Z1 does not exhibit a strong systematic relationship with the response.
These patterns indicate that the strength of a marginal association between a predictor and the response does not necessarily reflect its direct contribution to the response-generating mechanism.
This distinction is important when applying different variable selection methods.
Multiple Linear Regression with All Predictors
The initial model is fitted using multiple linear regression and includes all available predictors.
This approach is referred to as the Full Model, since no variable selection has yet been applied.
The general multiple linear regression model is:
\[Y_i = \beta_0 + \sum_{j=1}^{p}\beta_jX_{ij} + \varepsilon_i\]
where \(p\) denotes the number of predictors, \(\beta_0\) is the intercept, and \(\beta_j\) is the regression coefficient associated with the \(j\)-th predictor.
In this practical session, the Full Model includes all 18 predictors.
Model parameters are estimated using the training set only.
# Fit the model using all predictors
model_full <- lm(
Y ~ .,
data = data_train
)
# Display the model summary
summary(model_full)#>
#> Call:
#> lm(formula = Y ~ ., data = data_train)
#>
#> Residuals:
#> Min 1Q Median 3Q Max
#> -8.6481 -1.5280 -0.1829 1.6296 5.5402
#>
#> Coefficients:
#> Estimate Std. Error t value Pr(>|t|)
#> (Intercept) 2.5833199 0.2088869 12.367 < 2e-16 ***
#> X1 1.8246134 0.6816523 2.677 0.00799 **
#> X2 0.4066370 0.6949691 0.585 0.55907
#> X3 0.0038032 0.1587809 0.024 0.98091
#> X3_sq 1.9567815 0.1236434 15.826 < 2e-16 ***
#> X4 1.9743453 0.6646984 2.970 0.00330 **
#> X5 -0.8205646 0.6598049 -1.244 0.21495
#> Z1 -0.0275349 0.1706883 -0.161 0.87199
#> Z2 0.0003536 0.1802335 0.002 0.99844
#> Z3 -0.1417554 0.1616025 -0.877 0.38134
#> Z4 -0.1452449 0.1669707 -0.870 0.38531
#> Z5 -0.1558452 0.1577120 -0.988 0.32415
#> Z6 0.0557960 0.1715204 0.325 0.74526
#> Z7 0.2137552 0.1647574 1.297 0.19585
#> Z8 0.0695075 0.1562923 0.445 0.65695
#> Z9 -0.2109267 0.1561169 -1.351 0.17805
#> Z10 0.1098394 0.1690347 0.650 0.51649
#> Z11 0.1567065 0.1578480 0.993 0.32191
#> Z12 0.0856139 0.1627829 0.526 0.59946
#> ---
#> Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#>
#> Residual standard error: 2.425 on 221 degrees of freedom
#> Multiple R-squared: 0.6779, Adjusted R-squared: 0.6517
#> F-statistic: 25.84 on 18 and 221 DF, p-value: < 2.2e-16
The Full Model produces an R-squared of 0.6779 and an adjusted R-squared of 0.6517 on the training set.
This indicates that the model explains approximately 67.79% of the variation in the response within the data used for estimation. However, this result does not establish its predictive performance on new observations.
Among the 18 predictors, X1, X3_sq, and X4 have statistically significant coefficients at the 5% significance level. These variables correspond to the components included in the response-generating equation.
In contrast, X3 is not statistically significant because its contribution to the response is represented through X3_sq, rather than through a direct linear term.
Variables X2 and X5 are also not statistically significant, despite being strongly correlated with X1 and X4, respectively. This multicollinearity can make it difficult to distinguish the individual contributions of correlated predictors and may reduce the precision of coefficient estimates.
All predictors Z1 through Z12 are statistically insignificant, consistent with their roles as irrelevant predictors in the simulation design.
These results show that the Full Model includes predictors that do not directly contribute to the response-generating mechanism.
Nevertheless, coefficient significance is not the only criterion for deciding whether a predictor should be retained for predictive modeling.
Therefore, variable selection methods are applied to obtain simpler models and evaluate whether they can maintain or improve predictive performance.
I · B. Seleksi Variabel Menggunakan FilteringI · B. Variable Selection Using Filtering
Filtering memberi peringkat prediktor sebelum model akhir dibentuk. Korelasi Pearson menilai hubungan linear sehingga pola kuadrat dapat terlewat.Filtering ranks predictors before fitting the final model. Pearson correlation measures linear association and can miss quadratic relationships.
Pemeringkatan Prediktor Berdasarkan Korelasi Pearson
Filtering merupakan metode seleksi variabel yang mengevaluasi relevansi setiap prediktor secara individual tanpa terlebih dahulu membangun model yang menggunakan seluruh prediktor.
Salah satu ukuran yang dapat digunakan pada regresi adalah koefisien korelasi Pearson:
\[r_{X_j,Y} = \frac{ \sum_{i=1}^{n}(X_{ij}-\bar{X}_j)(Y_i-\bar{Y}) }{ \sqrt{ \sum_{i=1}^{n}(X_{ij}-\bar{X}_j)^2 } \sqrt{ \sum_{i=1}^{n}(Y_i-\bar{Y})^2 } }\]
dengan \(X_j\) merupakan prediktor ke-\(j\), \(Y\) merupakan respons, dan \(n\) merupakan jumlah observasi pada data latih.
Pemeringkatan dilakukan menggunakan nilai absolut korelasi:
\[S_j = |r_{X_j,Y}|\]
Nilai \(S_j\) yang lebih besar menunjukkan hubungan linear marginal yang lebih kuat antara prediktor dan respons. Pada praktikum ini, enam prediktor dengan nilai \(S_j\) terbesar dipilih untuk membangun model hasil Filtering.
# Menghitung korelasi setiap prediktor dengan Y
hasil_filter <- data_train %>%
dplyr::select(-Y) %>%
purrr::map_dbl(
~ cor(.x, data_train$Y, use = "complete.obs")
) %>%
tibble::enframe(
name = "Prediktor",
value = "Korelasi"
) %>%
dplyr::mutate(
Korelasi_Absolut = abs(Korelasi)
) %>%
dplyr::arrange(
dplyr::desc(Korelasi_Absolut)
) %>%
dplyr::mutate(
Peringkat = dplyr::row_number(),
Status = dplyr::if_else(
Peringkat <= 6,
"Dipilih",
"Tidak dipilih"
)
)
# Menampilkan pemeringkatan
hasil_filter %>%
dplyr::select(
Peringkat,
Prediktor,
Korelasi,
Korelasi_Absolut,
Status
) %>%
knitr::kable(
digits = 3,
caption = "Pemeringkatan prediktor berdasarkan korelasi Pearson pada data latih."
)| Peringkat | Prediktor | Korelasi | Korelasi_Absolut | Status |
|---|---|---|---|---|
| 1 | X3_sq | 0.578 | 0.578 | Dipilih |
| 2 | X1 | 0.430 | 0.430 | Dipilih |
| 3 | X2 | 0.420 | 0.420 | Dipilih |
| 4 | X4 | 0.270 | 0.270 | Dipilih |
| 5 | X5 | 0.224 | 0.224 | Dipilih |
| 6 | Z11 | 0.172 | 0.172 | Dipilih |
| 7 | Z7 | 0.147 | 0.147 | Tidak dipilih |
| 8 | Z5 | -0.097 | 0.097 | Tidak dipilih |
| 9 | Z2 | -0.081 | 0.081 | Tidak dipilih |
| 10 | Z3 | -0.066 | 0.066 | Tidak dipilih |
| 11 | Z10 | 0.054 | 0.054 | Tidak dipilih |
| 12 | Z1 | 0.037 | 0.037 | Tidak dipilih |
| 13 | Z4 | 0.029 | 0.029 | Tidak dipilih |
| 14 | X3 | -0.016 | 0.016 | Tidak dipilih |
| 15 | Z8 | -0.014 | 0.014 | Tidak dipilih |
| 16 | Z6 | -0.013 | 0.013 | Tidak dipilih |
| 17 | Z9 | -0.007 | 0.007 | Tidak dipilih |
| 18 | Z12 | 0.004 | 0.004 | Tidak dipilih |
Visualisasi Hasil Pemeringkatan
ggplot(
hasil_filter,
aes(
x = reorder(Prediktor, Korelasi_Absolut),
y = Korelasi_Absolut,
fill = Status
)
) +
geom_col(width = 0.75) +
coord_flip() +
scale_fill_manual(
values = c(
"Dipilih" = "#2563EB",
"Tidak dipilih" = "#CBD5E1"
)
) +
labs(
x = "Prediktor",
y = "Nilai Absolut Korelasi Pearson",
fill = "Status Seleksi"
) +
theme_minimal(base_size = 12) +
theme(
panel.grid.minor = element_blank(),
legend.position = "bottom"
)Berdasarkan korelasi Pearson, enam prediktor yang terpilih adalah X3_sq, X1, X2, X4, X5, dan Z11. X3_sq memiliki korelasi absolut tertinggi terhadap Y (0,578), diikuti X1 (0,430) dan X2 (0,420). Ketiga prediktor yang memiliki pengaruh langsung dalam persamaan pembangkitan respons, yaitu X1, X3_sq, dan X4, berhasil masuk dalam kelompok terpilih.
Namun, Filtering juga memilih X2 dan X5 yang tidak memiliki pengaruh langsung terhadap respons, tetapi berkorelasi kuat dengan X1 dan X4. Selain itu, Z11 ikut terpilih meskipun merupakan prediktor noise. Korelasi Z11 sebesar 0,172 mencerminkan hubungan yang muncul pada sampel, bukan pengaruh yang ditetapkan dalam mekanisme pembangkitan data.
Sebaliknya, X3 menempati peringkat ke-14 dengan korelasi sebesar -0,016, meskipun memiliki hubungan kuadratik dengan respons. Hasil ini memperlihatkan keterbatasan Filtering berbasis korelasi Pearson: penilaian dilakukan secara individual dan berdasarkan hubungan linear, sehingga belum mempertimbangkan ketergantungan antarprediktor maupun bentuk hubungan nonlinear.
Membangun Model Hasil Filtering
Enam prediktor dengan nilai absolut korelasi Pearson tertinggi digunakan untuk membangun model regresi linear. Model ini kemudian dibandingkan dengan model lengkap pada tahap evaluasi akhir.
# Mengambil enam prediktor hasil Filtering
prediktor_filter <- hasil_filter %>%
dplyr::filter(Peringkat <= 6) %>%
dplyr::pull(Prediktor)
# Membentuk formula regresi
formula_filter <- stats::reformulate(
prediktor_filter,
response = "Y"
)
# Membangun model pada data latih
model_filter <- lm(
formula_filter,
data = data_train
)
# Menampilkan hasil model
summary(model_filter)#>
#> Call:
#> lm(formula = formula_filter, data = data_train)
#>
#> Residuals:
#> Min 1Q Median 3Q Max
#> -9.3374 -1.5475 0.0125 1.6489 6.0435
#>
#> Coefficients:
#> Estimate Std. Error t value Pr(>|t|)
#> (Intercept) 2.6149 0.2031 12.877 < 2e-16 ***
#> X3_sq 1.9545 0.1209 16.169 < 2e-16 ***
#> X1 1.7852 0.6505 2.744 0.006537 **
#> X2 0.4349 0.6613 0.658 0.511443
#> X4 2.1322 0.6319 3.374 0.000867 ***
#> X5 -0.9867 0.6335 -1.558 0.120653
#> Z11 0.2096 0.1516 1.383 0.168006
#> ---
#> Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#>
#> Residual standard error: 2.406 on 233 degrees of freedom
#> Multiple R-squared: 0.6658, Adjusted R-squared: 0.6572
#> F-statistic: 77.36 on 6 and 233 DF, p-value: < 2.2e-16
Model hasil Filtering menggunakan enam prediktor dan menghasilkan R-squared sebesar 0,6658, sedikit lebih rendah dibandingkan full model (0,6779). Namun, adjusted R-squared meningkat dari 0,6517 menjadi 0,6572, sedangkan residual standard error menurun dari 2,425 menjadi 2,406. Hasil ini menunjukkan bahwa pengurangan jumlah prediktor tidak banyak mengurangi kecocokan model pada data latih.
X1, X3_sq, dan X4 tetap memiliki koefisien yang signifikan, sedangkan X2, X5, dan Z11 tidak signifikan. Hasil tersebut memperlihatkan bahwa pemilihan berdasarkan korelasi individual masih dapat mempertahankan prediktor yang memberikan informasi tumpang tindih atau tidak memiliki pengaruh langsung dalam mekanisme pembangkitan respons.
Meskipun model hasil Filtering lebih ringkas, peningkatan adjusted R-squared belum cukup untuk menyimpulkan bahwa kemampuan prediksinya lebih baik. Hal tersebut perlu diperiksa melalui RMSE pada data uji dalam tahap perbandingan model.
Ranking Predictors Using Pearson Correlation
Filtering evaluates the relevance of each predictor individually, without first fitting a predictive model containing all predictors.
For regression problems, one commonly used measure is the Pearson correlation coefficient:
\[r_{X_j,Y} = \frac{ \sum_{i=1}^{n} (X_{ij}-\bar{X}_j)(Y_i-\bar{Y}) }{ \sqrt{ \sum_{i=1}^{n}(X_{ij}-\bar{X}_j)^2 } \sqrt{ \sum_{i=1}^{n}(Y_i-\bar{Y})^2 } }\]
where \(X_j\) denotes the \(j\)-th predictor, \(Y\) is the response variable, and \(n\) is the number of training observations.
Predictors are ranked using the absolute correlation coefficient:
\[S_j=|r_{X_j,Y}|\]
A larger value of \(S_j\) indicates a stronger marginal linear association between the predictor and the response.
In this practical session, the six predictors with the highest absolute correlations are selected to build the Filtering model.
The Top-6 rule is used for demonstration and comparison purposes; it is not claimed to represent the optimal number of predictors.
# Calculate correlations between each predictor and Y
hasil_filter <- data_train %>%
dplyr::select(-Y) %>%
purrr::map_dbl(
~ cor(.x, data_train$Y, use = "complete.obs")
) %>%
tibble::enframe(
name = "Predictor",
value = "Correlation"
) %>%
dplyr::mutate(
Absolute_Correlation = abs(Correlation)
) %>%
dplyr::arrange(
dplyr::desc(Absolute_Correlation)
) %>%
dplyr::mutate(
Rank = dplyr::row_number(),
Status = dplyr::if_else(
Rank <= 6,
"Selected",
"Not selected"
)
)
# Display predictor rankings
hasil_filter %>%
dplyr::select(
Rank,
Predictor,
Correlation,
Absolute_Correlation,
Status
) %>%
knitr::kable(
digits = 3,
caption = "Predictor ranking based on Pearson correlation in the training set."
)| Rank | Predictor | Correlation | Absolute_Correlation | Status |
|---|---|---|---|---|
| 1 | X3_sq | 0.578 | 0.578 | Selected |
| 2 | X1 | 0.430 | 0.430 | Selected |
| 3 | X2 | 0.420 | 0.420 | Selected |
| 4 | X4 | 0.270 | 0.270 | Selected |
| 5 | X5 | 0.224 | 0.224 | Selected |
| 6 | Z11 | 0.172 | 0.172 | Selected |
| 7 | Z7 | 0.147 | 0.147 | Not selected |
| 8 | Z5 | -0.097 | 0.097 | Not selected |
| 9 | Z2 | -0.081 | 0.081 | Not selected |
| 10 | Z3 | -0.066 | 0.066 | Not selected |
| 11 | Z10 | 0.054 | 0.054 | Not selected |
| 12 | Z1 | 0.037 | 0.037 | Not selected |
| 13 | Z4 | 0.029 | 0.029 | Not selected |
| 14 | X3 | -0.016 | 0.016 | Not selected |
| 15 | Z8 | -0.014 | 0.014 | Not selected |
| 16 | Z6 | -0.013 | 0.013 | Not selected |
| 17 | Z9 | -0.007 | 0.007 | Not selected |
| 18 | Z12 | 0.004 | 0.004 | Not selected |
Visualizing Predictor Rankings
ggplot(
hasil_filter,
aes(
x = reorder(Predictor, Absolute_Correlation),
y = Absolute_Correlation,
fill = Status
)
) +
geom_col(width = 0.75) +
coord_flip() +
scale_fill_manual(
values = c(
"Selected" = "#2563EB",
"Not selected" = "#CBD5E1"
)
) +
labs(
x = "Predictor",
y = "Absolute Pearson Correlation",
fill = "Selection Status"
) +
theme_minimal(base_size = 12) +
theme(
panel.grid.minor = element_blank(),
legend.position = "bottom"
)Based on Pearson correlation, the six selected predictors are X3_sq, X1, X2, X4, X5, and Z11.
The highest absolute correlation with Y is observed for X3_sq (0.578), followed by X1 (0.430) and X2 (0.420).
All three predictors that directly contribute to the systematic response function, namely X1, X3_sq, and X4, are included among the selected variables.
However, Filtering also selects X2 and X5, which do not directly contribute to the response but are strongly correlated with X1 and X4.
In addition, Z11 is selected despite being an irrelevant predictor in the simulation design. Its correlation of 0.172 reflects an association observed in the sample rather than a direct contribution specified in the data-generating mechanism.
Conversely, X3 ranks 14th with a correlation of -0.016, despite having a quadratic relationship with the response.
This result illustrates a limitation of Pearson correlation-based Filtering: predictors are evaluated individually using a measure of linear association, without accounting for dependencies among predictors or nonlinear functional relationships.
Building the Filtering Model
The six predictors with the highest absolute Pearson correlations are used to fit a multiple linear regression model.
This model will later be compared with the Full Model using the test set.
# Extract the six selected predictors
prediktor_filter <- hasil_filter %>%
dplyr::filter(Rank <= 6) %>%
dplyr::pull(Predictor)
# Construct the regression formula
formula_filter <- stats::reformulate(
prediktor_filter,
response = "Y"
)
# Fit the model on the training set
model_filter <- lm(
formula_filter,
data = data_train
)
# Display the model summary
summary(model_filter)#>
#> Call:
#> lm(formula = formula_filter, data = data_train)
#>
#> Residuals:
#> Min 1Q Median 3Q Max
#> -9.3374 -1.5475 0.0125 1.6489 6.0435
#>
#> Coefficients:
#> Estimate Std. Error t value Pr(>|t|)
#> (Intercept) 2.6149 0.2031 12.877 < 2e-16 ***
#> X3_sq 1.9545 0.1209 16.169 < 2e-16 ***
#> X1 1.7852 0.6505 2.744 0.006537 **
#> X2 0.4349 0.6613 0.658 0.511443
#> X4 2.1322 0.6319 3.374 0.000867 ***
#> X5 -0.9867 0.6335 -1.558 0.120653
#> Z11 0.2096 0.1516 1.383 0.168006
#> ---
#> Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#>
#> Residual standard error: 2.406 on 233 degrees of freedom
#> Multiple R-squared: 0.6658, Adjusted R-squared: 0.6572
#> F-statistic: 77.36 on 6 and 233 DF, p-value: < 2.2e-16
The Filtering model includes six predictors and produces an R-squared of 0.6658, slightly lower than the Full Model’s R-squared of 0.6779.
However, adjusted R-squared increases from 0.6517 to 0.6572, while the residual standard error decreases from 2.425 to 2.406.
These results indicate that reducing the number of predictors does not substantially reduce model fit on the training set.
Variables X1, X3_sq, and X4 remain statistically significant, whereas X2, X5, and Z11 are not statistically significant.
This finding illustrates that selection based on individual correlations may retain predictors containing redundant information or predictors without a direct contribution to the response-generating mechanism.
Although the Filtering model is more parsimonious, the increase in adjusted R-squared is not sufficient to conclude that its predictive performance is superior.
Predictive performance must be evaluated using RMSE on the test set in the final model comparison.
Korelasi linear dan hubungan kuadratLinear correlation and quadratic relationships
Ubah koefisien linear pada y = ax + x², dengan x = −3, −2, −1, 0, 1, 2, 3.Change the linear coefficient in y = ax + x² for x = −3, −2, −1, 0, 1, 2, 3.
Data ilustratif, bukan hasil estimasi R pada dataset praktikum.Illustrative data, not estimated R results for the practicum dataset.
I · C. Seleksi Variabel Menggunakan Metode WrapperI · C. Variable Selection Using Wrapper Methods
Wrapper membandingkan subset melalui model. Forward menambah prediktor, backward menghapus prediktor, dan RFE mengevaluasi ukuran subset melalui resampling.Wrapper methods compare subsets through models. Forward adds predictors, backward removes them, and RFE evaluates subset sizes through resampling.
Metode Wrapper melakukan seleksi variabel dengan membangun dan mengevaluasi model menggunakan subset prediktor yang berbeda. Berbeda dengan Filtering yang menilai setiap prediktor secara individual, Wrapper mempertimbangkan prediktor melalui keterlibatannya dalam suatu model.
Pencarian subset dapat dilakukan secara sekuensial, seperti Forward Selection, Backward Elimination, dan Bidirectional Stepwise, maupun melalui eliminasi rekursif berdasarkan kepentingan variabel, seperti Recursive Feature Elimination (RFE).
Pada praktikum ini, keempat metode diterapkan menggunakan regresi linear sebagai model dasar. Seluruh proses seleksi dilakukan pada data latih.
Persiapan Model untuk Seleksi Variabel
Sebelum menjalankan metode Wrapper, disiapkan dua model sebagai titik awal pencarian:
- Null model, yaitu model yang hanya memiliki intersep.
- Full model, yaitu model yang menggunakan seluruh 18 prediktor.
# Model tanpa prediktor
model_null <- lm(
Y ~ 1,
data = data_train
)
# Model dengan seluruh prediktor
model_full <- lm(
Y ~ .,
data = data_train
)
# Formula yang mencakup seluruh prediktor
formula_full <- stats::reformulate(
setdiff(names(data_train), "Y"),
response = "Y"
)Forward Selection
Forward Selection merupakan prosedur seleksi sekuensial yang dimulai dari model tanpa prediktor.
Pada setiap langkah, algoritma mengevaluasi penambahan setiap prediktor yang belum masuk ke dalam model. Prediktor yang menghasilkan perbaikan terbesar berdasarkan kriteria pemilihan akan ditambahkan.
Proses berlanjut hingga tidak ada lagi penambahan prediktor yang memperbaiki nilai kriteria.
Dalam praktikum ini digunakan Akaike Information Criterion (AIC):
\[\mathrm{AIC}=-2\log(L)+2k\]
dengan \(L\) merupakan likelihood model dan \(k\) merupakan jumlah parameter yang diestimasi.
Nilai AIC yang lebih kecil menunjukkan keseimbangan yang lebih baik antara kecocokan model dan kompleksitasnya.
# Forward Selection berdasarkan AIC
model_forward <- MASS::stepAIC(
object = model_null,
scope = list(
lower = ~ 1,
upper = formula_full
),
direction = "forward",
trace = FALSE
)
# Tahapan penambahan prediktor
knitr::kable(
model_forward$anova,
digits = 3,
caption = "Tahapan Forward Selection berdasarkan AIC."
)| Step | Df | Deviance | Resid. Df | Resid. Dev | AIC |
|---|---|---|---|---|---|
| NA | NA | 239 | 4035.213 | 679.322 | |
| + X3_sq | 1 | 1348.526 | 238 | 2686.687 | 583.702 |
| + X1 | 1 | 1007.639 | 237 | 1679.049 | 472.882 |
| + X4 | 1 | 301.308 | 236 | 1377.741 | 427.415 |
| + Z7 | 1 | 20.164 | 235 | 1357.577 | 425.876 |
| + Z9 | 1 | 14.898 | 234 | 1342.679 | 425.228 |
# Prediktor terpilih
attr(terms(model_forward), "term.labels")#> [1] "X3_sq" "X1" "X4" "Z7" "Z9"
Backward Elimination
Backward Elimination menggunakan arah pencarian yang berlawanan dengan Forward Selection.
Proses dimulai dari model lengkap yang mencakup seluruh prediktor. Pada setiap langkah, algoritma mengevaluasi penghapusan masing-masing prediktor dan memilih penghapusan yang menghasilkan perbaikan nilai AIC.
Prosedur dihentikan ketika penghapusan prediktor berikutnya tidak lagi menghasilkan nilai AIC yang lebih kecil.
# Backward Elimination berdasarkan AIC
model_backward <- MASS::stepAIC(
object = model_full,
direction = "backward",
trace = FALSE
)
# Tahapan penghapusan prediktor
knitr::kable(
model_backward$anova,
digits = 3,
caption = "Tahapan Backward Elimination berdasarkan AIC."
)| Step | Df | Deviance | Resid. Df | Resid. Dev | AIC |
|---|---|---|---|---|---|
| NA | NA | 221 | 1299.742 | 443.428 | |
| - Z2 | 1 | 0.000 | 222 | 1299.742 | 441.428 |
| - X3 | 1 | 0.004 | 223 | 1299.746 | 439.428 |
| - Z1 | 1 | 0.157 | 224 | 1299.903 | 437.457 |
| - Z6 | 1 | 0.693 | 225 | 1300.596 | 435.585 |
| - Z8 | 1 | 1.289 | 226 | 1301.885 | 433.823 |
| - X2 | 1 | 1.825 | 227 | 1303.710 | 432.159 |
| - Z12 | 1 | 2.125 | 228 | 1305.835 | 430.550 |
| - Z10 | 1 | 3.483 | 229 | 1309.318 | 429.189 |
| - Z3 | 1 | 4.249 | 230 | 1313.567 | 427.967 |
| - Z4 | 1 | 4.988 | 231 | 1318.555 | 426.877 |
| - Z5 | 1 | 4.977 | 232 | 1323.532 | 425.781 |
| - Z11 | 1 | 8.598 | 233 | 1332.130 | 425.335 |
| - X5 | 1 | 10.549 | 234 | 1342.679 | 425.228 |
# Prediktor yang dipertahankan
attr(terms(model_backward), "term.labels")#> [1] "X1" "X3_sq" "X4" "Z7" "Z9"
Bidirectional Stepwise Selection
Bidirectional Stepwise menggabungkan kemungkinan penambahan dan penghapusan prediktor dalam satu proses pencarian.
Berbeda dengan Forward Selection atau Backward Elimination yang bergerak dalam satu arah, metode ini dapat mempertimbangkan kembali variabel yang telah dihapus atau menghapus variabel yang sebelumnya dimasukkan.
Pada praktikum ini, pencarian dimulai dari model lengkap. Dengan demikian, langkah awal berupa penghapusan prediktor, tetapi variabel yang telah dikeluarkan dapat dimasukkan kembali apabila tindakan tersebut memperbaiki nilai AIC.
# Bidirectional Stepwise berdasarkan AIC
model_stepwise <- MASS::stepAIC(
object = model_full,
scope = list(
lower = ~ 1,
upper = formula_full
),
direction = "both",
trace = FALSE
)
# Tahapan seleksi
knitr::kable(
model_stepwise$anova,
digits = 3,
caption = "Tahapan Bidirectional Stepwise berdasarkan AIC."
)| Step | Df | Deviance | Resid. Df | Resid. Dev | AIC |
|---|---|---|---|---|---|
| NA | NA | 221 | 1299.742 | 443.428 | |
| - Z2 | 1 | 0.000 | 222 | 1299.742 | 441.428 |
| - X3 | 1 | 0.004 | 223 | 1299.746 | 439.428 |
| - Z1 | 1 | 0.157 | 224 | 1299.903 | 437.457 |
| - Z6 | 1 | 0.693 | 225 | 1300.596 | 435.585 |
| - Z8 | 1 | 1.289 | 226 | 1301.885 | 433.823 |
| - X2 | 1 | 1.825 | 227 | 1303.710 | 432.159 |
| - Z12 | 1 | 2.125 | 228 | 1305.835 | 430.550 |
| - Z10 | 1 | 3.483 | 229 | 1309.318 | 429.189 |
| - Z3 | 1 | 4.249 | 230 | 1313.567 | 427.967 |
| - Z4 | 1 | 4.988 | 231 | 1318.555 | 426.877 |
| - Z5 | 1 | 4.977 | 232 | 1323.532 | 425.781 |
| - Z11 | 1 | 8.598 | 233 | 1332.130 | 425.335 |
| - X5 | 1 | 10.549 | 234 | 1342.679 | 425.228 |
# Prediktor terpilih
attr(terms(model_stepwise), "term.labels")#> [1] "X1" "X3_sq" "X4" "Z7" "Z9"
Perbandingan Hasil Sequential Selection
Ketiga metode sekuensial menggunakan AIC sebagai kriteria, tetapi memiliki arah pencarian yang berbeda. Oleh karena itu, subset yang diperoleh tidak harus sama.
Untuk membandingkan hasilnya, ditampilkan jumlah prediktor, AIC model akhir, dan variabel yang dipertahankan.
# Mengumpulkan model sequential selection
model_sequential <- list(
Forward = model_forward,
Backward = model_backward,
Stepwise = model_stepwise
)
# Ringkasan hasil
ringkasan_sequential <- purrr::imap_dfr(
model_sequential,
function(model, metode) {
variabel <- attr(
terms(model),
"term.labels"
)
tibble::tibble(
Metode = metode,
Jumlah_Prediktor = length(variabel),
AIC = stats::extractAIC(model)[2],
Prediktor_Terpilih = paste(
variabel,
collapse = ", "
)
)
}
)
knitr::kable(
ringkasan_sequential,
digits = 3,
caption = "Perbandingan Forward, Backward, dan Bidirectional Stepwise."
)| Metode | Jumlah_Prediktor | AIC | Prediktor_Terpilih |
|---|---|---|---|
| Forward | 5 | 425.228 | X3_sq, X1, X4, Z7, Z9 |
| Backward | 5 | 425.228 | X1, X3_sq, X4, Z7, Z9 |
| Stepwise | 5 | 425.228 | X1, X3_sq, X4, Z7, Z9 |
Ketiga metode sequential selection menghasilkan subset yang sama, yaitu X1, X3_sq, X4, Z7, dan Z9, dengan nilai AIC akhir sebesar 425,228. Meskipun demikian, proses pencariannya berbeda. Forward Selection membangun model dari intersep saja dengan menambahkan prediktor secara bertahap, sedangkan Backward Elimination mengurangi jumlah prediktor dari 18 menjadi 5. Bidirectional Stepwise menghasilkan urutan penghapusan yang sama dengan Backward Elimination karena tidak terdapat penambahan kembali variabel yang memperbaiki AIC.
Ketiga metode berhasil mempertahankan X1, X3_sq, dan X4, yaitu prediktor yang membentuk komponen sistematis dalam persamaan pembangkitan respons. Sebaliknya, X2 dan X5 yang berkorelasi kuat dengan prediktor relevan tidak dipertahankan. Hasil ini menunjukkan bahwa seleksi berdasarkan evaluasi model dapat mengurangi penggunaan prediktor yang memiliki informasi tumpang tindih.
Meskipun demikian, Z7 dan Z9 tetap terpilih meskipun keduanya merupakan prediktor noise dalam rancangan simulasi. Pada Forward Selection, penambahan kedua prediktor tersebut masih menurunkan AIC, meskipun penurunannya relatif kecil. Hal ini memperlihatkan bahwa kriteria AIC menyeimbangkan kecocokan dan kompleksitas model, tetapi tidak menjamin bahwa seluruh variabel terpilih benar-benar relevan dalam mekanisme pembangkitan data.
Kesamaan hasil ketiga metode pada simulasi ini tidak berarti bahwa arah pencarian selalu menghasilkan subset yang identik. Selain itu, karena seleksi dilakukan berdasarkan AIC pada data latih, kemampuan prediksi model tetap perlu dievaluasi menggunakan data uji.
Recursive Feature Elimination (RFE)
Recursive Feature Elimination (RFE) merupakan metode seleksi variabel berbasis Wrapper yang dilakukan dengan mengeliminasi prediktor secara bertahap berdasarkan tingkat kepentingannya dalam model. Pada setiap tahap, model dibangun menggunakan sejumlah prediktor tertentu, kemudian kinerja prediksinya dievaluasi.
Berbeda dengan Forward Selection, Backward Elimination, dan Bidirectional Stepwise yang sebelumnya menggunakan AIC, RFE pada praktikum ini menggunakan Root Mean Squared Error (RMSE) dari validasi silang sebagai kriteria pemilihan subset.
RFE diterapkan menggunakan regresi linear dengan validasi silang 5-fold. Ukuran subset yang dievaluasi adalah 2, 3, 4, 5, 6, 8, 12, dan 18 prediktor. Subset dengan rata-rata RMSE validasi silang terkecil dipilih sebagai hasil akhir.
Menjalankan RFE
# Menyiapkan data untuk RFE
x_train <- data_train[, names(data_train) != "Y", drop = FALSE]
y_train <- data_train$Y
# Pengaturan RFE menggunakan regresi linear
kontrol_rfe <- caret::rfeControl(
functions = caret::lmFuncs,
method = "cv",
number = 5,
rerank = TRUE,
verbose = FALSE,
allowParallel = FALSE
)
# Menjalankan Recursive Feature Elimination
set.seed(2026)
hasil_rfe <- caret::rfe(
x = x_train,
y = y_train,
sizes = c(2, 3, 4, 5, 6, 8, 12, 18),
metric = "RMSE",
rfeControl = kontrol_rfe
)Evaluasi Ukuran Subset
Hasil validasi silang digunakan untuk membandingkan kinerja setiap ukuran subset. Nilai RMSE yang lebih kecil menunjukkan kesalahan prediksi yang lebih rendah.
# Mengambil hasil evaluasi setiap ukuran subset
tabel_rfe <- hasil_rfe$results %>%
dplyr::mutate(
Terpilih = ifelse(
Variables == hasil_rfe$optsize,
"Ya",
"Tidak"
)
) %>%
dplyr::select(
Variables,
RMSE,
RMSESD,
Terpilih
)
# Menampilkan tabel hasil RFE
knitr::kable(
tabel_rfe,
digits = 3,
caption = "Hasil RFE berdasarkan RMSE validasi silang."
)| Variables | RMSE | RMSESD | Terpilih |
|---|---|---|---|
| 2 | 2.677 | 0.104 | Tidak |
| 3 | 2.418 | 0.239 | Tidak |
| 4 | 2.409 | 0.240 | Ya |
| 5 | 2.434 | 0.214 | Tidak |
| 6 | 2.460 | 0.217 | Tidak |
| 8 | 2.510 | 0.199 | Tidak |
| 12 | 2.502 | 0.225 | Tidak |
| 18 | 2.522 | 0.231 | Tidak |
Berdasarkan hasil validasi silang yang diperoleh, subset berukuran empat prediktor menghasilkan RMSE terkecil, yaitu 2,409, dibandingkan ukuran subset lain yang dievaluasi. Penambahan prediktor setelah ukuran tersebut tidak memberikan perbaikan RMSE. Oleh karena itu, RFE memilih empat prediktor sebagai subset terbaik.
Prediktor Terpilih
Setelah ukuran subset terbaik ditentukan, nama prediktor yang dipertahankan dapat diperoleh menggunakan fungsi predictors().
# Mengambil prediktor hasil RFE
prediktor_rfe <- caret::predictors(hasil_rfe)
# Jumlah prediktor terpilih
jumlah_terpilih <- length(prediktor_rfe)
# Menampilkan prediktor terpilih
prediktor_rfe#> [1] "X3_sq" "X1" "X4" "X5"
# Ringkasan prediktor terpilih
tabel_prediktor_rfe <- data.frame(
Metode = "RFE",
Jumlah_Prediktor = jumlah_terpilih,
Prediktor_Terpilih = paste(prediktor_rfe, collapse = ", ")
)
knitr::kable(
tabel_prediktor_rfe,
caption = "Prediktor yang terpilih berdasarkan metode RFE."
)| Metode | Jumlah_Prediktor | Prediktor_Terpilih |
|---|---|---|
| RFE | 4 | X3_sq, X1, X4, X5 |
Pada hasil yang diperoleh sebelumnya, RFE mempertahankan X3_sq, X1, X4, dan X5. Tiga prediktor pertama merupakan komponen yang berkontribusi langsung terhadap pembentukan respons dalam data simulasi, sedangkan X5 merupakan prediktor yang berkorelasi dengan X4.
Hasil ini menunjukkan bahwa RFE dapat mempertahankan prediktor yang relevan terhadap respons, tetapi tidak selalu menghilangkan prediktor yang memiliki informasi tumpang tindih dengan prediktor lainnya.
Membangun Model Hasil RFE
Setelah prediktor terpilih diperoleh, model regresi linear dibangun kembali menggunakan subset tersebut. Model ini selanjutnya digunakan untuk mengevaluasi kinerja prediksi pada data uji.
# Model regresi berdasarkan prediktor hasil RFE
model_rfe <- lm(
stats::reformulate(
prediktor_rfe,
response = "Y"
),
data = data_train
)
# Ringkasan model
summary(model_rfe)#>
#> Call:
#> lm(formula = stats::reformulate(prediktor_rfe, response = "Y"),
#> data = data_train)
#>
#> Residuals:
#> Min 1Q Median 3Q Max
#> -9.2589 -1.4647 -0.0108 1.7251 6.2974
#>
#> Coefficients:
#> Estimate Std. Error t value Pr(>|t|)
#> (Intercept) 2.6052 0.2029 12.837 < 2e-16 ***
#> X3_sq 1.9758 0.1201 16.453 < 2e-16 ***
#> X1 2.2084 0.1691 13.059 < 2e-16 ***
#> X4 2.1786 0.6291 3.463 0.000635 ***
#> X5 -1.0187 0.6318 -1.612 0.108249
#> ---
#> Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#>
#> Residual standard error: 2.408 on 235 degrees of freedom
#> Multiple R-squared: 0.6623, Adjusted R-squared: 0.6566
#> F-statistic: 115.2 on 4 and 235 DF, p-value: < 2.2e-16
Model hasil RFE memiliki nilai R-squared sebesar 0,6623 dan Adjusted R-squared sebesar 0,6566 pada data latih. Prediktor X3_sq, X1, dan X4 menunjukkan pengaruh yang signifikan secara parsial pada taraf 5%, sedangkan X5 tidak signifikan.
Perlu diperhatikan bahwa RFE memilih prediktor berdasarkan kontribusinya terhadap kinerja prediksi, bukan berdasarkan signifikansi koefisien regresi. Oleh karena itu, prediktor yang tidak signifikan secara parsial masih dapat dipertahankan apabila kombinasi prediktor tersebut menghasilkan RMSE validasi silang yang lebih rendah.
Ringkasan Prediktor Hasil Wrapper
Untuk melihat perbedaan variabel yang dipertahankan oleh setiap metode, hasil seleksi disajikan dalam satu tabel.
# Daftar model Wrapper
daftar_wrapper <- list(
Forward = model_forward,
Backward = model_backward,
Stepwise = model_stepwise,
RFE = model_rfe
)
# Tabel prediktor terpilih
ringkasan_wrapper <- purrr::imap_dfr(
daftar_wrapper,
function(model, metode) {
variabel <- attr(
terms(model),
"term.labels"
)
tibble::tibble(
Metode = metode,
Jumlah_Prediktor = length(variabel),
Prediktor_Terpilih = paste(
variabel,
collapse = ", "
)
)
}
)
knitr::kable(
ringkasan_wrapper,
caption = "Perbandingan prediktor terpilih pada empat metode Wrapper."
)| Metode | Jumlah_Prediktor | Prediktor_Terpilih |
|---|---|---|
| Forward | 5 | X3_sq, X1, X4, Z7, Z9 |
| Backward | 5 | X1, X3_sq, X4, Z7, Z9 |
| Stepwise | 5 | X1, X3_sq, X4, Z7, Z9 |
| RFE | 4 | X3_sq, X1, X4, X5 |
Hasil RFE menunjukkan bahwa subset dengan empat prediktor menghasilkan rata-rata RMSE validasi silang terendah, yaitu 2,409. Nilai ini sedikit lebih rendah dibandingkan subset tiga prediktor (2,418), sedangkan penggunaan 18 prediktor menghasilkan RMSE sebesar 2,522. Dengan demikian, penambahan jumlah prediktor tidak selalu menghasilkan kesalahan prediksi yang lebih kecil.
Empat prediktor yang dipertahankan adalah X3_sq, X1, X4, dan X5. RFE berhasil mengidentifikasi ketiga prediktor yang membentuk komponen sistematis respons, sekaligus tidak mempertahankan prediktor noise Z1–Z12. Meskipun demikian, X5 masih terpilih karena berkaitan erat dengan X4. Hal ini menunjukkan bahwa RFE juga belum sepenuhnya menghilangkan informasi yang tumpang tindih antarprediktor.
Model regresi berdasarkan hasil RFE menghasilkan R-squared sebesar 0,6623 dan adjusted R-squared sebesar 0,6566 pada data latih. Dibandingkan dengan metode sequential selection yang mempertahankan lima prediktor, RFE menghasilkan subset yang lebih kecil tanpa perbedaan besar dalam kecocokan model pada data latih.
Hasil ini memperlihatkan bahwa metode Wrapper dapat menghasilkan komposisi variabel yang berbeda ketika menggunakan kriteria seleksi yang berbeda. Namun, RMSE validasi silang RFE belum dapat dibandingkan langsung dengan AIC metode sequential selection. Penilaian kemampuan prediksi seluruh model tetap dilakukan menggunakan data uji yang sama.
Wrapper methods perform variable selection by repeatedly fitting and evaluating predictive models using different subsets of predictors.
Unlike Filtering, which evaluates each predictor individually, Wrapper methods assess predictors through their inclusion in a fitted model.
Subset searches can be performed sequentially through Forward Selection, Backward Elimination, and Bidirectional Stepwise Selection, or recursively through Recursive Feature Elimination (RFE).
In this practical session, all four methods use linear regression as the underlying model. All selection procedures are performed using the training set.
Preparing Models for Variable Selection
Before applying Wrapper methods, two reference models are prepared:
- The Null Model, which contains only an intercept.
- The Full Model, which includes all 18 predictors.
# Intercept-only model
model_null <- lm(
Y ~ 1,
data = data_train
)
# Model with all predictors
model_full <- lm(
Y ~ .,
data = data_train
)
# Formula including all predictors
formula_full <- stats::reformulate(
setdiff(names(data_train), "Y"),
response = "Y"
)Forward Selection
Forward Selection is a sequential variable selection procedure that begins with an intercept-only model.
At each step, the algorithm evaluates adding each predictor that is not yet included in the model.
The predictor that produces the greatest improvement according to the selection criterion is added.
This process continues until adding another predictor no longer improves the selected criterion.
In this practical session, model selection is based on the Akaike Information Criterion (AIC):
\[\mathrm{AIC} = -2\log(L)+2k\]
where \(L\) is the model likelihood and \(k\) represents the number of estimated parameters.
A lower AIC indicates a more favorable balance between model fit and complexity.
# Forward Selection based on AIC
model_forward <- MASS::stepAIC(
object = model_null,
scope = list(
lower = ~ 1,
upper = formula_full
),
direction = "forward",
trace = FALSE
)
# Display variable addition steps
knitr::kable(
model_forward$anova,
digits = 3,
caption = "Forward Selection steps based on AIC."
)| Step | Df | Deviance | Resid. Df | Resid. Dev | AIC |
|---|---|---|---|---|---|
| NA | NA | 239 | 4035.213 | 679.322 | |
| + X3_sq | 1 | 1348.526 | 238 | 2686.687 | 583.702 |
| + X1 | 1 | 1007.639 | 237 | 1679.049 | 472.882 |
| + X4 | 1 | 301.308 | 236 | 1377.741 | 427.415 |
| + Z7 | 1 | 20.164 | 235 | 1357.577 | 425.876 |
| + Z9 | 1 | 14.898 | 234 | 1342.679 | 425.228 |
# Display selected predictors
attr(terms(model_forward), "term.labels")#> [1] "X3_sq" "X1" "X4" "Z7" "Z9"
Backward Elimination
Backward Elimination searches in the opposite direction from Forward Selection.
The procedure begins with the Full Model containing all available predictors.
At each step, the algorithm evaluates removing each predictor and selects the removal that improves AIC the most.
The procedure stops when removing another predictor no longer reduces AIC.
# Backward Elimination based on AIC
model_backward <- MASS::stepAIC(
object = model_full,
direction = "backward",
trace = FALSE
)
# Display variable elimination steps
knitr::kable(
model_backward$anova,
digits = 3,
caption = "Backward Elimination steps based on AIC."
)| Step | Df | Deviance | Resid. Df | Resid. Dev | AIC |
|---|---|---|---|---|---|
| NA | NA | 221 | 1299.742 | 443.428 | |
| - Z2 | 1 | 0.000 | 222 | 1299.742 | 441.428 |
| - X3 | 1 | 0.004 | 223 | 1299.746 | 439.428 |
| - Z1 | 1 | 0.157 | 224 | 1299.903 | 437.457 |
| - Z6 | 1 | 0.693 | 225 | 1300.596 | 435.585 |
| - Z8 | 1 | 1.289 | 226 | 1301.885 | 433.823 |
| - X2 | 1 | 1.825 | 227 | 1303.710 | 432.159 |
| - Z12 | 1 | 2.125 | 228 | 1305.835 | 430.550 |
| - Z10 | 1 | 3.483 | 229 | 1309.318 | 429.189 |
| - Z3 | 1 | 4.249 | 230 | 1313.567 | 427.967 |
| - Z4 | 1 | 4.988 | 231 | 1318.555 | 426.877 |
| - Z5 | 1 | 4.977 | 232 | 1323.532 | 425.781 |
| - Z11 | 1 | 8.598 | 233 | 1332.130 | 425.335 |
| - X5 | 1 | 10.549 | 234 | 1342.679 | 425.228 |
# Display retained predictors
attr(terms(model_backward), "term.labels")#> [1] "X1" "X3_sq" "X4" "Z7" "Z9"
Bidirectional Stepwise Selection
Bidirectional Stepwise Selection combines the possibility of adding and removing predictors within a single search procedure.
Unlike Forward Selection or Backward Elimination, which move in one direction, Bidirectional Stepwise Selection allows variables to be reconsidered during the selection process.
A previously removed predictor may be added back if doing so improves the selection criterion. Similarly, a predictor that was previously included may subsequently be removed.
In this practical session, the search begins with the Full Model.
Therefore, the initial steps involve predictor removal, although previously removed predictors may be reconsidered if reintroducing them reduces AIC.
# Bidirectional Stepwise Selection based on AIC
model_stepwise <- MASS::stepAIC(
object = model_full,
scope = list(
lower = ~ 1,
upper = formula_full
),
direction = "both",
trace = FALSE
)
# Display selection steps
knitr::kable(
model_stepwise$anova,
digits = 3,
caption = "Bidirectional Stepwise Selection steps based on AIC."
)| Step | Df | Deviance | Resid. Df | Resid. Dev | AIC |
|---|---|---|---|---|---|
| NA | NA | 221 | 1299.742 | 443.428 | |
| - Z2 | 1 | 0.000 | 222 | 1299.742 | 441.428 |
| - X3 | 1 | 0.004 | 223 | 1299.746 | 439.428 |
| - Z1 | 1 | 0.157 | 224 | 1299.903 | 437.457 |
| - Z6 | 1 | 0.693 | 225 | 1300.596 | 435.585 |
| - Z8 | 1 | 1.289 | 226 | 1301.885 | 433.823 |
| - X2 | 1 | 1.825 | 227 | 1303.710 | 432.159 |
| - Z12 | 1 | 2.125 | 228 | 1305.835 | 430.550 |
| - Z10 | 1 | 3.483 | 229 | 1309.318 | 429.189 |
| - Z3 | 1 | 4.249 | 230 | 1313.567 | 427.967 |
| - Z4 | 1 | 4.988 | 231 | 1318.555 | 426.877 |
| - Z5 | 1 | 4.977 | 232 | 1323.532 | 425.781 |
| - Z11 | 1 | 8.598 | 233 | 1332.130 | 425.335 |
| - X5 | 1 | 10.549 | 234 | 1342.679 | 425.228 |
# Display selected predictors
attr(terms(model_stepwise), "term.labels")#> [1] "X1" "X3_sq" "X4" "Z7" "Z9"
Comparing Sequential Selection Results
The three sequential methods use AIC as their selection criterion but follow different search directions.
Therefore, they are not guaranteed to produce identical subsets.
The following table compares the number of selected predictors, the final AIC, and the retained variables.
# Collect sequential selection models
model_sequential <- list(
Forward = model_forward,
Backward = model_backward,
Stepwise = model_stepwise
)
# Summarize selection results
ringkasan_sequential <- purrr::imap_dfr(
model_sequential,
function(model, metode) {
variabel <- attr(
terms(model),
"term.labels"
)
tibble::tibble(
Method = metode,
Number_of_Predictors = length(variabel),
AIC = stats::extractAIC(model)[2],
Selected_Predictors = paste(
variabel,
collapse = ", "
)
)
}
)
knitr::kable(
ringkasan_sequential,
digits = 3,
caption = "Comparison of Forward, Backward, and Bidirectional Stepwise Selection."
)| Method | Number_of_Predictors | AIC | Selected_Predictors |
|---|---|---|---|
| Forward | 5 | 425.228 | X3_sq, X1, X4, Z7, Z9 |
| Backward | 5 | 425.228 | X1, X3_sq, X4, Z7, Z9 |
| Stepwise | 5 | 425.228 | X1, X3_sq, X4, Z7, Z9 |
All three sequential methods select the same five predictors: X1, X3_sq, X4, Z7, and Z9, with a final AIC of 425.228.
Nevertheless, their search procedures differ.
Forward Selection begins with an intercept-only model and adds predictors sequentially. Backward Elimination reduces the model from 18 predictors to five. Bidirectional Stepwise Selection follows the same elimination sequence as Backward Elimination because none of the previously removed predictors provides an additional reduction in AIC when reconsidered.
All three methods retain X1, X3_sq, and X4, which form the systematic component of the response-generating equation.
Conversely, X2 and X5, which are strongly correlated with relevant predictors, are not retained.
This result illustrates that model-based selection can reduce the inclusion of predictors containing overlapping information.
However, Z7 and Z9 are still selected, despite being irrelevant predictors in the simulation design.
In Forward Selection, adding these predictors continues to decrease AIC, although the reductions are relatively small.
This illustrates that AIC balances model fit against complexity but does not guarantee that all selected variables are truly relevant to the data-generating mechanism.
The identical results obtained from the three sequential methods in this simulation do not imply that different search directions always lead to the same subset.
Furthermore, since the selection is based on AIC calculated from the training data, predictive performance must still be evaluated on the test set.
Recursive Feature Elimination (RFE)
Recursive Feature Elimination (RFE) is a Wrapper-based variable selection method that progressively eliminates predictors according to their estimated importance within a predictive model.
The procedure begins by fitting a model and ranking predictors based on their importance.
Predictors with lower importance are then removed, and models are refitted using smaller subsets.
Unlike the previous sequential methods, which use AIC, RFE in this practical session selects the subset size based on Root Mean Squared Error (RMSE) obtained through cross-validation.
RFE uses linear regression as the underlying model and five-fold cross-validation to assess predictive performance.
The evaluated subset sizes are 2, 3, 4, 5, 6, 8, 12, and 18 predictors.
The subset size with the lowest mean cross-validation RMSE is selected.
Running RFE
# Prepare predictors for RFE
x_train <- data_train[
,
names(data_train) != "Y",
drop = FALSE
]
y_train <- data_train$Y
# Configure RFE using linear regression
kontrol_rfe <- caret::rfeControl(
functions = caret::lmFuncs,
method = "cv",
number = 5,
rerank = TRUE,
verbose = FALSE,
allowParallel = FALSE
)
# Run Recursive Feature Elimination
set.seed(2026)
hasil_rfe <- caret::rfe(
x = x_train,
y = y_train,
sizes = c(2, 3, 4, 5, 6, 8, 12, 18),
metric = "RMSE",
rfeControl = kontrol_rfe
)Evaluating Subset Sizes
Cross-validation is used to compare predictive performance across different subset sizes.
The mean cross-validation RMSE for each subset size can be expressed as:
\[\mathrm{RMSE}_{CV} = \frac{1}{K} \sum_{k=1}^{K} \sqrt{ \frac{1}{n_k} \sum_{i\in V_k} \left( Y_i-\hat{Y}_i^{(-k)} \right)^2 }\]
where \(K\) is the number of folds, \(V_k\) denotes the validation observations in fold \(k\), \(n_k\) is the number of observations in that fold, and \(\hat{Y}_i^{(-k)}\) is the prediction obtained from a model fitted without using fold \(k\).
A lower mean cross-validation RMSE indicates better predictive performance among the subset sizes evaluated.
# Extract evaluation results for each subset size
tabel_rfe <- hasil_rfe$results %>%
dplyr::mutate(
Selected = ifelse(
Variables == hasil_rfe$optsize,
"Yes",
"No"
)
) %>%
dplyr::select(
Variables,
RMSE,
RMSESD,
Selected
)
# Display RFE results
knitr::kable(
tabel_rfe,
digits = 3,
caption = "RFE results based on cross-validation RMSE."
)| Variables | RMSE | RMSESD | Selected |
|---|---|---|---|
| 2 | 2.677 | 0.104 | No |
| 3 | 2.418 | 0.239 | No |
| 4 | 2.409 | 0.240 | Yes |
| 5 | 2.434 | 0.214 | No |
| 6 | 2.460 | 0.217 | No |
| 8 | 2.510 | 0.199 | No |
| 12 | 2.502 | 0.225 | No |
| 18 | 2.522 | 0.231 | No |
Based on the cross-validation results, the subset containing four predictors produces the lowest RMSE of 2.409 among the evaluated subset sizes.
Adding more predictors beyond this subset size does not improve cross-validation RMSE in this analysis.
Therefore, RFE selects four predictors as the preferred subset size.
Selected Predictors
After identifying the preferred subset size, the retained predictors are extracted using caret::predictors().
# Extract the predictors selected by RFE
prediktor_rfe <- caret::predictors(hasil_rfe)
# Number of selected predictors
jumlah_terpilih <- length(prediktor_rfe)
# Display selected predictors
prediktor_rfe#> [1] "X3_sq" "X1" "X4" "X5"
# Summarize selected predictors
tabel_prediktor_rfe <- data.frame(
Method = "RFE",
Number_of_Predictors = jumlah_terpilih,
Selected_Predictors = paste(
prediktor_rfe,
collapse = ", "
)
)
knitr::kable(
tabel_prediktor_rfe,
caption = "Predictors selected using RFE."
)| Method | Number_of_Predictors | Selected_Predictors |
|---|---|---|
| RFE | 4 | X3_sq, X1, X4, X5 |
In the obtained results, RFE retains X3_sq, X1, X4, and X5.
The first three predictors directly contribute to the systematic response function, whereas X5 is strongly correlated with X4.
This indicates that RFE can retain predictors relevant to the response, but it does not necessarily eliminate all predictors containing overlapping information.
Building the RFE Model
After identifying the selected predictors, a multiple linear regression model is refitted using the selected subset.
This model is subsequently used to evaluate predictive performance on the test set.
# Fit a linear regression model using RFE-selected predictors
model_rfe <- lm(
stats::reformulate(
prediktor_rfe,
response = "Y"
),
data = data_train
)
# Display the model summary
summary(model_rfe)#>
#> Call:
#> lm(formula = stats::reformulate(prediktor_rfe, response = "Y"),
#> data = data_train)
#>
#> Residuals:
#> Min 1Q Median 3Q Max
#> -9.2589 -1.4647 -0.0108 1.7251 6.2974
#>
#> Coefficients:
#> Estimate Std. Error t value Pr(>|t|)
#> (Intercept) 2.6052 0.2029 12.837 < 2e-16 ***
#> X3_sq 1.9758 0.1201 16.453 < 2e-16 ***
#> X1 2.2084 0.1691 13.059 < 2e-16 ***
#> X4 2.1786 0.6291 3.463 0.000635 ***
#> X5 -1.0187 0.6318 -1.612 0.108249
#> ---
#> Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#>
#> Residual standard error: 2.408 on 235 degrees of freedom
#> Multiple R-squared: 0.6623, Adjusted R-squared: 0.6566
#> F-statistic: 115.2 on 4 and 235 DF, p-value: < 2.2e-16
The RFE model produces an R-squared of 0.6623 and an adjusted R-squared of 0.6566 on the training set.
Variables X3_sq, X1, and X4 are statistically significant at the 5% level, whereas X5 is not statistically significant.
It is important to note that RFE selects predictors based on their contribution to predictive performance, rather than the statistical significance of individual regression coefficients.
Therefore, a predictor that is not statistically significant may still be retained if its inclusion contributes to lower cross-validation RMSE.
Summary of Predictors Selected by Wrapper Methods
To examine differences in the predictors retained by each method, the selection results are summarized in one table.
# Collect Wrapper models
daftar_wrapper <- list(
Forward = model_forward,
Backward = model_backward,
Stepwise = model_stepwise,
RFE = model_rfe
)
# Summarize selected predictors
ringkasan_wrapper <- purrr::imap_dfr(
daftar_wrapper,
function(model, metode) {
variabel <- attr(
terms(model),
"term.labels"
)
tibble::tibble(
Method = metode,
Number_of_Predictors = length(variabel),
Selected_Predictors = paste(
variabel,
collapse = ", "
)
)
}
)
knitr::kable(
ringkasan_wrapper,
caption = "Comparison of predictors selected by four Wrapper methods."
)| Method | Number_of_Predictors | Selected_Predictors |
|---|---|---|
| Forward | 5 | X3_sq, X1, X4, Z7, Z9 |
| Backward | 5 | X1, X3_sq, X4, Z7, Z9 |
| Stepwise | 5 | X1, X3_sq, X4, Z7, Z9 |
| RFE | 4 | X3_sq, X1, X4, X5 |
RFE selects four predictors with the lowest mean cross-validation RMSE of 2.409.
This RMSE is slightly lower than that obtained using three predictors (2.418), while the model using all 18 predictors produces an RMSE of 2.522.
Thus, including more predictors does not necessarily result in lower prediction error.
The four predictors selected by RFE are X3_sq, X1, X4, and X5.
RFE successfully retains all three predictors included in the systematic response function and excludes the irrelevant predictors Z1 through Z12.
However, X5 remains selected because it is strongly associated with X4. This indicates that RFE does not completely eliminate redundant information among predictors.
The refitted RFE regression model produces an R-squared of 0.6623 and an adjusted R-squared of 0.6566 on the training set.
Compared with the sequential selection methods, which retain five predictors, RFE produces a smaller subset without a substantial difference in training-set model fit.
These results illustrate that Wrapper methods may produce different predictor subsets when different selection criteria are used.
However, the cross-validation RMSE from RFE cannot be directly compared with the AIC values from sequential selection.
A consistent comparison of predictive performance requires evaluating all models using the same test set.
I · D. Seleksi Variabel Menggunakan Embedded: LASSOI · D. Variable Selection Using Embedded Methods: LASSO
LASSO menyusutkan koefisien melalui penalti L1. Pilih lambda dengan validasi silang pada data latih, lalu bandingkan prediksi pada data uji.LASSO shrinks coefficients through an L1 penalty. Select lambda using training-set cross-validation, then compare test predictions.
Estimasi LASSO dengan Validasi Silang
Metode Embedded mengintegrasikan proses seleksi variabel ke dalam algoritma pemodelan. Salah satu metode yang digunakan dalam regresi adalah Least Absolute Shrinkage and Selection Operator (LASSO).
LASSO mengestimasi parameter regresi dengan menambahkan penalti terhadap nilai absolut koefisien. Secara matematis, estimasi LASSO diperoleh melalui:
\[\hat{\boldsymbol{\beta}}_{\mathrm{LASSO}} = \underset{\beta_0,\boldsymbol{\beta}}{\arg\min} \left\{ \frac{1}{2n} \sum_{i=1}^{n} \left( Y_i-\beta_0-\sum_{j=1}^{p}X_{ij}\beta_j \right)^2 + \lambda\sum_{j=1}^{p}|\beta_j| \right\}\]
dengan \(\lambda \geq 0\) merupakan parameter penalti yang mengendalikan kekuatan penyusutan koefisien. Nilai \(\lambda\) yang lebih besar memberikan penalti lebih kuat dan dapat menyebabkan sebagian koefisien regresi bernilai nol.
Dalam praktikum ini, nilai penalti ditentukan menggunakan validasi silang 5-fold pada data latih.
# Menyiapkan matriks prediktor
x_lasso <- model.matrix(
Y ~ .,
data = data_train
)[, -1, drop = FALSE]
# Menyiapkan respons
y_lasso <- data_train$Y
# Estimasi LASSO dengan validasi silang
set.seed(2026)
cv_lasso <- glmnet::cv.glmnet(
x = x_lasso,
y = y_lasso,
family = "gaussian",
alpha = 1,
nfolds = 5,
type.measure = "mse",
standardize = TRUE
)
# Menampilkan dua nilai penalti
tibble::tibble(
Kriteria = c("lambda.min", "lambda.1se"),
Lambda = c(
cv_lasso$lambda.min,
cv_lasso$lambda.1se
)
) %>%
knitr::kable(
digits = 4,
caption = "Nilai parameter penalti LASSO berdasarkan validasi silang."
)| Kriteria | Lambda |
|---|---|
| lambda.min | 0.1454 |
| lambda.1se | 0.3360 |
Jalur Koefisien LASSO
LASSO menghasilkan estimasi koefisien untuk berbagai nilai parameter penalti. Ketika nilai lambda meningkat, penalti menjadi lebih kuat sehingga koefisien regresi mengalami penyusutan. Sebagian koefisien dapat menyusut hingga bernilai nol.
Perubahan koefisien sepanjang nilai lambda dapat diamati melalui coefficient path.
plot(
cv_lasso$glmnet.fit,
xvar = "lambda",
sign.lambda = 1,
label = FALSE,
xlab = "Log(Lambda)",
ylab = "Koefisien Regresi"
)
# Garis penanda parameter penalti
abline(
v = log(cv_lasso$lambda.min),
col = "#2563EB",
lty = 2,
lwd = 2
)
abline(
v = log(cv_lasso$lambda.1se),
col = "#DC2626",
lty = 2,
lwd = 2
)Seleksi Variabel Berdasarkan Koefisien LASSO
Nilai penalti hasil validasi silang digunakan untuk menentukan prediktor yang dipertahankan dalam model.
Pada LASSO, prediktor dengan koefisien tidak nol dinyatakan terpilih, sedangkan prediktor dengan koefisien nol dikeluarkan dari model.
Dua nilai penalti dibandingkan:
lambda.min: nilai lambda yang menghasilkan rata-rata kesalahan validasi silang terkecil.lambda.1se: nilai lambda terbesar yang masih menghasilkan kesalahan dalam satu standar error dari nilai minimum.
# Mengambil koefisien pada lambda.min
coef_min <- as.matrix(
coef(cv_lasso, s = "lambda.min")
)
# Mengambil koefisien pada lambda.1se
coef_1se <- as.matrix(
coef(cv_lasso, s = "lambda.1se")
)
# Menggabungkan hasil koefisien
hasil_koef_lasso <- tibble::tibble(
Prediktor = rownames(coef_min),
Lambda_min = as.numeric(coef_min[, 1]),
Lambda_1se = as.numeric(coef_1se[, 1])
) %>%
dplyr::filter(
Prediktor != "(Intercept)"
) %>%
dplyr::mutate(
Terpilih_min = Lambda_min != 0,
Terpilih_1se = Lambda_1se != 0
)
# Menampilkan prediktor yang terpilih
# pada setidaknya salah satu nilai lambda
hasil_koef_lasso %>%
dplyr::filter(
Terpilih_min | Terpilih_1se
) %>%
knitr::kable(
digits = 4,
caption = "Koefisien prediktor terpilih berdasarkan lambda.min dan lambda.1se."
)| Prediktor | Lambda_min | Lambda_1se | Terpilih_min | Terpilih_1se |
|---|---|---|---|---|
| X1 | 1.7737 | 1.6371 | TRUE | TRUE |
| X2 | 0.2695 | 0.1750 | TRUE | TRUE |
| X3_sq | 1.8589 | 1.7061 | TRUE | TRUE |
| X4 | 1.0182 | 0.8382 | TRUE | TRUE |
| Z3 | -0.0335 | 0.0000 | TRUE | FALSE |
| Z5 | -0.0389 | 0.0000 | TRUE | FALSE |
| Z7 | 0.1464 | 0.0206 | TRUE | TRUE |
| Z9 | -0.0914 | 0.0000 | TRUE | FALSE |
| Z11 | 0.0960 | 0.0000 | TRUE | FALSE |
# Menghitung jumlah prediktor terpilih
tibble::tibble(
Kriteria = c("lambda.min", "lambda.1se"),
Jumlah_Prediktor = c(
sum(hasil_koef_lasso$Terpilih_min),
sum(hasil_koef_lasso$Terpilih_1se)
)
) %>%
knitr::kable(
caption = "Jumlah prediktor terpilih pada dua nilai penalti LASSO."
)| Kriteria | Jumlah_Prediktor |
|---|---|
| lambda.min | 9 |
| lambda.1se | 5 |
Hasil validasi silang memberikan nilai lambda.min sebesar 0,1454 dan lambda.1se sebesar 0,3360. Pada lambda.min, LASSO mempertahankan sembilan prediktor, sedangkan pada lambda.1se jumlahnya berkurang menjadi lima. Peningkatan penalti menyebabkan beberapa koefisien yang sebelumnya tidak nol menyusut hingga tepat nol.
Pada lambda.1se, prediktor yang dipertahankan adalah X1, X2, X3_sq, X4, dan Z7. Ketiga prediktor yang membentuk komponen sistematis respons tetap terpilih. Namun, X2 yang berkorelasi kuat dengan X1 dan Z7 yang merupakan prediktor noise juga masih dipertahankan.
Dibandingkan lambda.min, penggunaan lambda.1se menghilangkan empat prediktor noise, yaitu Z3, Z5, Z9, dan Z11. Hasil ini menunjukkan bahwa penalti yang lebih kuat dapat menghasilkan model yang lebih ringkas. Meskipun demikian, LASSO tidak selalu mampu mengidentifikasi hanya prediktor yang relevan dalam mekanisme pembangkitan data, terutama ketika terdapat prediktor yang berkorelasi kuat.
Untuk perbandingan akhir, digunakan model LASSO pada lambda.1se sebagai pilihan yang lebih sederhana. Kemampuan prediksinya selanjutnya dievaluasi menggunakan data uji yang sama dengan metode seleksi lainnya.
Perbandingan Kinerja Prediksi
Evaluasi pada data uji menunjukkan bahwa Wrapper Stepwise menghasilkan RMSE terendah sebesar 2,3249 dengan mempertahankan lima prediktor. Hasil ini diikuti oleh RFE dengan RMSE sebesar 2,3342 menggunakan empat prediktor. Selisih RMSE kedua model hanya 0,0093, sehingga perbedaan kemampuan prediksinya pada data uji relatif kecil.
Filtering Pearson menghasilkan RMSE sebesar 2,3569 dengan enam prediktor, lebih rendah dibandingkan Full Model yang menggunakan 18 prediktor (RMSE = 2,4004). Hasil tersebut memperlihatkan bahwa pengurangan jumlah prediktor dapat menghasilkan model yang lebih sederhana tanpa harus meningkatkan kesalahan prediksi.
Sebaliknya, LASSO pada lambda.1se menghasilkan RMSE sebesar 2,4056 dengan lima prediktor, sedikit lebih tinggi dibandingkan Full Model. Meskipun LASSO berhasil mengurangi jumlah prediktor melalui penyusutan koefisien, penyederhanaan tersebut tidak memberikan perbaikan akurasi pada data uji ini.
Dari sisi identifikasi variabel, seluruh metode seleksi berhasil mempertahankan X1, X3_sq, dan X4 yang membentuk komponen sistematis respons. Namun, masing-masing metode masih mempertahankan prediktor tambahan yang tidak memiliki pengaruh langsung dalam rancangan simulasi. Stepwise mempertahankan Z7 dan Z9, RFE mempertahankan X5, Filtering mempertahankan X2, X5, dan Z11, sedangkan LASSO pada lambda.1se mempertahankan X2 dan Z7. Hal ini menunjukkan bahwa kemampuan prediksi yang baik tidak selalu disertai pemilihan variabel yang sepenuhnya sesuai dengan mekanisme pembangkitan data.
Secara keseluruhan, metode seleksi variabel mampu mengurangi kompleksitas model, tetapi hasil pemilihan dan kemampuan prediksi bergantung pada pendekatan yang digunakan. Perbandingan ini didasarkan pada satu pembagian data latih dan data uji, sehingga perbedaan RMSE yang kecil belum cukup untuk menyimpulkan keunggulan suatu metode secara umum.
LASSO Estimation Using Cross-Validation
Embedded methods integrate variable selection into the model-fitting algorithm.
One widely used Embedded method for regression is the Least Absolute Shrinkage and Selection Operator (LASSO).
LASSO estimates regression coefficients by adding a penalty based on their absolute values.
Mathematically, the LASSO estimator is obtained by minimizing:
\[\hat{\boldsymbol{\beta}}_{\mathrm{LASSO}} = \underset{\beta_0,\boldsymbol{\beta}}{\arg\min} \left\{ \frac{1}{2n} \sum_{i=1}^{n} \left( Y_i-\beta_0-\sum_{j=1}^{p}X_{ij}\beta_j \right)^2 + \lambda\sum_{j=1}^{p}|\beta_j| \right\}\]
where \(\lambda\geq 0\) is the regularization parameter controlling the strength of coefficient shrinkage.
A larger value of \(\lambda\) imposes a stronger penalty and may cause some regression coefficients to become exactly zero.
Predictors with coefficients equal to zero are excluded from the resulting model.
In this practical session, the penalty parameter is selected using five-fold cross-validation on the training set.
# Prepare predictor matrix
x_lasso <- model.matrix(
Y ~ .,
data = data_train
)[, -1, drop = FALSE]
# Prepare response vector
y_lasso <- data_train$Y
# Fit LASSO using cross-validation
set.seed(2026)
cv_lasso <- glmnet::cv.glmnet(
x = x_lasso,
y = y_lasso,
family = "gaussian",
alpha = 1,
nfolds = 5,
type.measure = "mse",
standardize = TRUE
)
# Display the two selected penalty values
tibble::tibble(
Criterion = c("lambda.min", "lambda.1se"),
Lambda = c(
cv_lasso$lambda.min,
cv_lasso$lambda.1se
)
) %>%
knitr::kable(
digits = 4,
caption = "LASSO penalty parameters selected through cross-validation."
)| Criterion | Lambda |
|---|---|
| lambda.min | 0.1454 |
| lambda.1se | 0.3360 |
The parameter alpha = 1 specifies the LASSO penalty, while type.measure = "mse" uses mean squared error as the cross-validation criterion.
Two penalty values are reported:
lambda.min: the value of lambda that minimizes the mean cross-validation error.lambda.1se: the largest value of lambda whose cross-validation error is within one standard error of the minimum.
LASSO Coefficient Paths
LASSO produces coefficient estimates over a sequence of penalty values.
As lambda increases, the penalty becomes stronger, causing regression coefficients to shrink toward zero.
Some coefficients may eventually become exactly zero.
The changes in regression coefficients across penalty values can be examined using a coefficient path plot.
# Plot coefficient paths
plot(
cv_lasso$glmnet.fit,
xvar = "lambda",
sign.lambda = 1,
label = FALSE,
xlab = "Log(Lambda)",
ylab = "Regression Coefficient"
)
# Mark lambda.min
abline(
v = log(cv_lasso$lambda.min),
col = "#2563EB",
lty = 2,
lwd = 2
)
# Mark lambda.1se
abline(
v = log(cv_lasso$lambda.1se),
col = "#DC2626",
lty = 2,
lwd = 2
)In this plot, moving to the right corresponds to increasing lambda values and stronger regularization.
The coefficient paths illustrate how predictors may gradually lose their contribution as the penalty increases.
Variable Selection Based on LASSO Coefficients
The penalty values obtained from cross-validation are used to identify the predictors retained in the LASSO model.
A predictor is considered selected when its estimated coefficient is nonzero.
Two penalty values are compared: lambda.min and lambda.1se.
# Extract coefficients at lambda.min
coef_min <- as.matrix(
coef(cv_lasso, s = "lambda.min")
)
# Extract coefficients at lambda.1se
coef_1se <- as.matrix(
coef(cv_lasso, s = "lambda.1se")
)
# Combine coefficient estimates
hasil_koef_lasso <- tibble::tibble(
Predictor = rownames(coef_min),
Lambda_min = as.numeric(coef_min[, 1]),
Lambda_1se = as.numeric(coef_1se[, 1])
) %>%
dplyr::filter(
Predictor != "(Intercept)"
) %>%
dplyr::mutate(
Selected_min = Lambda_min != 0,
Selected_1se = Lambda_1se != 0
)
# Display predictors selected by at least one criterion
hasil_koef_lasso %>%
dplyr::filter(
Selected_min | Selected_1se
) %>%
knitr::kable(
digits = 4,
caption = "LASSO coefficients at lambda.min and lambda.1se."
)| Predictor | Lambda_min | Lambda_1se | Selected_min | Selected_1se |
|---|---|---|---|---|
| X1 | 1.7737 | 1.6371 | TRUE | TRUE |
| X2 | 0.2695 | 0.1750 | TRUE | TRUE |
| X3_sq | 1.8589 | 1.7061 | TRUE | TRUE |
| X4 | 1.0182 | 0.8382 | TRUE | TRUE |
| Z3 | -0.0335 | 0.0000 | TRUE | FALSE |
| Z5 | -0.0389 | 0.0000 | TRUE | FALSE |
| Z7 | 0.1464 | 0.0206 | TRUE | TRUE |
| Z9 | -0.0914 | 0.0000 | TRUE | FALSE |
| Z11 | 0.0960 | 0.0000 | TRUE | FALSE |
# Compare the number of selected predictors
tibble::tibble(
Criterion = c("lambda.min", "lambda.1se"),
Number_of_Predictors = c(
sum(hasil_koef_lasso$Selected_min),
sum(hasil_koef_lasso$Selected_1se)
)
) %>%
knitr::kable(
caption = "Number of predictors selected under the two LASSO penalty criteria."
)| Criterion | Number_of_Predictors |
|---|---|
| lambda.min | 9 |
| lambda.1se | 5 |
Cross-validation produces lambda.min = 0.1454 and lambda.1se = 0.3360.
At lambda.min, LASSO retains nine predictors, whereas only five predictors remain at lambda.1se.
The stronger penalty causes several previously nonzero coefficients to shrink to exactly zero.
At lambda.1se, the retained predictors are X1, X2, X3_sq, X4, and Z7.
All three predictors included in the systematic response function remain selected.
However, X2, which is strongly correlated with X1, and Z7, which is an irrelevant predictor, are also retained.
Compared with lambda.min, the use of lambda.1se eliminates four irrelevant predictors: Z3, Z5, Z9, and Z11.
These results illustrate that stronger regularization can produce a more parsimonious model.
Nevertheless, LASSO does not necessarily recover only the predictors that truly contribute to the response-generating mechanism, especially when predictors are strongly correlated.
For the final comparison, the model using lambda.1se is selected because the practical session emphasizes model simplification.
Its predictive performance is subsequently evaluated using the same test set as the other variable selection methods.
E. Model Performance Comparison
Evaluating Predictions on the Test Set
The predictive performance of each model is evaluated using Root Mean Squared Error (RMSE):
\[\mathrm{RMSE}_{\mathrm{test}} = \sqrt{ \frac{1}{n_{\mathrm{test}}} \sum_{i=1}^{n_{\mathrm{test}}} \left( Y_i-\hat{Y}_i \right)^2 }\]
where \(n_{\mathrm{test}}\) is the number of observations in the test set, \(Y_i\) is the observed response, and \(\hat{Y}_i\) is the predicted response.
A lower RMSE indicates lower prediction error on the original response scale.
All five models are evaluated using the same test observations to provide a consistent comparison of predictive performance.
# Predictions from four linear regression models
pred_full <- predict(
model_full,
newdata = data_test
)
pred_filter <- predict(
model_filter,
newdata = data_test
)
pred_stepwise <- predict(
model_stepwise,
newdata = data_test
)
pred_rfe <- predict(
model_rfe,
newdata = data_test
)
# Prepare the test predictor matrix for LASSO
x_test_lasso <- model.matrix(
Y ~ .,
data = data_test
)[, -1, drop = FALSE]
# LASSO predictions using lambda.1se
pred_lasso <- as.numeric(
predict(
cv_lasso,
newx = x_test_lasso,
s = "lambda.1se"
)
)
# Function to calculate RMSE
hitung_rmse <- function(actual, predicted) {
sqrt(mean((actual - predicted)^2))
}
# Function to count predictors in a regression model
hitung_prediktor <- function(model) {
length(attr(terms(model), "term.labels"))
}
# Compare model performance
hasil_evaluasi <- tibble::tibble(
Model = c(
"Full Model",
"Filtering Pearson",
"Wrapper Stepwise",
"Wrapper RFE",
"Embedded LASSO"
),
Number_of_Predictors = c(
hitung_prediktor(model_full),
hitung_prediktor(model_filter),
hitung_prediktor(model_stepwise),
hitung_prediktor(model_rfe),
sum(hasil_koef_lasso$Selected_1se)
),
Test_RMSE = c(
hitung_rmse(data_test$Y, pred_full),
hitung_rmse(data_test$Y, pred_filter),
hitung_rmse(data_test$Y, pred_stepwise),
hitung_rmse(data_test$Y, pred_rfe),
hitung_rmse(data_test$Y, pred_lasso)
)
) %>%
dplyr::arrange(Test_RMSE)
# Display the comparison table
knitr::kable(
hasil_evaluasi,
digits = 4,
caption = "Comparison of the number of predictors and test RMSE across models."
)| Model | Number_of_Predictors | Test_RMSE |
|---|---|---|
| Wrapper Stepwise | 5 | 2.3249 |
| Wrapper RFE | 4 | 2.3342 |
| Filtering Pearson | 6 | 2.3569 |
| Full Model | 18 | 2.4004 |
| Embedded LASSO | 5 | 2.4056 |
Interpretation of Model Performance
The test-set evaluation shows that Wrapper Stepwise achieves the lowest RMSE of 2.3249 while retaining five predictors.
RFE follows closely with an RMSE of 2.3342 using only four predictors.
The difference in RMSE between these two models is 0.0093, indicating relatively similar predictive performance on the test set used in this analysis.
Pearson correlation-based Filtering produces an RMSE of 2.3569 with six predictors, lower than the Full Model, which includes 18 predictors and produces an RMSE of 2.4004.
This result illustrates that reducing the number of predictors can produce a simpler model without necessarily increasing prediction error.
In contrast, LASSO at lambda.1se produces an RMSE of 2.4056 with five predictors, slightly higher than the Full Model.
Although LASSO successfully reduces the number of predictors through coefficient shrinkage, this simplification does not improve test-set predictive accuracy in this particular simulation.
Regarding variable identification, all selection methods retain X1, X3_sq, and X4, which form the systematic component of the response-generating equation.
However, each method also retains additional predictors that have no direct contribution to the data-generating mechanism.
Stepwise retains Z7 and Z9, RFE retains X5, Filtering retains X2, X5, and Z11, while LASSO at lambda.1se retains X2 and Z7.
This demonstrates that good predictive performance does not necessarily imply that a selection method has fully recovered the true set of predictors in the simulation design.
Overall, variable selection can reduce model complexity, but both the selected subset and predictive performance depend on the selection approach.
Since the comparison is based on a single training–test split, small differences in RMSE are not sufficient to establish the general superiority of one method.
Conclusion
This practical session demonstrates three major approaches to variable selection: Filtering, Wrapper, and Embedded methods.
Filtering evaluates predictor relevance individually using a predefined statistical measure. Wrapper methods repeatedly fit and evaluate models with different predictor subsets. Embedded methods incorporate variable selection directly into the model estimation process.
In the simulated dataset, Wrapper methods achieve the lowest test RMSE, while all three selection approaches reduce the number of predictors compared with the Full Model.
Nevertheless, none of the methods selects exclusively the predictors included in the true response-generating equation.
These findings emphasize that variable selection should be understood as an attempt to obtain a more parsimonious model while maintaining predictive performance, rather than simply removing as many predictors as possible.
Penyusutan koefisien LASSOLASSO coefficient shrinkage
Ilustrasi soft-threshold pada desain ortonormal: koefisien awal 3, −2, 1, 0,4.Soft-threshold illustration for an orthonormal design: initial coefficients 3, −2, 1, 0.4.
Data ilustratif, bukan hasil estimasi R pada dataset praktikum.Illustrative data, not estimated R results for the practicum dataset.
I · Tugas Mandiri: Seleksi Variabel pada Data EmpirisI · Independent Assignment: Variable Selection Using Empirical Data
Terapkan pendekatan yang sama pada data College; lakukan seleksi pada data latih sebelum evaluasi akhir.Apply the same approaches to College data; perform selection on training data before final evaluation.
Pada praktikum sebelumnya, seleksi variabel dilakukan menggunakan data simulasi sehingga prediktor yang membentuk respons sudah diketahui.
Dalam tugas ini, metode yang sama diterapkan pada data empiris. Berbeda dari data simulasi, kita tidak mengetahui secara pasti prediktor mana yang benar-benar berpengaruh terhadap respons.
Dataset yang digunakan adalah College dari paket ISLR2. Data ini memuat karakteristik 777 perguruan tinggi di Amerika Serikat berdasarkan informasi tahun 1995.
Variabel respons adalah Outstate, yaitu biaya kuliah bagi mahasiswa dari luar negara bagian tempat perguruan tinggi berada.
1. Persiapan Data
# Memeriksa ketersediaan paket
if (!requireNamespace("ISLR2", quietly = TRUE)) {
stop("Instal paket ISLR2 terlebih dahulu.")
}
# Memuat data empiris
data_empiris <- ISLR2::College
# Mengubah Private menjadi dummy numerik
# 1 = perguruan tinggi swasta
# 0 = perguruan tinggi negeri
data_empiris$Private <- as.integer(
data_empiris$Private == "Yes"
)
# Memeriksa struktur dan kelengkapan data
dim(data_empiris)#> [1] 777 18
str(data_empiris)#> 'data.frame': 777 obs. of 18 variables:
#> $ Private : int 1 1 1 1 1 1 1 1 1 1 ...
#> $ Apps : num 1660 2186 1428 417 193 ...
#> $ Accept : num 1232 1924 1097 349 146 ...
#> $ Enroll : num 721 512 336 137 55 158 103 489 227 172 ...
#> $ Top10perc : num 23 16 22 60 16 38 17 37 30 21 ...
#> $ Top25perc : num 52 29 50 89 44 62 45 68 63 44 ...
#> $ F.Undergrad: num 2885 2683 1036 510 249 ...
#> $ P.Undergrad: num 537 1227 99 63 869 ...
#> $ Outstate : num 7440 12280 11250 12960 7560 ...
#> $ Room.Board : num 3300 6450 3750 5450 4120 ...
#> $ Books : num 450 750 400 450 800 500 500 450 300 660 ...
#> $ Personal : num 2200 1500 1165 875 1500 ...
#> $ PhD : num 70 29 53 92 76 67 90 89 79 40 ...
#> $ Terminal : num 78 30 66 97 72 73 93 100 84 41 ...
#> $ S.F.Ratio : num 18.1 12.2 12.9 7.7 11.9 9.4 11.5 13.7 11.3 11.5 ...
#> $ perc.alumni: num 12 16 30 37 2 11 26 37 23 15 ...
#> $ Expend : num 7041 10527 8735 19016 10922 ...
#> $ Grad.Rate : num 60 56 54 59 15 55 63 73 80 52 ...
colSums(is.na(data_empiris))#> Private Apps Accept Enroll Top10perc Top25perc
#> 0 0 0 0 0 0
#> F.Undergrad P.Undergrad Outstate Room.Board Books Personal
#> 0 0 0 0 0 0
#> PhD Terminal S.F.Ratio perc.alumni Expend Grad.Rate
#> 0 0 0 0 0 0
# Membagi data menjadi 80% latih dan 20% uji
set.seed(2026)
indeks_train <- sample.int(
n = nrow(data_empiris),
size = floor(0.8 * nrow(data_empiris))
)
data_train_empiris <- data_empiris[
indeks_train, , drop = FALSE
]
data_test_empiris <- data_empiris[
-indeks_train, , drop = FALSE
]
# Memeriksa hasil pembagian
data.frame(
Dataset = c(
"Data keseluruhan",
"Data latih",
"Data uji"
),
Observasi = c(
nrow(data_empiris),
nrow(data_train_empiris),
nrow(data_test_empiris)
),
Peubah = c(
ncol(data_empiris),
ncol(data_train_empiris),
ncol(data_test_empiris)
)
)| Dataset | Observasi | Peubah |
|---|---|---|
| Data keseluruhan | 777 | 18 |
| Data latih | 621 | 18 |
| Data uji | 156 | 18 |
2. Penerapan Seleksi Variabel
Gunakan Outstate sebagai variabel respons dan seluruh 17 prediktor lainnya sebagai kandidat.
Terapkan pendekatan berikut:
- Full Model: regresi linear menggunakan seluruh prediktor.
- Filtering: pemilihan enam prediktor dengan nilai absolut korelasi Pearson terbesar terhadap
Outstate. - Wrapper: Forward Selection, Backward Elimination, dan Bidirectional Stepwise berdasarkan AIC, serta Recursive Feature Elimination (RFE) berdasarkan RMSE validasi silang.
- Embedded: LASSO dengan pemilihan parameter penalti melalui validasi silang.
Untuk RFE, sesuaikan ukuran subset dengan jumlah prediktor yang tersedia, misalnya:
ukuran_subset <- c(2, 3, 4, 5, 6, 8, 12, 17)
ukuran_subset#> [1] 2 3 4 5 6 8 12 17
Gunakan prosedur yang sama seperti pada praktikum utama. Seluruh proses seleksi variabel dan validasi silang dilakukan menggunakan data latih.
3. Evaluasi Model
Evaluasi model menggunakan RMSE pada data uji yang sama.
Susun tabel yang memuat:
- Metode seleksi variabel.
- Jumlah prediktor terpilih.
- Nama prediktor terpilih.
- RMSE pada data uji.
4. Pertanyaan Analisis
Jawablah pertanyaan berikut berdasarkan hasil yang diperoleh.
Apakah Filtering, Wrapper, dan Embedded memilih kombinasi prediktor yang sama? Jelaskan perbedaan yang ditemukan berdasarkan mekanisme masing-masing metode.
Apakah pengurangan jumlah prediktor selalu diikuti penurunan RMSE pada data uji? Gunakan hasil perbandingan model untuk mendukung jawaban.
Berbeda dari data simulasi, pada data empiris kita tidak mengetahui persamaan pembentukan respons yang sebenarnya. Apa keterbatasan yang perlu diperhatikan ketika menyimpulkan bahwa prediktor terpilih merupakan prediktor yang penting?
Link Submission: https://forms.gle/ju6uUBd871wvzfET9
The main practical session applies variable selection methods to simulated data, where the predictors included in the response-generating mechanism are known.
In this assignment, the same methods are applied to empirical data.
Unlike simulated data, empirical data generally do not provide direct knowledge of which predictors truly contribute to the response-generating mechanism.
The dataset used is College from the ISLR2 package. It contains information on 777 colleges and universities in the United States, based on data from 1995.
The response variable is Outstate, representing out-of-state tuition.
1. Data Preparation
# Check whether the package is available
if (!requireNamespace("ISLR2", quietly = TRUE)) {
stop("Please install the ISLR2 package before running this section.")
}
# Load the empirical dataset
data_empiris <- ISLR2::College
# Convert Private into a numeric dummy variable
# 1 = Private institution
# 0 = Public institution
data_empiris$Private <- as.integer(
data_empiris$Private == "Yes"
)
# Examine data structure and missing values
dim(data_empiris)#> [1] 777 18
str(data_empiris)#> 'data.frame': 777 obs. of 18 variables:
#> $ Private : int 1 1 1 1 1 1 1 1 1 1 ...
#> $ Apps : num 1660 2186 1428 417 193 ...
#> $ Accept : num 1232 1924 1097 349 146 ...
#> $ Enroll : num 721 512 336 137 55 158 103 489 227 172 ...
#> $ Top10perc : num 23 16 22 60 16 38 17 37 30 21 ...
#> $ Top25perc : num 52 29 50 89 44 62 45 68 63 44 ...
#> $ F.Undergrad: num 2885 2683 1036 510 249 ...
#> $ P.Undergrad: num 537 1227 99 63 869 ...
#> $ Outstate : num 7440 12280 11250 12960 7560 ...
#> $ Room.Board : num 3300 6450 3750 5450 4120 ...
#> $ Books : num 450 750 400 450 800 500 500 450 300 660 ...
#> $ Personal : num 2200 1500 1165 875 1500 ...
#> $ PhD : num 70 29 53 92 76 67 90 89 79 40 ...
#> $ Terminal : num 78 30 66 97 72 73 93 100 84 41 ...
#> $ S.F.Ratio : num 18.1 12.2 12.9 7.7 11.9 9.4 11.5 13.7 11.3 11.5 ...
#> $ perc.alumni: num 12 16 30 37 2 11 26 37 23 15 ...
#> $ Expend : num 7041 10527 8735 19016 10922 ...
#> $ Grad.Rate : num 60 56 54 59 15 55 63 73 80 52 ...
colSums(is.na(data_empiris))#> Private Apps Accept Enroll Top10perc Top25perc
#> 0 0 0 0 0 0
#> F.Undergrad P.Undergrad Outstate Room.Board Books Personal
#> 0 0 0 0 0 0
#> PhD Terminal S.F.Ratio perc.alumni Expend Grad.Rate
#> 0 0 0 0 0 0
# Split the data into 80% training and 20% test observations
set.seed(2026)
indeks_train <- sample.int(
n = nrow(data_empiris),
size = floor(0.8 * nrow(data_empiris))
)
data_train_empiris <- data_empiris[
indeks_train, , drop = FALSE
]
data_test_empiris <- data_empiris[
-indeks_train, , drop = FALSE
]
# Examine the resulting data split
data.frame(
Dataset = c(
"Complete dataset",
"Training set",
"Test set"
),
Observations = c(
nrow(data_empiris),
nrow(data_train_empiris),
nrow(data_test_empiris)
),
Variables = c(
ncol(data_empiris),
ncol(data_train_empiris),
ncol(data_test_empiris)
)
)| Dataset | Observations | Variables |
|---|---|---|
| Complete dataset | 777 | 18 |
| Training set | 621 | 18 |
| Test set | 156 | 18 |
2. Applying Variable Selection Methods
Use Outstate as the response variable and all 17 remaining variables as candidate predictors.
Apply the following approaches:
- Full Model: Fit multiple linear regression using all candidate predictors.
- Filtering: Select the six predictors with the highest absolute Pearson correlations with
Outstate. - Wrapper: Apply Forward Selection, Backward Elimination, and Bidirectional Stepwise Selection using AIC. Also apply RFE using cross-validation RMSE.
- Embedded: Fit LASSO regression and select the regularization parameter through cross-validation.
For RFE, adjust the candidate subset sizes to reflect the number of predictors in this dataset.
For example:
# Candidate subset sizes for RFE
ukuran_subset <- c(2, 3, 4, 5, 6, 8, 12, 17)
ukuran_subset#> [1] 2 3 4 5 6 8 12 17
Use the same general modeling procedures demonstrated in the main practical session.
All variable selection procedures and cross-validation must be performed using the training set only.
3. Model Evaluation
Evaluate the selected models using RMSE on the same test set.
Prepare a comparison table containing:
- Variable selection method.
- Number of selected predictors.
- Names of selected predictors.
- Test RMSE.
4. Analysis Questions
Answer the following questions based on your results.
Do Filtering, Wrapper, and Embedded methods select the same combinations of predictors? Explain the observed differences based on the selection mechanisms of each method.
Does reducing the number of predictors always lead to a lower test RMSE? Support your answer using the model comparison results.
Unlike simulated data, the true response-generating equation is unknown in empirical data. What limitations should be considered when concluding that selected predictors are important?
5. Submission Requirements
Submit a reproducible R analysis containing the implemented code, model comparison table, and concise interpretations of the results.
Use the specified training–test split and the same candidate predictors across all methods.
Perform variable selection and model tuning using the training set only. The test set must be reserved for final evaluation and should not be repeatedly used to select model settings.
The discussion should focus on differences in selected predictors, model complexity, predictive performance, and the limitations of interpreting variable selection results from empirical data.
Link Submission: https://forms.gle/okMgnwbvPJvWvk147
II · Persiapan PackageII · Package Setup
Siapkan paket untuk ukuran relevansi, subset model, Boruta dan Group LASSO.Prepare packages for relevance scores, subset models, Boruta and Group LASSO.
Praktikum ini menggunakan beberapa package R untuk penyiapan data, seleksi variabel menggunakan Filtering, Wrapper, dan Embedded, serta evaluasi dan visualisasi hasil pemodelan.
# Daftar package yang diperlukan
paket <- c(
"MASS",
"tidyverse",
"rsample",
"knitr",
"scales",
"rpart",
"pROC",
"FSelector",
"leaps",
"Boruta",
"grpreg"
)
# Menginstal package yang belum tersedia
paket_belum_ada <- paket[
!vapply(
paket,
requireNamespace,
logical(1),
quietly = TRUE
)
]
if (length(paket_belum_ada) > 0) {
install.packages(
paket_belum_ada,
repos = "https://cloud.r-project.org"
)
}
# Memuat seluruh library
library(MASS)
library(tidyverse)
library(rsample)
library(knitr)
library(scales)
library(rpart)
library(pROC)
library(FSelector)
library(leaps)
library(Boruta)
library(grpreg)This practical session uses several R packages for data preparation, variable selection using Filtering, Wrapper, and Embedded approaches, and model evaluation and visualization.
# List of required packages
paket <- c(
"MASS",
"tidyverse",
"rsample",
"knitr",
"scales",
"rpart",
"pROC",
"FSelector",
"leaps",
"Boruta",
"grpreg"
)
# Install missing packages
paket_belum_ada <- paket[
!vapply(
paket,
requireNamespace,
logical(1),
quietly = TRUE
)
]
if (length(paket_belum_ada) > 0) {
install.packages(
paket_belum_ada,
repos = "https://cloud.r-project.org"
)
}
# Load all libraries
library(MASS)
library(tidyverse)
library(rsample)
library(knitr)
library(scales)
library(rpart)
library(pROC)
library(FSelector)
library(leaps)
library(Boruta)
library(grpreg)II · PendahuluanII · Introduction
Data empiris memperluas masalah dari regresi simulasi ke tipe respons yang berbeda. Pilih ukuran relevansi sesuai jenis prediktor dan respons.Empirical data extend the simulation to different response types. Choose relevance measures according to predictor and response types.
Pada praktikum sebelumnya, seleksi variabel telah diterapkan pada pemodelan regresi menggunakan data simulasi melalui pendekatan Filtering, Wrapper, dan Embedded. Ketiga pendekatan tersebut mempunyai mekanisme berbeda dalam menentukan prediktor yang dipertahankan. Filtering menilai relevansi prediktor berdasarkan ukuran statistik tertentu, Wrapper mengevaluasi kombinasi prediktor melalui model, sedangkan Embedded melakukan seleksi sebagai bagian dari proses estimasi model.
Praktikum ini memperluas pembahasan menggunakan data empiris dengan respons kategorik dan numerik. Materi mengacu pada Bab 5–7 buku Seleksi Variabel pada Pemodelan Prediktif Statistika dan Machine Learning (Sartono et al., 2024), dengan fokus pada perbedaan ukuran relevansi, pemilihan subset prediktor, dan seleksi koefisien yang memiliki struktur kelompok.
Secara umum, materi praktikum mencakup tiga pendekatan berikut.
| Pendekatan | Metode | Fokus |
|---|---|---|
| Filtering | ANOVA, Kruskal–Wallis, Chi-Square, AUC, oneR, Information Gain, Gain Ratio, dan Information Value | Pemeringkatan relevansi prediktor |
| Wrapper | Best Subset Selection dan Boruta | Seleksi berdasarkan evaluasi model atau kepentingan prediktor |
| Embedded | Group LASSO | Seleksi kelompok koefisien melalui regularisasi |
Metode Filtering umumnya mengevaluasi prediktor secara marginal, yaitu tanpa mempertimbangkan kontribusinya setelah prediktor lain dimasukkan ke dalam model. Sebaliknya, metode Wrapper dan Embedded dapat mempertimbangkan penggunaan prediktor secara bersama-sama, meskipun mekanisme seleksinya berbeda.
Hal lain yang perlu diperhatikan adalah representasi prediktor. Metode berbasis distribusi kategori memerlukan prediktor kategorik sehingga prediktor numerik perlu didiskretisasi. Sementara itu, pada pemodelan regresi, variabel kategorik dapat menghasilkan beberapa koefisien dummy. Perbedaan representasi ini dapat memengaruhi hasil seleksi.
Seluruh proses pemilihan prediktor menggunakan data latih. Data uji dipertahankan untuk evaluasi kemampuan prediksi setelah model ditentukan. Pada data empiris, prediktor terpilih diinterpretasikan sebagai prediktor yang relevan menurut metode tertentu, bukan sebagai bukti hubungan sebab-akibat.
In the previous practical session, variable selection was applied to regression modeling with simulated data using Filtering, Wrapper, and Embedded approaches. These approaches differ in how they determine which predictors to retain. Filtering assesses predictor relevance using statistical measures; Wrapper evaluates combinations of predictors through a predictive model; and Embedded performs selection as part of model estimation.
This session extends the discussion to empirical data with categorical and numerical responses. The material draws on Chapters 5–7 of Seleksi Variabel pada Pemodelan Prediktif Statistika dan Machine Learning (Sartono et al., 2024), focusing on different relevance measures, predictor subset selection, and the selection of coefficients with a group structure.
The practical covers three main approaches.
| Approach | Methods | Focus |
|---|---|---|
| Filtering | ANOVA, Kruskal–Wallis, Chi-Square, AUC, oneR, Information Gain, Gain Ratio, and Information Value | Ranking predictors by relevance |
| Wrapper | Best Subset Selection and Boruta | Selection based on model evaluation or predictor importance |
| Embedded | Group LASSO | Selecting groups of coefficients through regularization |
Filtering methods generally assess predictors marginally, without considering their contribution once other predictors are included in a model. Wrapper and Embedded methods, by contrast, can account for predictors used together, although their selection mechanisms differ.
Predictor representation is another important consideration. Methods based on categorical distributions require categorical predictors, so numerical predictors must first be discretized. Conversely, in regression modeling, a categorical variable may generate several dummy coefficients. These differences in representation can affect the selection results.
All predictor selection is performed using the training data. The test data are reserved for evaluating predictive performance after a model has been determined. With empirical data, selected predictors are interpreted as relevant according to a particular method, not as evidence of causation.
II · 1. Data dan PersiapanII · 1. Data and Preparation
Dataset birthwt menyediakan respons biner dan berat lahir numerik. Pisahkan definisi respons untuk masing-masing tugas agar informasi target tidak bocor.The birthwt dataset supplies binary and numerical birth-weight responses. Separate response definitions to avoid leaking target information.
1.1 Dataset birthwt
Praktikum menggunakan dataset birthwt dari package MASS. Data ini memuat informasi karakteristik ibu selama kehamilan dan berat lahir bayi di Baystate Medical Center, Springfield, Massachusetts, pada tahun 1986.
Dataset terdiri atas 189 observasi dan 10 peubah.
| Peubah | Keterangan | Tipe |
|---|---|---|
low |
Status berat lahir rendah, yaitu kurang dari 2.500 gram | Kategorik biner |
age |
Umur ibu (tahun) | Numerik |
lwt |
Berat badan ibu pada menstruasi terakhir (pon) | Numerik |
race |
Kategori ras yang dicatat dalam data | Kategorik nominal |
smoke |
Status merokok selama kehamilan | Kategorik biner |
ptl |
Jumlah persalinan prematur sebelumnya | Numerik diskrit |
ht |
Riwayat hipertensi | Kategorik biner |
ui |
Iritabilitas uterus | Kategorik biner |
ftv |
Jumlah kunjungan dokter pada trimester pertama | Numerik diskrit |
bwt |
Berat lahir bayi (gram) | Numerik |
Dataset digunakan untuk dua tujuan pemodelan, yaitu klasifikasi dengan respons low dan regresi dengan respons bwt. Keduanya memiliki hubungan definisional karena low dibentuk dari batas nilai bwt.
Oleh karena itu, bwt tidak digunakan sebagai prediktor ketika low menjadi respons, dan sebaliknya. Penggunaan keduanya secara bersamaan sebagai respons dan prediktor akan menyebabkan data leakage.
1.2 Membaca dan Menyiapkan Data
Pada data asli, beberapa prediktor kategorik disimpan sebagai bilangan bulat. Peubah tersebut diubah menjadi faktor agar diperlakukan sesuai karakteristik pengukurannya.
# Package utama
library(MASS)
library(tidyverse)
library(rsample)
# Membaca data
data("birthwt", package = "MASS")
data_birthwt <- MASS::birthwt %>%
tibble::as_tibble() %>%
dplyr::mutate(
low = factor(
low,
levels = c(0, 1),
labels = c("Tidak rendah", "Rendah")
),
race = factor(
race,
levels = c(1, 2, 3),
labels = c("White", "Black", "Other")
),
smoke = factor(
smoke,
levels = c(0, 1),
labels = c("Tidak", "Ya")
),
ht = factor(
ht,
levels = c(0, 1),
labels = c("Tidak", "Ya")
),
ui = factor(
ui,
levels = c(0, 1),
labels = c("Tidak", "Ya")
)
)
# Memeriksa struktur dan nilai hilang
dplyr::glimpse(data_birthwt)Rows: 189
Columns: 10
$ low <fct> Tidak rendah, Tidak rendah, Tidak rendah, Tidak rendah, Tidak re…
$ age <int> 19, 33, 20, 21, 18, 21, 22, 17, 29, 26, 19, 19, 22, 30, 18, 18, …
$ lwt <int> 182, 155, 105, 108, 107, 124, 118, 103, 123, 113, 95, 150, 95, 1…
$ race <fct> Black, Other, White, White, White, Other, White, Other, White, W…
$ smoke <fct> Tidak, Tidak, Ya, Ya, Ya, Tidak, Tidak, Tidak, Ya, Ya, Tidak, Ti…
$ ptl <int> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0…
$ ht <fct> Tidak, Tidak, Tidak, Tidak, Tidak, Tidak, Tidak, Tidak, Tidak, T…
$ ui <fct> Ya, Tidak, Tidak, Ya, Ya, Tidak, Tidak, Tidak, Tidak, Tidak, Tid…
$ ftv <int> 0, 3, 1, 2, 0, 0, 1, 1, 1, 0, 0, 1, 0, 2, 0, 0, 0, 3, 0, 1, 2, 3…
$ bwt <int> 2523, 2551, 2557, 2594, 2600, 2622, 2637, 2637, 2663, 2665, 2722…
tibble::tibble(
Peubah = names(data_birthwt),
Jumlah_NA = colSums(is.na(data_birthwt))
) %>%
knitr::kable(
caption = "Pemeriksaan kelengkapan data."
)| Peubah | Jumlah_NA |
|---|---|
| low | 0 |
| age | 0 |
| lwt | 0 |
| race | 0 |
| smoke | 0 |
| ptl | 0 |
| ht | 0 |
| ui | 0 |
| ftv | 0 |
| bwt | 0 |
Dataset memiliki 189 observasi dan tidak mengandung nilai hilang. Selanjutnya, distribusi respons diperiksa untuk mengetahui proporsi kelas berat lahir rendah.
# Distribusi kelas respons
data_birthwt %>%
dplyr::count(low, name = "Frekuensi") %>%
dplyr::mutate(
Persentase = 100 * Frekuensi / sum(Frekuensi)
) %>%
knitr::kable(
digits = 2,
caption = "Distribusi status berat lahir."
)| low | Frekuensi | Persentase |
|---|---|---|
| Tidak rendah | 130 | 68.78 |
| Rendah | 59 | 31.22 |
Sebanyak 130 bayi (68,78%) termasuk kategori tidak rendah dan 59 bayi (31,22%) termasuk kategori berat lahir rendah. Distribusi ini menunjukkan ketidakseimbangan proporsi kelas yang perlu diperhatikan pada pemodelan klasifikasi.
1.3 Pembagian Data Latih dan Data Uji
Data dibagi menjadi 80% data latih dan 20% data uji. Stratifikasi berdasarkan low digunakan untuk mempertahankan proporsi kedua kelas secara mendekati proporsional.
set.seed(2026)
split_birthwt <- rsample::initial_split(
data_birthwt,
prop = 0.80,
strata = low
)
data_train <- rsample::training(split_birthwt)
data_test <- rsample::testing(split_birthwt)
# Dataset klasifikasi
data_train_klasifikasi <- data_train %>%
dplyr::select(-bwt)
data_test_klasifikasi <- data_test %>%
dplyr::select(-bwt)
# Dataset regresi
data_train_regresi <- data_train %>%
dplyr::select(-low)
data_test_regresi <- data_test %>%
dplyr::select(-low)
# Memeriksa pembagian data
tibble::tibble(
Dataset = c("Latih", "Uji"),
Observasi = c(nrow(data_train), nrow(data_test))
) %>%
knitr::kable(
caption = "Ukuran data latih dan data uji."
)| Dataset | Observasi |
|---|---|
| Latih | 151 |
| Uji | 38 |
# Distribusi kelas pada data latih dan uji
dplyr::bind_rows(
data_train %>%
dplyr::count(low) %>%
dplyr::mutate(Dataset = "Latih"),
data_test %>%
dplyr::count(low) %>%
dplyr::mutate(Dataset = "Uji")
) %>%
dplyr::group_by(Dataset) %>%
dplyr::mutate(
Persentase = 100 * n / sum(n)
) %>%
dplyr::ungroup() %>%
knitr::kable(
digits = 2,
caption = "Distribusi kelas menurut pembagian data."
)| low | n | Dataset | Persentase |
|---|---|---|---|
| Tidak rendah | 104 | Latih | 68.87 |
| Rendah | 47 | Latih | 31.13 |
| Tidak rendah | 26 | Uji | 68.42 |
| Rendah | 12 | Uji | 31.58 |
Pembagian menghasilkan 151 observasi data latih dan 38 observasi data uji. Kedua jenis pemodelan menggunakan delapan kandidat prediktor yang sama, tetapi memiliki bentuk respons dan tujuan prediksi yang berbeda.
Pada pendekatan Filtering, analisis utama difokuskan pada klasifikasi menggunakan respons low. Best Subset Selection diimplementasikan untuk regresi menggunakan respons bwt. Sementara itu, Boruta dan Group LASSO diterapkan pada kedua jenis pemodelan, yaitu klasifikasi dengan respons low dan regresi dengan respons bwt.
Seluruh proses seleksi variabel dilakukan pada data latih, sedangkan data uji dipertahankan untuk mengevaluasi kemampuan prediksi model yang telah ditentukan. Variabel bwt tidak digunakan sebagai prediktor klasifikasi low, dan sebaliknya, untuk menghindari data leakage..
1.1 The birthwt Dataset
This practical uses the birthwt dataset from the MASS package. It contains maternal characteristics during pregnancy and infant birth weights collected at Baystate Medical Center, Springfield, Massachusetts, in 1986.
The dataset contains 189 observations and 10 variables.
| Variable | Description | Type |
|---|---|---|
low |
Low-birth-weight status, defined as less than 2,500 grams | Binary categorical |
age |
Mother’s age (years) | Numerical |
lwt |
Mother’s weight at her last menstrual period (pounds) | Numerical |
race |
Race category recorded in the dataset | Nominal categorical |
smoke |
Smoking status during pregnancy | Binary categorical |
ptl |
Number of previous premature labors | Discrete numerical |
ht |
History of hypertension | Binary categorical |
ui |
Uterine irritability | Binary categorical |
ftv |
Number of physician visits during the first trimester | Discrete numerical |
bwt |
Infant birth weight (grams) | Numerical |
The dataset is used for two modeling tasks: classification with low as the response and regression with bwt as the response. The two responses are linked by definition because low is derived by thresholding bwt.
Accordingly, bwt is excluded as a predictor when low is the response, and vice versa. Using one to predict the other would create data leakage.
1.2 Loading and Preparing the Data
In the original dataset, some categorical predictors are stored as integers. These variables are converted to factors so that their measurement characteristics are correctly represented.
# Main packages
library(MASS)
library(tidyverse)
library(rsample)
# Load the dataset
data("birthwt", package = "MASS")
data_birthwt <- MASS::birthwt %>%
tibble::as_tibble() %>%
dplyr::mutate(
low = factor(
low,
levels = c(0, 1),
labels = c("Not low", "Low")
),
race = factor(
race,
levels = c(1, 2, 3),
labels = c("White", "Black", "Other")
),
smoke = factor(
smoke,
levels = c(0, 1),
labels = c("No", "Yes")
),
ht = factor(
ht,
levels = c(0, 1),
labels = c("No", "Yes")
),
ui = factor(
ui,
levels = c(0, 1),
labels = c("No", "Yes")
)
)
# Inspect the data structure and missing values
dplyr::glimpse(data_birthwt)Rows: 189
Columns: 10
$ low <fct> Not low, Not low, Not low, Not low, Not low, Not low, Not low, N…
$ age <int> 19, 33, 20, 21, 18, 21, 22, 17, 29, 26, 19, 19, 22, 30, 18, 18, …
$ lwt <int> 182, 155, 105, 108, 107, 124, 118, 103, 123, 113, 95, 150, 95, 1…
$ race <fct> Black, Other, White, White, White, Other, White, Other, White, W…
$ smoke <fct> No, No, Yes, Yes, Yes, No, No, No, Yes, Yes, No, No, No, No, Yes…
$ ptl <int> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0…
$ ht <fct> No, No, No, No, No, No, No, No, No, No, No, No, Yes, No, No, No,…
$ ui <fct> Yes, No, No, Yes, Yes, No, No, No, No, No, No, No, No, Yes, No, …
$ ftv <int> 0, 3, 1, 2, 0, 0, 1, 1, 1, 0, 0, 1, 0, 2, 0, 0, 0, 3, 0, 1, 2, 3…
$ bwt <int> 2523, 2551, 2557, 2594, 2600, 2622, 2637, 2637, 2663, 2665, 2722…
tibble::tibble(
Variable = names(data_birthwt),
Missing_Count = colSums(is.na(data_birthwt))
) %>%
knitr::kable(
caption = "Data completeness check."
)| Variable | Missing_Count |
|---|---|
| low | 0 |
| age | 0 |
| lwt | 0 |
| race | 0 |
| smoke | 0 |
| ptl | 0 |
| ht | 0 |
| ui | 0 |
| ftv | 0 |
| bwt | 0 |
The dataset contains 189 observations with no missing values. Next, the response distribution is examined to determine the proportion of infants with low birth weight.
# Response-class distribution
data_birthwt %>%
dplyr::count(low, name = "Frequency") %>%
dplyr::mutate(
Percentage = 100 * Frequency / sum(Frequency)
) %>%
knitr::kable(
digits = 2,
caption = "Birth-weight status distribution."
)| low | Frequency | Percentage |
|---|---|---|
| Not low | 130 | 68.78 |
| Low | 59 | 31.22 |
Of the 189 infants, 130 (68.78%) belong to the non-low-birth-weight category and 59 (31.22%) to the low-birth-weight category. This class imbalance should be considered when fitting and evaluating classification models.
1.3 Training and Test Data Split
The data are divided into 80% training and 20% test observations. Stratification by low is used to approximately preserve the proportions of the two classes.
set.seed(2026)
split_birthwt <- rsample::initial_split(
data_birthwt,
prop = 0.80,
strata = low
)
data_train <- rsample::training(split_birthwt)
data_test <- rsample::testing(split_birthwt)
# Classification dataset
data_train_klasifikasi <- data_train %>%
dplyr::select(-bwt)
data_test_klasifikasi <- data_test %>%
dplyr::select(-bwt)
# Regression dataset
data_train_regresi <- data_train %>%
dplyr::select(-low)
data_test_regresi <- data_test %>%
dplyr::select(-low)
# Inspect the data split
tibble::tibble(
Dataset = c("Training", "Test"),
Observations = c(nrow(data_train), nrow(data_test))
) %>%
knitr::kable(
caption = "Training and test sample sizes."
)| Dataset | Observations |
|---|---|
| Training | 151 |
| Test | 38 |
# Class distribution in training and test data
dplyr::bind_rows(
data_train %>%
dplyr::count(low) %>%
dplyr::mutate(Dataset = "Training"),
data_test %>%
dplyr::count(low) %>%
dplyr::mutate(Dataset = "Test")
) %>%
dplyr::group_by(Dataset) %>%
dplyr::mutate(
Percentage = 100 * n / sum(n)
) %>%
dplyr::ungroup() %>%
knitr::kable(
digits = 2,
caption = "Class distribution by data split."
)| low | n | Dataset | Percentage |
|---|---|---|---|
| Not low | 104 | Training | 68.87 |
| Low | 47 | Training | 31.13 |
| Not low | 26 | Test | 68.42 |
| Low | 12 | Test | 31.58 |
The split yields 151 training observations and 38 test observations. Both modeling tasks use the same eight candidate predictors but differ in their response type and prediction objective.
Filtering is primarily demonstrated for classification with low as the response. Best Subset Selection is implemented for regression with bwt as the response. Boruta and Group LASSO are applied to both tasks: classification with low and regression with bwt.
All variable selection is performed on the training data, while the test data are reserved for evaluating the predictive performance of the selected model. The variable bwt is excluded from predictors of low, and vice versa, to avoid data leakage.
II · 2. Seleksi Variabel Menggunakan FilteringII · 2. Variable Selection Using Filtering
Filtering untuk respons kategorik mencakup perbandingan distribusi, tabel kontingensi, kemampuan diskriminasi dan ukuran informasi. Periksa asumsi serta tipe data sebelum memilih ukuran.Filtering for categorical outcomes includes distribution comparisons, contingency tables, discrimination and information measures. Check assumptions and data types before choosing a score.
Metode Filtering memeringkat prediktor berdasarkan ukuran relevansi tertentu tanpa mengevaluasi seluruh kombinasi prediktor dalam model multivariat. Pada bagian ini, delapan kandidat prediktor dievaluasi menggunakan beberapa kriteria yang berbeda.
Prediktor numerik terdiri atas age, lwt, ptl, dan ftv, sedangkan prediktor kategorik terdiri atas race, smoke, ht, dan ui.
prediktor_numerik <- c("age", "lwt", "ptl", "ftv")
prediktor_kategorik <- c(
"race", "smoke", "ht", "ui"
)
semua_prediktor <- c(
prediktor_numerik,
prediktor_kategorik
)Penggunaan Metode Filtering Berdasarkan Tipe Peubah
Pemilihan metode Filtering perlu mempertimbangkan tipe respons dan tipe prediktor. Meskipun seluruh metode bertujuan mengevaluasi relevansi prediktor, ukuran yang digunakan tidak selalu dapat diterapkan secara langsung pada semua kombinasi tipe peubah.
Pada persoalan klasifikasi, respons berbentuk kategorik. Relevansi prediktor dapat dinilai berdasarkan perbedaan karakteristik prediktor antarkelas, ketergantungan kategori, pengurangan ketidakpastian kelas, maupun kemampuan model membedakan kelas.
Pada persoalan regresi, respons berbentuk numerik. Relevansi prediktor dapat dinilai melalui hubungan dengan respons numerik, perbedaan respons antarkategori prediktor, atau kontribusi prediktor terhadap kesalahan model regresi.
Dengan demikian, suatu metode dapat digunakan pada kedua persoalan apabila struktur data dan formulasi ukuran relevansinya sesuai. Namun, tidak semua metode dapat langsung dipindahkan dari klasifikasi ke regresi tanpa perubahan pendekatan.
Kesesuaian Metode Filtering
| Metode | Prediktor yang Dievaluasi | Klasifikasi | Regresi |
|---|---|---|---|
| One-Way ANOVA | Numerik pada klasifikasi; kategorik pada regresi | Membandingkan rata-rata prediktor numerik antarkelas respons | Membandingkan rata-rata respons numerik antarkategori prediktor |
| Kruskal–Wallis | Numerik pada klasifikasi; kategorik pada regresi | Membandingkan distribusi peringkat prediktor antarkelas | Membandingkan distribusi peringkat respons antarkategori prediktor |
| Chi-Square | Kategorik; numerik setelah diskretisasi | Dapat digunakan secara langsung pada respons kategorik | Memerlukan pengubahan respons numerik menjadi kategori jika tetap menggunakan Chi-Square |
| AUC | Numerik atau kategorik melalui model klasifikasi | Digunakan untuk menilai kemampuan diskriminasi kelas | Tidak digunakan secara langsung untuk respons numerik |
| oneR | Kategorik; numerik setelah diskretisasi | Digunakan untuk menilai aturan klasifikasi satu prediktor | Tidak digunakan secara langsung dalam formulasi oneR klasifikasi |
| Information Gain | Kategorik; numerik setelah diskretisasi | Mengukur pengurangan entropy respons kategorik | Memerlukan pendekatan yang sesuai untuk respons kontinu, misalnya diskretisasi atau estimasi informasi mutual kontinu |
| Gain Ratio | Kategorik; numerik setelah diskretisasi | Menormalisasi Information Gain terhadap entropy prediktor | Tidak langsung digunakan dengan formulasi entropy diskrit yang sama untuk respons kontinu |
| Information Value | Kategorik; numerik setelah diskretisasi | Digunakan untuk respons biner | Tidak langsung digunakan untuk respons numerik |
Tabel tersebut menunjukkan kesesuaian metode berdasarkan formulasi yang digunakan dalam praktikum ini, bukan seluruh kemungkinan pengembangan masing-masing metode.
Perbedaan Penerapan ANOVA dan Kruskal–Wallis
ANOVA dan Kruskal–Wallis dapat digunakan pada klasifikasi maupun regresi, tetapi peran respons dan prediktor dalam pengujian berbeda.
Pada klasifikasi, respons kategorik digunakan sebagai faktor pengelompokan, sedangkan prediktor numerik merupakan nilai yang dibandingkan antarkelas.
Sebagai contoh, untuk memeriksa relevansi lwt terhadap status berat lahir rendah:
aov(lwt ~ low, data = data_train_klasifikasi)Call:
aov(formula = lwt ~ low, data = data_train_klasifikasi)
Terms:
low Residuals
Sum of Squares 4783.79 133562.15
Deg. of Freedom 1 149
Residual standard error: 29.93978
Estimated effects may be unbalanced
kruskal.test(
lwt ~ low,
data = data_train_klasifikasi
)
Kruskal-Wallis rank sum test
data: lwt by low
Kruskal-Wallis chi-squared = 5.8622, df = 1, p-value = 0.01547
Pengujian tersebut mengevaluasi apakah karakteristik berat badan ibu berbeda antara dua kelas status berat lahir.
Pada regresi, respons numerik dapat dibandingkan berdasarkan kategori suatu prediktor.
Sebagai contoh, untuk memeriksa hubungan marginal prediktor kategorik smoke dengan berat lahir numerik:
aov(bwt ~ smoke, data = data_train_regresi)Call:
aov(formula = bwt ~ smoke, data = data_train_regresi)
Terms:
smoke Residuals
Sum of Squares 2213165 70098703
Deg. of Freedom 1 149
Residual standard error: 685.9017
Estimated effects may be unbalanced
kruskal.test(
bwt ~ smoke,
data = data_train_regresi
)
Kruskal-Wallis rank sum test
data: bwt by smoke
Kruskal-Wallis chi-squared = 5.3401, df = 1, p-value = 0.02084
Pada penerapan ini, ANOVA membandingkan rata-rata berat lahir antarkategori smoke, sedangkan Kruskal–Wallis membandingkan distribusi peringkat berat lahir antarkategori tersebut.
Kedua contoh menunjukkan bahwa metode yang sama dapat digunakan pada persoalan pemodelan berbeda apabila struktur variabel memenuhi persyaratan pengujiannya.
Namun, ANOVA dan Kruskal–Wallis bukan pilihan langsung untuk mengevaluasi hubungan antara dua variabel numerik kontinu dalam regresi. Untuk kondisi tersebut, dapat digunakan pendekatan lain seperti korelasi, regresi univariat, atau ukuran relevansi yang sesuai.
Diskretisasi Prediktor dan Respons
Metode seperti Chi-Square, oneR, Information Gain, Gain Ratio, dan Information Value dalam formulasi diskritnya memerlukan data kategorik.
Pada klasifikasi, respons sudah berbentuk kategori. Oleh karena itu, prediktor numerik dapat didiskretisasi jika diperlukan.
Pada regresi, respons numerik tidak langsung memenuhi persyaratan tersebut. Mengubah respons menjadi kategori memang memungkinkan penerapan beberapa ukuran berbasis kategori, tetapi juga mengubah persoalan analisis dan menghilangkan sebagian informasi nilai numerik.
Oleh karena itu, diskretisasi respons tidak dilakukan dalam praktikum ini hanya untuk memaksakan penggunaan metode Filtering klasifikasi pada persoalan regresi.
Dengan pertimbangan tersebut, penerapan Filtering pada praktikum difokuskan pada respons low, sedangkan penggunaan metode Filtering untuk respons numerik dijelaskan melalui kesesuaian prinsip dan formulasi masing-masing metode.
Hasil Filtering tetap perlu dipahami sebagai ukuran relevansi berdasarkan kriteria tertentu. Prediktor dengan skor relevansi tinggi belum tentu memberikan tambahan kemampuan prediksi yang besar ketika digunakan bersama prediktor lainnya.
2.1 One-Way ANOVA
One-Way ANOVA digunakan untuk mengukur perbedaan rata-rata prediktor numerik antarkelas respons. Dalam konteks Filtering, setiap prediktor dianalisis secara terpisah dengan kelas respons sebagai faktor pengelompokan.
Statistik F merupakan perbandingan variasi antarkelas terhadap variasi dalam kelas:
\[F_j = \frac{ \displaystyle \frac{\sum_{k=1}^{K}n_k(\bar{x}_{jk}-\bar{x}_j)^2}{K-1} }{ \displaystyle \frac{\sum_{k=1}^{K}\sum_{i=1}^{n_k} (x_{ijk}-\bar{x}_{jk})^2}{n-K} }\]
dengan \(K\) menyatakan jumlah kelas respons, \(n_k\) jumlah observasi kelas ke-\(k\), \(\bar{x}_{jk}\) rata-rata prediktor ke-\(j\) pada kelas ke-\(k\), dan \(\bar{x}_j\) rata-rata keseluruhan prediktor tersebut.
Semakin besar nilai F, semakin besar perbedaan rata-rata antarkelas relatif terhadap keragaman dalam kelas.
Pengujian F klasik mempunyai asumsi yang perlu diperhatikan, khususnya normalitas dalam kelompok dan kesamaan varians. Welch ANOVA digunakan sebagai pemeriksaan sensitivitas ketika varians antarkelas mungkin berbeda.
Implementasi ANOVA dan Welch ANOVA
hasil_anova <- purrr::map_dfr(
prediktor_numerik,
function(pred) {
formula_uji <- stats::reformulate(
"low",
response = pred
)
# ANOVA klasik
model_anova <- stats::aov(
formula_uji,
data = data_train_klasifikasi
)
tab_anova <- summary(model_anova)[[1]]
# Welch ANOVA
model_welch <- stats::oneway.test(
formula_uji,
data = data_train_klasifikasi,
var.equal = FALSE
)
tibble::tibble(
Prediktor = pred,
F_ANOVA = as.numeric(tab_anova[1, "F value"]),
p_ANOVA = as.numeric(tab_anova[1, "Pr(>F)"]),
F_Welch = as.numeric(model_welch$statistic),
p_Welch = model_welch$p.value
)
}
) %>%
dplyr::mutate(
Peringkat_ANOVA = dplyr::min_rank(
dplyr::desc(F_ANOVA)
),
Peringkat_Welch = dplyr::min_rank(
dplyr::desc(F_Welch)
)
) %>%
dplyr::arrange(Peringkat_ANOVA)
knitr::kable(
hasil_anova,
digits = 4,
caption = "Pemeringkatan prediktor berdasarkan ANOVA dan Welch ANOVA."
)| Prediktor | F_ANOVA | p_ANOVA | F_Welch | p_Welch | Peringkat_ANOVA | Peringkat_Welch |
|---|---|---|---|---|---|---|
| ptl | 7.8369 | 0.0058 | 6.1145 | 0.0159 | 1 | 2 |
| lwt | 5.3367 | 0.0223 | 6.1783 | 0.0145 | 2 | 1 |
| age | 1.3370 | 0.2494 | 1.5211 | 0.2202 | 3 | 3 |
| ftv | 0.4795 | 0.4897 | 0.4747 | 0.4926 | 4 | 4 |
Hasil ANOVA klasik menunjukkan bahwa ptl memiliki statistik F tertinggi (7,8369; p = 0,0058), diikuti lwt (5,3367; p = 0,0223). Pada Welch ANOVA, urutan keduanya berubah, dengan lwt menempati peringkat pertama. Meskipun terdapat perubahan peringkat, kedua metode tetap menempatkan ptl dan lwt sebagai dua prediktor numerik yang paling membedakan rata-rata antarkelas.
Statistik F digunakan sebagai ukuran relevansi marginal. Hasil pengujian signifikansi perlu ditafsirkan secara hati-hati apabila asumsi parametrik tidak terpenuhi.
2.2 Kruskal–Wallis
Kruskal–Wallis merupakan pendekatan nonparametrik yang menggunakan peringkat nilai prediktor untuk membandingkan distribusinya antarkelas respons.
Berbeda dari ANOVA, metode ini tidak langsung membandingkan rata-rata nilai asli, melainkan distribusi peringkat observasi.
Statistik Kruskal–Wallis dinyatakan sebagai:
\[H_j = \frac{12}{n(n+1)} \sum_{k=1}^{K} \frac{R_{jk}^{2}}{n_k} -3(n+1)\]
dengan \(R_{jk}\) merupakan jumlah peringkat prediktor ke-\(j\) pada kelas ke-\(k\), \(n_k\) jumlah observasi kelas ke-\(k\), dan \(n\) jumlah observasi seluruhnya.
Jika terdapat nilai yang sama (ties), statistik dikoreksi menggunakan:
\[H_{j,\text{koreksi}} = \frac{H_j} { 1-\frac{\sum_h(t_h^3-t_h)}{n^3-n} }\]
dengan \(t_h\) adalah banyaknya observasi pada kelompok nilai yang sama. Fungsi kruskal.test() di R telah menerapkan koreksi tersebut.
Implementasi Kruskal–Wallis
hasil_kw <- purrr::map_dfr(
prediktor_numerik,
function(pred) {
formula_uji <- stats::reformulate(
"low",
response = pred
)
uji <- stats::kruskal.test(
formula_uji,
data = data_train_klasifikasi
)
tibble::tibble(
Prediktor = pred,
Statistik_KW = as.numeric(uji$statistic),
p_value = uji$p.value
)
}
) %>%
dplyr::arrange(
dplyr::desc(Statistik_KW)
) %>%
dplyr::mutate(
Peringkat = dplyr::row_number()
)
knitr::kable(
hasil_kw,
digits = 4,
caption = "Pemeringkatan prediktor berdasarkan Kruskal-Wallis."
)| Prediktor | Statistik_KW | p_value | Peringkat |
|---|---|---|---|
| ptl | 10.5630 | 0.0012 | 1 |
| lwt | 5.8622 | 0.0155 | 2 |
| ftv | 1.2446 | 0.2646 | 3 |
| age | 0.6072 | 0.4358 | 4 |
Hasil Kruskal–Wallis menunjukkan bahwa ptl memiliki statistik tertinggi (10,5630; p = 0,0012), diikuti lwt (5,8622; p = 0,0155). Keduanya menunjukkan perbedaan distribusi peringkat yang signifikan pada taraf 5%.
Pemeringkatan ini konsisten dengan ANOVA klasik dalam menempatkan ptl dan lwt pada dua posisi teratas. Namun, Kruskal–Wallis mengukur perbedaan distribusi peringkat dan tidak selalu dapat diinterpretasikan sebagai perbedaan median apabila bentuk distribusi antarkelas berbeda.
2.3 Chi-Square
Statistik Chi-Square Pearson digunakan untuk mengukur ketergantungan antara prediktor kategorik dan respons kategorik. Dasar perhitungannya adalah perbedaan antara frekuensi observasi yang teramati dan frekuensi harapan ketika kedua variabel independen.
\[\chi_j^2 = \sum_{k=1}^{K} \sum_{m=1}^{M_j} \frac{(O_{km}-E_{km})^2}{E_{km}}\]
dengan:
\[E_{km} = \frac{O_{k\cdot}O_{\cdot m}}{n}\]
\(O_{km}\) merupakan frekuensi teramati, \(E_{km}\) frekuensi harapan, \(K\) jumlah kategori respons, dan \(M_j\) jumlah kategori prediktor.
Statistik yang lebih besar menunjukkan penyimpangan yang lebih besar dari kondisi independensi. Namun, besarnya statistik juga dipengaruhi jumlah kategori dan derajat bebas, sehingga perbandingan antarprediktor perlu dilakukan secara hati-hati.
Diskretisasi Prediktor Numerik
Untuk memungkinkan evaluasi seluruh prediktor menggunakan Chi-Square, prediktor numerik didiskretisasi menggunakan metode equal frequency berdasarkan kuantil data latih.
Agar tidak menuliskan prosedur yang sama berulang kali, dibuat fungsi yang dapat digunakan kembali untuk Chi-Square, oneR, Information Gain, Gain Ratio, dan Information Value.
# Fungsi diskretisasi berdasarkan kuantil data latih
buat_data_kategori <- function(jumlah_kelompok) {
latih <- data_train_klasifikasi %>%
dplyr::select(
low,
dplyr::all_of(prediktor_kategorik)
)
uji <- data_test_klasifikasi %>%
dplyr::select(
low,
dplyr::all_of(prediktor_kategorik)
)
for (pred in prediktor_numerik) {
nilai <- data_train_klasifikasi[[pred]]
batas <- stats::quantile(
nilai,
probs = seq_len(jumlah_kelompok - 1) /
jumlah_kelompok,
names = FALSE
)
# Menghapus batas berulang dan batas maksimum
batas <- sort(unique(batas))
batas <- batas[batas < max(nilai)]
batas <- c(-Inf, batas, Inf)
latih[[pred]] <- cut(
data_train_klasifikasi[[pred]],
breaks = batas,
include.lowest = TRUE
)
uji[[pred]] <- cut(
data_test_klasifikasi[[pred]],
breaks = batas,
include.lowest = TRUE
)
}
list(
latih = latih,
uji = uji
)
}
# Tiga kategori untuk Chi-Square
data_chisq <- buat_data_kategori(3)
data_train_chisq <- data_chisq$latih
data_test_chisq <- data_chisq$uji
# Memeriksa jumlah kategori aktual
tibble::tibble(
Prediktor = prediktor_numerik,
Jumlah_Kategori = vapply(
data_train_chisq[prediktor_numerik],
nlevels,
integer(1)
)
) %>%
knitr::kable(
caption = "Jumlah kategori hasil diskretisasi untuk Chi-Square."
)| Prediktor | Jumlah_Kategori |
|---|---|
| age | 3 |
| lwt | 3 |
| ptl | 2 |
| ftv | 3 |
Target diskretisasi adalah tiga kategori, tetapi jumlah kategori aktual dapat berkurang apabila terdapat banyak nilai yang sama. Pada data birthwt, kondisi tersebut terjadi pada ptl.
Pemeringkatan Seluruh Prediktor
hasil_chisq_semua <- purrr::map_dfr(
semua_prediktor,
function(pred) {
tab <- table(
data_train_chisq[[pred]],
data_train_chisq$low
)
uji <- stats::chisq.test(
tab,
correct = FALSE
)
tibble::tibble(
Prediktor = pred,
Chi_Square = as.numeric(uji$statistic),
DB = as.numeric(uji$parameter),
p_value = uji$p.value,
Minimum_Harapan = min(uji$expected)
)
}
) %>%
dplyr::arrange(
dplyr::desc(Chi_Square)
) %>%
dplyr::mutate(
Peringkat = dplyr::row_number()
)Warning in stats::chisq.test(tab, correct = FALSE): Chi-squared approximation
may be incorrect
knitr::kable(
hasil_chisq_semua,
digits = 4,
caption = "Pemeringkatan seluruh prediktor berdasarkan Chi-Square Pearson."
)| Prediktor | Chi_Square | DB | p_value | Minimum_Harapan | Peringkat |
|---|---|---|---|---|---|
| ptl | 11.1972 | 1 | 0.0008 | 7.1589 | 1 |
| lwt | 6.0306 | 2 | 0.0490 | 14.9404 | 2 |
| smoke | 4.6184 | 1 | 0.0316 | 18.0530 | 3 |
| ht | 4.5014 | 1 | 0.0339 | 3.7351 | 4 |
| ftv | 2.9939 | 2 | 0.2238 | 10.5828 | 5 |
| age | 1.5109 | 2 | 0.4698 | 14.0066 | 6 |
| ui | 1.2222 | 1 | 0.2689 | 5.9139 | 7 |
| race | 1.2080 | 2 | 0.5466 | 6.5364 | 8 |
# Pemeriksaan tambahan pada ht
p_fisher_ht <- stats::fisher.test(
table(
data_train_chisq$ht,
data_train_chisq$low
)
)$p.value
cat("p-value Fisher untuk ht:", round(p_fisher_ht, 4))p-value Fisher untuk ht: 0.0493
Chi-Square menempatkan ptl pada peringkat pertama (χ² = 11,1972; p = 0,0008), diikuti lwt (χ² = 6,0306; p = 0,0490), smoke (χ² = 4,6184; p = 0,0316), dan ht (χ² = 4,5014; p = 0,0339).
Pada ht, terdapat frekuensi harapan kurang dari lima. Pemeriksaan tambahan menggunakan Fisher’s Exact Test menghasilkan p = 0,0493. Nilai ini menunjukkan bahwa hasil pengujian perlu ditafsirkan dengan memperhatikan ukuran frekuensi pada tabel kontingensi.
Peringkat berdasarkan statistik Chi-Square tidak selalu sama dengan urutan nilai p karena jumlah kategori dan derajat bebas prediktor dapat berbeda.
2.4 AUC dan oneR
AUC dan oneR menilai prediktor berdasarkan performa klasifikasi sederhana. Keduanya tetap mengevaluasi satu prediktor pada satu waktu, tetapi menggunakan ukuran yang berbeda.
Area Under the ROC Curve (AUC) mengukur kemampuan model membedakan kelas berdasarkan skor prediksi. Kurva ROC dibentuk dari True Positive Rate (TPR) dan False Positive Rate (FPR):
\[TPR=\frac{TP}{TP+FN}\]
\[FPR=\frac{FP}{FP+TN}\]
AUC merupakan luas di bawah kurva ROC:
\[AUC=\int_0^1 TPR(u)\,du\]
Dalam Filtering, setiap prediktor \(X_j\) digunakan untuk membentuk model klasifikasi tersendiri, kemudian nilai AUC dijadikan skor relevansinya.
\[S_j=AUC(\hat f_j)\]
Sementara itu, oneR membentuk aturan klasifikasi dengan memilih kelas mayoritas pada setiap kategori prediktor. Ketepatan aturan tersebut dinyatakan sebagai:
\[oneR(X_j)= \frac{1}{n} \sum_{m=1}^{M_j} \max_{k=1,\ldots,K} n_{mk}\]
dengan \(n_{mk}\) merupakan jumlah observasi pada kategori prediktor ke-\(m\) dan kelas respons ke-\(k\).
AUC menilai kemampuan diskriminasi berdasarkan skor model, sedangkan oneR menilai ketepatan keputusan kelas. Karena itu, keduanya dapat menghasilkan peringkat prediktor yang berbeda.
Pemeringkatan Berdasarkan AUC
Mengikuti pendekatan pada buku acuan, setiap prediktor digunakan untuk membentuk pohon klasifikasi menggunakan rpart. Peluang prediksi kelas Rendah kemudian digunakan untuk menghitung AUC.
hasil_auc <- purrr::map_dfr(
semua_prediktor,
function(pred) {
formula_model <- stats::reformulate(
pred,
response = "low"
)
model <- rpart::rpart(
formula_model,
data = data_train_klasifikasi,
method = "class",
control = rpart::rpart.control(
cp = -1,
minsplit = 15
)
)
peluang <- predict(
model,
newdata = data_train_klasifikasi,
type = "prob"
)[, "Rendah"]
roc_model <- pROC::roc(
response = data_train_klasifikasi$low,
predictor = peluang,
levels = c("Tidak rendah", "Rendah"),
direction = "<",
quiet = TRUE
)
tibble::tibble(
Prediktor = pred,
AUC = as.numeric(pROC::auc(roc_model))
)
}
) %>%
dplyr::arrange(dplyr::desc(AUC)) %>%
dplyr::mutate(
Peringkat = dplyr::row_number()
)
knitr::kable(
hasil_auc,
digits = 4,
caption = "Pemeringkatan prediktor berdasarkan AUC."
)| Prediktor | AUC | Peringkat |
|---|---|---|
| lwt | 0.7851 | 1 |
| age | 0.6887 | 2 |
| ptl | 0.6081 | 3 |
| ftv | 0.6009 | 4 |
| smoke | 0.5919 | 5 |
| race | 0.5505 | 6 |
| ht | 0.5504 | 7 |
| ui | 0.5322 | 8 |
Hasil menunjukkan bahwa lwt memiliki AUC tertinggi (0,7851), diikuti age (0,6887) dan ptl (0,6081). Urutan tersebut berbeda dari ANOVA dan Chi-Square yang menempatkan ptl pada peringkat pertama.
Perlu diperhatikan bahwa AUC dihitung pada data latih yang juga digunakan untuk membentuk pohon. Oleh karena itu, nilai ini merupakan ukuran pemeringkatan dalam sampel dan dapat terlalu optimistis dibandingkan kemampuan generalisasi pada observasi baru.
Pemeringkatan Berdasarkan oneR
Prediktor numerik didiskretisasi menjadi lima kategori menggunakan fungsi yang telah disiapkan.
# Lima kategori untuk oneR
data_oneR <- buat_data_kategori(5)
data_train_oneR <- data_oneR$latih
# Akurasi kelas mayoritas sebagai baseline
akurasi_mayoritas <- max(
table(data_train_oneR$low)
) / nrow(data_train_oneR)
# Menghitung oneR pada setiap prediktor
hasil_oneR_semua <- purrr::map_dfr(
semua_prediktor,
function(pred) {
tab <- table(
data_train_oneR[[pred]],
data_train_oneR$low
)
akurasi <- sum(
apply(tab, 1, max)
) / sum(tab)
tibble::tibble(
Prediktor = pred,
Akurasi_oneR = akurasi,
Selisih_Baseline = akurasi - akurasi_mayoritas
)
}
) %>%
dplyr::arrange(
dplyr::desc(Akurasi_oneR)
) %>%
dplyr::mutate(
Peringkat = dplyr::min_rank(
dplyr::desc(Akurasi_oneR)
)
)
knitr::kable(
hasil_oneR_semua,
digits = 4,
caption = "Pemeringkatan prediktor berdasarkan oneR."
)| Prediktor | Akurasi_oneR | Selisih_Baseline | Peringkat |
|---|---|---|---|
| ptl | 0.7219 | 0.0331 | 1 |
| ht | 0.7020 | 0.0132 | 2 |
| lwt | 0.6954 | 0.0066 | 3 |
| age | 0.6887 | 0.0000 | 4 |
| ftv | 0.6887 | 0.0000 | 4 |
| race | 0.6887 | 0.0000 | 4 |
| smoke | 0.6887 | 0.0000 | 4 |
| ui | 0.6887 | 0.0000 | 4 |
cat(
"Akurasi kelas mayoritas:",
round(akurasi_mayoritas, 4)
)Akurasi kelas mayoritas: 0.6887
Hasil oneR menunjukkan bahwa ptl memperoleh ketepatan tertinggi sebesar 72,19%, diikuti ht (70,20%) dan lwt (69,54%). Sementara itu, akurasi kelas mayoritas adalah 68,87%. Dengan demikian, ptl meningkatkan ketepatan klasifikasi sebesar 3,31 poin persentase dibandingkan baseline.
Peningkatan tersebut masih relatif kecil. Skor oneR yang tinggi perlu ditafsirkan bersama akurasi kelas mayoritas, terutama ketika distribusi kelas tidak seimbang.
Visualisasi oneR
ggplot(
hasil_oneR_semua,
aes(
x = Akurasi_oneR,
y = forcats::fct_reorder(
Prediktor,
Akurasi_oneR
)
)
) +
geom_vline(
xintercept = akurasi_mayoritas,
linetype = "dashed",
color = "#E67E22",
linewidth = 0.8
) +
geom_point(
color = "#176B9A",
size = 3
) +
geom_text(
aes(
label = sprintf(
"%.2f%%",
Akurasi_oneR * 100
)
),
hjust = -0.2,
size = 3.5
) +
scale_x_continuous(
limits = c(0.66, 0.76),
labels = scales::label_percent(accuracy = 1)
) +
labs(
x = "Akurasi oneR",
y = "Prediktor"
) +
theme_minimal(base_size = 12) +
theme(
panel.grid.minor = element_blank()
)2.5 Information Gain dan Gain Ratio
Information Gain (IG) dan Gain Ratio (GR) menilai relevansi prediktor berdasarkan konsep entropy, yaitu ukuran ketidakpastian suatu variabel kategorik.
Jika respons \(Y\) memiliki \(K\) kelas, entropy respons didefinisikan sebagai:
\[H(Y)= -\sum_{k=1}^{K} P(Y=k)\log_2 P(Y=k)\]
Setelah kategori prediktor \(X_j\) diketahui, entropy kondisional respons adalah:
\[H(Y\mid X_j)= \sum_{m=1}^{M_j} P(X_j=m)\, H(Y\mid X_j=m)\]
Information Gain dihitung dari pengurangan entropy respons:
\[IG(Y,X_j)=H(Y)-H(Y\mid X_j)\]
Semakin besar Information Gain, semakin besar pengurangan ketidakpastian respons setelah prediktor diketahui.
Namun, Information Gain dapat cenderung memberikan skor tinggi pada prediktor yang mempunyai banyak kategori. Gain Ratio memperhitungkan entropy prediktor sebagai faktor normalisasi:
\[H(X_j)= -\sum_{m=1}^{M_j} P(X_j=m)\log_2 P(X_j=m)\]
\[GR(X_j)=\frac{IG(Y,X_j)}{H(X_j)}\]
Gain Ratio hanya dapat dihitung apabila \(H(X_j)>0\). Kedua metode dapat menghasilkan pemeringkatan berbeda karena menggunakan dasar normalisasi yang berbeda.
Implementasi Information Gain dan Gain Ratio
Pada praktikum ini, prediktor numerik didiskretisasi menjadi enam kategori menggunakan batas kuantil data latih.
# Enam kategori untuk IG, GR, dan IV
data_ig <- buat_data_kategori(6)
data_train_ig <- data_ig$latih
data_test_ig <- data_ig$uji
# Menghitung entropy respons
proporsi_y <- prop.table(
table(data_train_ig$low)
)
entropy_y <- -sum(
proporsi_y * log2(proporsi_y)
)
cat(
"Entropy respons:",
round(entropy_y, 4),
"bit"
)Entropy respons: 0.8946 bit
# Menghitung IG seluruh prediktor
skor_ig <- FSelector::information.gain(
low ~ .,
data = as.data.frame(data_train_ig),
unit = "log2"
) %>%
tibble::rownames_to_column("Prediktor") %>%
dplyr::rename(
Information_Gain = attr_importance
)
# Menghitung GR seluruh prediktor
skor_gr <- FSelector::gain.ratio(
low ~ .,
data = as.data.frame(data_train_ig),
unit = "log2"
) %>%
tibble::rownames_to_column("Prediktor") %>%
dplyr::rename(
Gain_Ratio = attr_importance
)
# Menghitung entropy setiap prediktor
entropy_x <- purrr::map_dfr(
semua_prediktor,
function(pred) {
prop <- prop.table(
table(data_train_ig[[pred]])
)
prop <- as.numeric(prop)
prop <- prop[prop > 0]
tibble::tibble(
Prediktor = pred,
Jumlah_Kategori = length(prop),
Entropy_X = -sum(prop * log2(prop))
)
}
)
# Menggabungkan hasil
hasil_ig_gr <- skor_ig %>%
dplyr::left_join(
skor_gr,
by = "Prediktor"
) %>%
dplyr::left_join(
entropy_x,
by = "Prediktor"
) %>%
dplyr::mutate(
Peringkat_IG = dplyr::min_rank(
dplyr::desc(Information_Gain)
),
Peringkat_GR = dplyr::min_rank(
dplyr::desc(Gain_Ratio)
)
) %>%
dplyr::arrange(Peringkat_IG)
knitr::kable(
hasil_ig_gr,
digits = 4,
caption = "Pemeringkatan prediktor berdasarkan Information Gain dan Gain Ratio."
)| Prediktor | Information_Gain | Gain_Ratio | Jumlah_Kategori | Entropy_X | Peringkat_IG | Peringkat_GR |
|---|---|---|---|---|---|---|
| lwt | 0.0557 | 0.0216 | 6 | 2.5815 | 1 | 4 |
| ptl | 0.0495 | 0.0805 | 2 | 0.6156 | 2 | 1 |
| ftv | 0.0241 | 0.0144 | 4 | 1.6787 | 3 | 5 |
| smoke | 0.0218 | 0.0227 | 2 | 0.9609 | 4 | 3 |
| ht | 0.0197 | 0.0493 | 2 | 0.4003 | 5 | 2 |
| age | 0.0177 | 0.0069 | 6 | 2.5697 | 6 | 7 |
| race | 0.0057 | 0.0040 | 3 | 1.4214 | 7 | 8 |
| ui | 0.0056 | 0.0102 | 2 | 0.5459 | 8 | 6 |
Entropy respons pada data latih sebesar 0,8946 bit. Hasil Information Gain menempatkan lwt pada peringkat pertama (0,0557), diikuti ptl (0,0495). Setelah dinormalisasi menggunakan entropy prediktor, Gain Ratio menempatkan ptl pada peringkat pertama (0,0805), diikuti ht (0,0493).
Perubahan tersebut berkaitan dengan jumlah dan distribusi kategori prediktor. lwt mempunyai enam kategori dengan entropy sebesar 2,5815 bit, sedangkan ptl mempunyai dua kategori dengan entropy sebesar 0,6156 bit. Perbedaan entropy sebagai pembagi menyebabkan ptl memperoleh Gain Ratio lebih tinggi daripada lwt, meskipun nilai Information Gain ptl lebih rendah. Dengan demikian, normalisasi terhadap entropy prediktor dapat mengubah urutan relevansi yang diperoleh.
Visualisasi Information Gain dan Gain Ratio
data_plot_ig_gr <- hasil_ig_gr %>%
dplyr::select(
Prediktor,
Information_Gain,
Gain_Ratio
) %>%
tidyr::pivot_longer(
cols = c(Information_Gain, Gain_Ratio),
names_to = "Metode",
values_to = "Skor"
) %>%
dplyr::mutate(
Metode = factor(
Metode,
levels = c("Information_Gain", "Gain_Ratio"),
labels = c("Information Gain", "Gain Ratio")
),
Prediktor = factor(
Prediktor,
levels = rev(hasil_ig_gr$Prediktor)
)
)
ggplot(
data_plot_ig_gr,
aes(
x = Skor,
y = Prediktor,
fill = Metode
)
) +
geom_col(width = 0.65) +
geom_text(
aes(label = sprintf("%.4f", Skor)),
hjust = -0.15,
size = 3.4
) +
facet_wrap(
~ Metode,
nrow = 1,
scales = "free_x"
) +
scale_fill_manual(
values = c(
"Information Gain" = "#235789",
"Gain Ratio" = "#E69F00"
)
) +
scale_x_continuous(
expand = expansion(mult = c(0, 0.25))
) +
labs(
x = "Skor",
y = "Prediktor"
) +
theme_minimal(base_size = 12) +
theme(
legend.position = "none",
panel.grid.major.y = element_blank(),
panel.grid.minor = element_blank()
)Kedua panel mempertahankan skala asli masing-masing ukuran. Oleh karena itu, panjang batang dibandingkan dalam metode yang sama, bukan secara langsung antara IG dan GR.
2.6 Information Value
Information Value (IV) digunakan untuk mengukur perbedaan distribusi kategori prediktor antara dua kelas respons. Perhitungannya berkaitan dengan Weight of Evidence (WoE).
Misalkan \(Y=1\) menyatakan kelas Rendah dan \(Y=0\) menyatakan kelas Tidak rendah. Untuk kategori prediktor ke-\(m\), didefinisikan:
\[p_{m1}=P(X_j=m\mid Y=1)\]
\[p_{m0}=P(X_j=m\mid Y=0)\]
Weight of Evidence dinyatakan sebagai:
\[WoE_m=\ln\left(\frac{p_{m1}}{p_{m0}}\right)\]
Nilai WoE positif menunjukkan bahwa kategori tersebut memiliki proporsi lebih besar pada kelas Rendah, sedangkan WoE negatif menunjukkan proporsi lebih besar pada kelas Tidak rendah.
Information Value diperoleh dengan menjumlahkan kontribusi setiap kategori:
\[IV(X_j)= \sum_{m=1}^{M_j} (p_{m1}-p_{m0}) \ln\left(\frac{p_{m1}}{p_{m0}}\right)\]
Semakin besar IV, semakin besar perbedaan distribusi kategori prediktor antara kedua kelas respons. Perhitungan memerlukan perhatian apabila terdapat kategori dengan frekuensi nol karena nilai logaritma rasio tidak berhingga.
Implementasi Information Value
Information Value dihitung menggunakan data hasil diskretisasi yang sama dengan Information Gain dan Gain Ratio, sehingga perbedaan peringkat tidak dipengaruhi perubahan skema kategori.
hasil_iv_semua <- purrr::map_dfr(
semua_prediktor,
function(pred) {
tab <- table(
data_train_ig[[pred]],
data_train_ig$low
)
# Proporsi kategori dalam masing-masing kelas
p0 <- tab[, "Tidak rendah"] /
sum(tab[, "Tidak rendah"])
p1 <- tab[, "Rendah"] /
sum(tab[, "Rendah"])
# IV tanpa smoothing apabila tidak ada sel nol
iv <- if (any(tab == 0)) {
NA_real_
} else {
sum((p1 - p0) * log(p1 / p0))
}
tibble::tibble(
Prediktor = pred,
Information_Value = iv,
Sel_Nol = sum(tab == 0),
Sel_Kurang_5 = sum(tab < 5)
)
}
) %>%
dplyr::mutate(
Peringkat_IV = dplyr::min_rank(
dplyr::desc(Information_Value)
)
) %>%
dplyr::arrange(Peringkat_IV)
knitr::kable(
hasil_iv_semua,
digits = 4,
caption = "Pemeringkatan prediktor berdasarkan Information Value."
)| Prediktor | Information_Value | Sel_Nol | Sel_Kurang_5 | Peringkat_IV |
|---|---|---|---|---|
| lwt | 0.3647 | 0 | 1 | 1 |
| ptl | 0.3168 | 0 | 0 | 2 |
| ftv | 0.1586 | 0 | 0 | 3 |
| smoke | 0.1405 | 0 | 0 | 4 |
| ht | 0.1253 | 0 | 0 | 5 |
| age | 0.1186 | 0 | 1 | 6 |
| race | 0.0371 | 0 | 0 | 7 |
| ui | 0.0355 | 0 | 0 | 8 |
Hasil pemeringkatan menunjukkan bahwa lwt memperoleh Information Value tertinggi sebesar 0,3647, diikuti ptl (0,3168) dan ftv (0,1586). Ketiga prediktor tersebut menunjukkan perbedaan distribusi kategori yang paling besar antara dua kelas respons berdasarkan ukuran IV.
Urutan pemeringkatan Information Value identik dengan Information Gain, tetapi berbeda dari Gain Ratio. Meskipun menggunakan dasar perhitungan yang berbeda, Information Value dan Information Gain menghasilkan prioritas prediktor yang sama pada data ini. Kesamaan tersebut tidak berarti kedua metode memiliki skala atau interpretasi skor yang sama.
Tidak ditemukan kategori dengan frekuensi nol sehingga seluruh nilai IV dapat dihitung tanpa smoothing. Meskipun demikian, beberapa sel pada age dan lwt memiliki frekuensi kurang dari lima sehingga stabilitas skor perlu diperhatikan.
2.7 Perbandingan Hasil Filtering
Masing-masing metode Filtering menggunakan dasar penilaian yang berbeda. ANOVA dan Kruskal–Wallis mengevaluasi perbedaan karakteristik prediktor numerik antarkelas, Chi-Square mengevaluasi ketergantungan kategori, AUC dan oneR menggunakan performa klasifikasi sederhana, sedangkan IG, GR, dan IV menggunakan ukuran informasi atau distribusi kelas.
Untuk memperlihatkan perbedaan tersebut, prediktor dengan peringkat pertama dari setiap metode dirangkum dalam satu tabel.
ringkasan_filtering <- tibble::tibble(
Metode = c(
"ANOVA",
"Kruskal-Wallis",
"Chi-Square",
"AUC",
"oneR",
"Information Gain",
"Gain Ratio",
"Information Value"
),
Prediktor_Teratas = c(
hasil_anova$Prediktor[which.max(hasil_anova$F_ANOVA)],
hasil_kw$Prediktor[which.max(hasil_kw$Statistik_KW)],
hasil_chisq_semua$Prediktor[
which.max(hasil_chisq_semua$Chi_Square)
],
hasil_auc$Prediktor[which.max(hasil_auc$AUC)],
hasil_oneR_semua$Prediktor[
which.max(hasil_oneR_semua$Akurasi_oneR)
],
hasil_ig_gr$Prediktor[
which.max(hasil_ig_gr$Information_Gain)
],
hasil_ig_gr$Prediktor[
which.max(hasil_ig_gr$Gain_Ratio)
],
hasil_iv_semua$Prediktor[
which.max(hasil_iv_semua$Information_Value)
]
)
)
knitr::kable(
ringkasan_filtering,
caption = "Prediktor dengan peringkat pertama pada setiap metode Filtering."
)| Metode | Prediktor_Teratas |
|---|---|
| ANOVA | ptl |
| Kruskal-Wallis | ptl |
| Chi-Square | ptl |
| AUC | lwt |
| oneR | ptl |
| Information Gain | lwt |
| Gain Ratio | ptl |
| Information Value | lwt |
Secara umum, ptl dan lwt mendominasi peringkat teratas, tetapi tidak selalu dengan urutan yang sama. AUC menempatkan lwt pada peringkat pertama, sedangkan ANOVA klasik, Kruskal–Wallis, Chi-Square, oneR, dan Gain Ratio menempatkan ptl pada peringkat pertama.
Perbedaan tersebut menunjukkan bahwa relevansi prediktor tidak bersifat tunggal, melainkan bergantung pada ukuran dan representasi data yang digunakan. Skor antar metode tidak dibandingkan secara langsung karena memiliki definisi dan skala berbeda. Selain itu, seluruh hasil Filtering masih bersifat marginal dan belum menunjukkan kontribusi suatu prediktor ketika digunakan bersama prediktor lain.
Filtering methods rank predictors using specific relevance measures without evaluating every combination of predictors in a multivariable model. In this section, eight candidate predictors are evaluated using several different criteria.
The numerical predictors are age, lwt, ptl, and ftv, while the categorical predictors are race, smoke, ht, and ui.
prediktor_numerik <- c("age", "lwt", "ptl", "ftv")
prediktor_kategorik <- c(
"race", "smoke", "ht", "ui"
)
semua_prediktor <- c(
prediktor_numerik,
prediktor_kategorik
)Using Filtering Methods with Different Variable Types
Choosing a Filtering method requires consideration of both response and predictor types. Although all these methods assess predictor relevance, their measures are not necessarily applicable to every combination of variable types.
In classification, the response is categorical. Predictor relevance can be assessed through between-class differences in predictor characteristics, categorical dependence, reductions in class uncertainty, or a model’s ability to distinguish classes.
In regression, the response is numerical. Relevance can be assessed through relationships with the numerical response, differences in the response across predictor categories, or a predictor’s contribution to the prediction error of a regression model.
A method may therefore be applicable to both tasks when its data requirements and relevance measure are appropriate. However, not every classification Filtering method can be transferred directly to regression without changing the approach.
Applicability of Filtering Methods
| Method | Predictors Evaluated | Classification | Regression |
|---|---|---|---|
| One-Way ANOVA | Numerical for classification; categorical for regression | Compares mean numerical predictor values across response classes | Compares the mean numerical response across predictor categories |
| Kruskal–Wallis | Numerical for classification; categorical for regression | Compares predictor rank distributions across classes | Compares response rank distributions across predictor categories |
| Chi-Square | Categorical; numerical after discretization | Can be used directly with a categorical response | Requires categorizing the numerical response if Chi-Square is to be used |
| AUC | Numerical or categorical through a classification model | Assesses class discrimination | Not directly applicable to a numerical response |
| oneR | Categorical; numerical after discretization | Assesses single-predictor classification rules | Not directly applicable using the classification formulation of oneR |
| Information Gain | Categorical; numerical after discretization | Measures the reduction in entropy of a categorical response | Requires an approach appropriate for continuous responses, such as discretization or continuous mutual-information estimation |
| Gain Ratio | Categorical; numerical after discretization | Normalizes Information Gain by predictor entropy | The same discrete-entropy formula does not apply directly to continuous responses |
| Information Value | Categorical; numerical after discretization | Used with a binary response | Not directly applicable to a numerical response |
This table describes applicability under the formulations used in this practical, rather than every possible extension of the methods.
Different Uses of ANOVA and Kruskal–Wallis
ANOVA and Kruskal–Wallis can be used in both classification and regression contexts, but the roles of the response and predictors in the statistical tests differ.
In classification, the categorical response serves as the grouping factor, and the numerical predictor is compared across classes.
For example, to examine the relevance of lwt to low-birth-weight status:
aov(lwt ~ low, data = data_train_klasifikasi)Call:
aov(formula = lwt ~ low, data = data_train_klasifikasi)
Terms:
low Residuals
Sum of Squares 4783.79 133562.15
Deg. of Freedom 1 149
Residual standard error: 29.93978
Estimated effects may be unbalanced
kruskal.test(
lwt ~ low,
data = data_train_klasifikasi
)
Kruskal-Wallis rank sum test
data: lwt by low
Kruskal-Wallis chi-squared = 5.8622, df = 1, p-value = 0.01547
These tests examine whether maternal weight characteristics differ between the two birth-weight classes.
In regression, a numerical response can be compared across the categories of a predictor.
For example, to examine the marginal relationship between categorical predictor smoke and numerical birth weight:
aov(bwt ~ smoke, data = data_train_regresi)Call:
aov(formula = bwt ~ smoke, data = data_train_regresi)
Terms:
smoke Residuals
Sum of Squares 2213165 70098703
Deg. of Freedom 1 149
Residual standard error: 685.9017
Estimated effects may be unbalanced
kruskal.test(
bwt ~ smoke,
data = data_train_regresi
)
Kruskal-Wallis rank sum test
data: bwt by smoke
Kruskal-Wallis chi-squared = 5.3401, df = 1, p-value = 0.02084
Here, ANOVA compares mean birth weight across the categories of smoke, whereas Kruskal–Wallis compares the corresponding birth-weight rank distributions.
These examples show that the same statistical method can be used in different modeling contexts when the variable structure meets its requirements.
However, ANOVA and Kruskal–Wallis are not direct choices for evaluating a relationship between two continuous numerical variables in regression. Correlation, univariable regression, or another appropriate relevance measure may be used instead.
Discretizing Predictors and Responses
The discrete formulations of Chi-Square, oneR, Information Gain, Gain Ratio, and Information Value require categorical data.
In classification, the response is already categorical. Numerical predictors can therefore be discretized when required.
In regression, the numerical response does not directly meet this requirement. Converting the response into categories may enable some categorical measures, but it also changes the analytical task and discards some information in the original values.
Accordingly, this practical does not discretize the regression response merely to force classification-based Filtering methods onto a regression problem.
Filtering demonstrations therefore focus on low, while potential applications to numerical responses are explained in terms of the requirements and formulations of each method.
Filtering results should still be interpreted as relevance measures under particular criteria. A predictor with a high relevance score does not necessarily improve predictive performance substantially when used alongside other predictors.
2.1 One-Way ANOVA
One-Way ANOVA measures differences in mean numerical predictor values across response classes. In Filtering, each predictor is analyzed separately, with the response class serving as the grouping factor.
The F statistic is the ratio of between-class variation to within-class variation:
\[F_j = \frac{ \displaystyle \frac{\sum_{k=1}^{K}n_k(\bar{x}_{jk}-\bar{x}_j)^2}{K-1} }{ \displaystyle \frac{\sum_{k=1}^{K}\sum_{i=1}^{n_k} (x_{ijk}-\bar{x}_{jk})^2}{n-K} }\]
Here, \(K\) is the number of response classes, \(n_k\) is the number of observations in class \(k\), \(\bar{x}_{jk}\) is the mean of predictor \(j\) in class \(k\), and \(\bar{x}_j\) is its overall mean.
A larger F statistic indicates greater differences in class means relative to within-class variability.
The classical F test relies on assumptions that require attention, particularly within-group normality and equal variances. Welch ANOVA is used as a sensitivity check when variances may differ across classes.
Implementing ANOVA and Welch ANOVA
hasil_anova <- purrr::map_dfr(
prediktor_numerik,
function(pred) {
formula_uji <- stats::reformulate(
"low",
response = pred
)
# Classical ANOVA
model_anova <- stats::aov(
formula_uji,
data = data_train_klasifikasi
)
tab_anova <- summary(model_anova)[[1]]
# Welch ANOVA
model_welch <- stats::oneway.test(
formula_uji,
data = data_train_klasifikasi,
var.equal = FALSE
)
tibble::tibble(
Predictor = pred,
F_ANOVA = as.numeric(tab_anova[1, "F value"]),
p_ANOVA = as.numeric(tab_anova[1, "Pr(>F)"]),
F_Welch = as.numeric(model_welch$statistic),
p_Welch = model_welch$p.value
)
}
) %>%
dplyr::mutate(
ANOVA_Rank = dplyr::min_rank(
dplyr::desc(F_ANOVA)
),
Welch_Rank = dplyr::min_rank(
dplyr::desc(F_Welch)
)
) %>%
dplyr::arrange(ANOVA_Rank)
knitr::kable(
hasil_anova,
digits = 4,
caption = "Predictor rankings from ANOVA and Welch ANOVA."
)| Predictor | F_ANOVA | p_ANOVA | F_Welch | p_Welch | ANOVA_Rank | Welch_Rank |
|---|---|---|---|---|---|---|
| ptl | 7.8369 | 0.0058 | 6.1145 | 0.0159 | 1 | 2 |
| lwt | 5.3367 | 0.0223 | 6.1783 | 0.0145 | 2 | 1 |
| age | 1.3370 | 0.2494 | 1.5211 | 0.2202 | 3 | 3 |
| ftv | 0.4795 | 0.4897 | 0.4747 | 0.4926 | 4 | 4 |
Classical ANOVA indicates that ptl has the largest F statistic (7.8369; p = 0.0058), followed by lwt (5.3367; p = 0.0223). Welch ANOVA reverses their order, placing lwt first. Despite the change in rank, both approaches identify ptl and lwt as the two numerical predictors with the strongest relative differences in class means.
The F statistic serves as a marginal relevance measure. Significance-test results should be interpreted cautiously if parametric assumptions are not satisfied.
2.2 Kruskal–Wallis
Kruskal–Wallis is a nonparametric method that uses ranks of predictor values to compare their distributions across response classes.
Unlike ANOVA, it does not directly compare means of the original values; instead, it compares the rank distributions of observations.
The Kruskal–Wallis statistic is:
\[H_j = \frac{12}{n(n+1)} \sum_{k=1}^{K} \frac{R_{jk}^{2}}{n_k} -3(n+1)\]
Here, \(R_{jk}\) is the sum of ranks for predictor \(j\) in class \(k\), \(n_k\) is the number of observations in that class, and \(n\) is the total sample size.
If observations have equal values (ties), the statistic is corrected as follows:
\[H_{j,\text{corrected}} = \frac{H_j} { 1-\frac{\sum_h(t_h^3-t_h)}{n^3-n} }\]
Here, \(t_h\) denotes the number of observations sharing a given value. The R function kruskal.test() applies this correction automatically.
Implementing Kruskal–Wallis
hasil_kw <- purrr::map_dfr(
prediktor_numerik,
function(pred) {
formula_uji <- stats::reformulate(
"low",
response = pred
)
uji <- stats::kruskal.test(
formula_uji,
data = data_train_klasifikasi
)
tibble::tibble(
Predictor = pred,
KW_Statistic = as.numeric(uji$statistic),
p_value = uji$p.value
)
}
) %>%
dplyr::arrange(
dplyr::desc(KW_Statistic)
) %>%
dplyr::mutate(
Rank = dplyr::row_number()
)
knitr::kable(
hasil_kw,
digits = 4,
caption = "Predictor rankings from Kruskal–Wallis."
)| Predictor | KW_Statistic | p_value | Rank |
|---|---|---|---|
| ptl | 10.5630 | 0.0012 | 1 |
| lwt | 5.8622 | 0.0155 | 2 |
| ftv | 1.2446 | 0.2646 | 3 |
| age | 0.6072 | 0.4358 | 4 |
The Kruskal–Wallis results rank ptl first (10.5630; p = 0.0012), followed by lwt (5.8622; p = 0.0155). Both show significant differences in rank distributions at the 5% level.
This ranking agrees with classical ANOVA in placing ptl and lwt in the top two positions. However, Kruskal–Wallis measures differences in rank distributions and cannot always be interpreted as a difference in medians when distributional shapes differ between classes.
2.3 Chi-Square
Pearson’s Chi-Square statistic measures dependence between a categorical predictor and a categorical response. It is based on differences between observed cell frequencies and the expected frequencies under independence.
\[\chi_j^2 = \sum_{k=1}^{K} \sum_{m=1}^{M_j} \frac{(O_{km}-E_{km})^2}{E_{km}}\]
where:
\[E_{km} = \frac{O_{k\cdot}O_{\cdot m}}{n}\]
\(O_{km}\) is the observed frequency, \(E_{km}\) the expected frequency, \(K\) the number of response categories, and \(M_j\) the number of predictor categories.
A larger statistic indicates a greater departure from independence. However, its magnitude also depends on the number of categories and degrees of freedom, so comparisons across predictors require care.
Discretizing Numerical Predictors
To evaluate all predictors using Chi-Square, the numerical predictors are discretized using equal-frequency intervals based on training-data quantiles.
To avoid repeating the same procedure, a reusable function is created for Chi-Square, oneR, Information Gain, Gain Ratio, and Information Value.
# Discretization function using training-data quantiles
buat_data_kategori <- function(jumlah_kelompok) {
latih <- data_train_klasifikasi %>%
dplyr::select(
low,
dplyr::all_of(prediktor_kategorik)
)
uji <- data_test_klasifikasi %>%
dplyr::select(
low,
dplyr::all_of(prediktor_kategorik)
)
for (pred in prediktor_numerik) {
nilai <- data_train_klasifikasi[[pred]]
batas <- stats::quantile(
nilai,
probs = seq_len(jumlah_kelompok - 1) /
jumlah_kelompok,
names = FALSE
)
# Remove repeated cut points and the maximum boundary
batas <- sort(unique(batas))
batas <- batas[batas < max(nilai)]
batas <- c(-Inf, batas, Inf)
latih[[pred]] <- cut(
data_train_klasifikasi[[pred]],
breaks = batas,
include.lowest = TRUE
)
uji[[pred]] <- cut(
data_test_klasifikasi[[pred]],
breaks = batas,
include.lowest = TRUE
)
}
list(
latih = latih,
uji = uji
)
}
# Three categories for Chi-Square
data_chisq <- buat_data_kategori(3)
data_train_chisq <- data_chisq$latih
data_test_chisq <- data_chisq$uji
# Check the actual number of categories
tibble::tibble(
Predictor = prediktor_numerik,
Category_Count = vapply(
data_train_chisq[prediktor_numerik],
nlevels,
integer(1)
)
) %>%
knitr::kable(
caption = "Number of categories after discretization for Chi-Square."
)| Predictor | Category_Count |
|---|---|
| age | 3 |
| lwt | 3 |
| ptl | 2 |
| ftv | 3 |
Three categories are targeted, but fewer may be formed when many observations have identical values. In birthwt, this occurs with ptl.
Ranking All Predictors
hasil_chisq_semua <- purrr::map_dfr(
semua_prediktor,
function(pred) {
tab <- table(
data_train_chisq[[pred]],
data_train_chisq$low
)
uji <- stats::chisq.test(
tab,
correct = FALSE
)
tibble::tibble(
Predictor = pred,
Chi_Square = as.numeric(uji$statistic),
DF = as.numeric(uji$parameter),
p_value = uji$p.value,
Minimum_Expected = min(uji$expected)
)
}
) %>%
dplyr::arrange(
dplyr::desc(Chi_Square)
) %>%
dplyr::mutate(
Rank = dplyr::row_number()
)Warning in stats::chisq.test(tab, correct = FALSE): Chi-squared approximation
may be incorrect
knitr::kable(
hasil_chisq_semua,
digits = 4,
caption = "Ranking all predictors by Pearson Chi-Square."
)| Predictor | Chi_Square | DF | p_value | Minimum_Expected | Rank |
|---|---|---|---|---|---|
| ptl | 11.1972 | 1 | 0.0008 | 7.1589 | 1 |
| lwt | 6.0306 | 2 | 0.0490 | 14.9404 | 2 |
| smoke | 4.6184 | 1 | 0.0316 | 18.0530 | 3 |
| ht | 4.5014 | 1 | 0.0339 | 3.7351 | 4 |
| ftv | 2.9939 | 2 | 0.2238 | 10.5828 | 5 |
| age | 1.5109 | 2 | 0.4698 | 14.0066 | 6 |
| ui | 1.2222 | 1 | 0.2689 | 5.9139 | 7 |
| race | 1.2080 | 2 | 0.5466 | 6.5364 | 8 |
# Additional check for ht
p_fisher_ht <- stats::fisher.test(
table(
data_train_chisq$ht,
data_train_chisq$low
)
)$p.value
cat("Fisher p-value for ht:", round(p_fisher_ht, 4))Fisher p-value for ht: 0.0493
Chi-Square ranks ptl first (χ² = 11.1972; p = 0.0008), followed by lwt (χ² = 6.0306; p = 0.0490), smoke (χ² = 4.6184; p = 0.0316), and ht (χ² = 4.5014; p = 0.0339).
For ht, one expected cell frequency is below five. An additional Fisher’s Exact Test yields p = 0.0493, indicating that the significance result should be interpreted in light of the cell counts in the contingency table.
Ranking by the Chi-Square statistic does not necessarily match ranking by p-value, since predictors can have different numbers of categories and degrees of freedom.
2.4 AUC and oneR
AUC and oneR assess predictors through simple classification performance. Both consider one predictor at a time, but they use different performance measures.
Area Under the ROC Curve (AUC) measures a model’s ability to distinguish classes using prediction scores. The ROC curve is formed from the True Positive Rate (TPR) and False Positive Rate (FPR):
\[TPR=\frac{TP}{TP+FN}\]
\[FPR=\frac{FP}{FP+TN}\]
AUC is the area under the ROC curve:
\[AUC=\int_0^1 TPR(u)\,du\]
In Filtering, a separate classification model is fitted with each predictor \(X_j\), and its AUC serves as the predictor’s relevance score.
\[S_j=AUC(\hat f_j)\]
oneR, by contrast, constructs a classification rule by predicting the majority class within each predictor category. The accuracy of this rule is:
\[oneR(X_j)= \frac{1}{n} \sum_{m=1}^{M_j} \max_{k=1,\ldots,K} n_{mk}\]
Here, \(n_{mk}\) is the number of observations in predictor category \(m\) and response class \(k\).
AUC assesses score-based discrimination, while oneR measures the accuracy of class assignments. They may therefore produce different predictor rankings.
Ranking Predictors by AUC
Following the reference text, a classification tree is fitted separately for each predictor using rpart. Predicted probabilities of the Low class are then used to calculate AUC.
hasil_auc <- purrr::map_dfr(
semua_prediktor,
function(pred) {
formula_model <- stats::reformulate(
pred,
response = "low"
)
model <- rpart::rpart(
formula_model,
data = data_train_klasifikasi,
method = "class",
control = rpart::rpart.control(
cp = -1,
minsplit = 15
)
)
peluang <- predict(
model,
newdata = data_train_klasifikasi,
type = "prob"
)[, "Low"]
roc_model <- pROC::roc(
response = data_train_klasifikasi$low,
predictor = peluang,
levels = c("Not low", "Low"),
direction = "<",
quiet = TRUE
)
tibble::tibble(
Predictor = pred,
AUC = as.numeric(pROC::auc(roc_model))
)
}
) %>%
dplyr::arrange(dplyr::desc(AUC)) %>%
dplyr::mutate(
Rank = dplyr::row_number()
)
knitr::kable(
hasil_auc,
digits = 4,
caption = "Predictor rankings by AUC."
)| Predictor | AUC | Rank |
|---|---|---|
| lwt | 0.7851 | 1 |
| age | 0.6887 | 2 |
| ptl | 0.6081 | 3 |
| ftv | 0.6009 | 4 |
| smoke | 0.5919 | 5 |
| race | 0.5505 | 6 |
| ht | 0.5504 | 7 |
| ui | 0.5322 | 8 |
The results show that lwt has the highest AUC (0.7851), followed by age (0.6887) and ptl (0.6081). This ranking differs from ANOVA and Chi-Square, which place ptl first.
Note that AUC is calculated on the same training observations used to fit the trees. These are therefore in-sample ranking scores and may be overly optimistic relative to performance on new observations.
Ranking Predictors by oneR
Numerical predictors are discretized into five categories using the previously defined function.
# Five categories for oneR
data_oneR <- buat_data_kategori(5)
data_train_oneR <- data_oneR$latih
# Majority-class accuracy as a baseline
akurasi_mayoritas <- max(
table(data_train_oneR$low)
) / nrow(data_train_oneR)
# Calculate oneR for each predictor
hasil_oneR_semua <- purrr::map_dfr(
semua_prediktor,
function(pred) {
tab <- table(
data_train_oneR[[pred]],
data_train_oneR$low
)
akurasi <- sum(
apply(tab, 1, max)
) / sum(tab)
tibble::tibble(
Predictor = pred,
oneR_Accuracy = akurasi,
Difference_from_Baseline = akurasi - akurasi_mayoritas
)
}
) %>%
dplyr::arrange(
dplyr::desc(oneR_Accuracy)
) %>%
dplyr::mutate(
Rank = dplyr::min_rank(
dplyr::desc(oneR_Accuracy)
)
)
knitr::kable(
hasil_oneR_semua,
digits = 4,
caption = "Predictor rankings by oneR."
)| Predictor | oneR_Accuracy | Difference_from_Baseline | Rank |
|---|---|---|---|
| ptl | 0.7219 | 0.0331 | 1 |
| ht | 0.7020 | 0.0132 | 2 |
| lwt | 0.6954 | 0.0066 | 3 |
| age | 0.6887 | 0.0000 | 4 |
| ftv | 0.6887 | 0.0000 | 4 |
| race | 0.6887 | 0.0000 | 4 |
| smoke | 0.6887 | 0.0000 | 4 |
| ui | 0.6887 | 0.0000 | 4 |
cat(
"Majority-class accuracy:",
round(akurasi_mayoritas, 4)
)Majority-class accuracy: 0.6887
The oneR results show that ptl has the highest accuracy at 72.19%, followed by ht (70.20%) and lwt (69.54%). The majority-class baseline accuracy is 68.87%. Thus, ptl improves training accuracy by 3.31 percentage points relative to the baseline.
This improvement is still relatively small. A high oneR score should be interpreted alongside majority-class accuracy, particularly when the class distribution is imbalanced.
Visualizing oneR
ggplot(
hasil_oneR_semua,
aes(
x = oneR_Accuracy,
y = forcats::fct_reorder(
Predictor,
oneR_Accuracy
)
)
) +
geom_vline(
xintercept = akurasi_mayoritas,
linetype = "dashed",
color = "#E67E22",
linewidth = 0.8
) +
geom_point(
color = "#176B9A",
size = 3
) +
geom_text(
aes(
label = sprintf(
"%.2f%%",
oneR_Accuracy * 100
)
),
hjust = -0.2,
size = 3.5
) +
scale_x_continuous(
limits = c(0.66, 0.76),
labels = scales::label_percent(accuracy = 1)
) +
labs(
x = "oneR Accuracy",
y = "Predictor"
) +
theme_minimal(base_size = 12) +
theme(
panel.grid.minor = element_blank()
)2.5 Information Gain and Gain Ratio
Information Gain (IG) and Gain Ratio (GR) assess predictor relevance through entropy, a measure of uncertainty in a categorical variable.
If the response \(Y\) has \(K\) classes, response entropy is defined as:
\[H(Y)= -\sum_{k=1}^{K} P(Y=k)\log_2 P(Y=k)\]
Conditional response entropy after observing predictor \(X_j\) is:
\[H(Y\mid X_j)= \sum_{m=1}^{M_j} P(X_j=m)\, H(Y\mid X_j=m)\]
Information Gain is the reduction in response entropy:
\[IG(Y,X_j)=H(Y)-H(Y\mid X_j)\]
Greater Information Gain indicates a greater reduction in response uncertainty after observing the predictor.
Information Gain may, however, favor predictors with many categories. Gain Ratio uses predictor entropy as a normalization factor:
\[H(X_j)= -\sum_{m=1}^{M_j} P(X_j=m)\log_2 P(X_j=m)\]
\[GR(X_j)=\frac{IG(Y,X_j)}{H(X_j)}\]
Gain Ratio is defined only when \(H(X_j)>0\). The two measures may yield different rankings because of this normalization.
Implementing Information Gain and Gain Ratio
In this practical, numerical predictors are discretized into six categories using training-data quantile boundaries.
# Six categories for IG, GR, and IV
data_ig <- buat_data_kategori(6)
data_train_ig <- data_ig$latih
data_test_ig <- data_ig$uji
# Calculate response entropy
proporsi_y <- prop.table(
table(data_train_ig$low)
)
entropy_y <- -sum(
proporsi_y * log2(proporsi_y)
)
cat(
"Response entropy:",
round(entropy_y, 4),
"bit"
)Response entropy: 0.8946 bit
# Calculate IG for all predictors
skor_ig <- FSelector::information.gain(
low ~ .,
data = as.data.frame(data_train_ig),
unit = "log2"
) %>%
tibble::rownames_to_column("Predictor") %>%
dplyr::rename(
Information_Gain = attr_importance
)
# Calculate GR for all predictors
skor_gr <- FSelector::gain.ratio(
low ~ .,
data = as.data.frame(data_train_ig),
unit = "log2"
) %>%
tibble::rownames_to_column("Predictor") %>%
dplyr::rename(
Gain_Ratio = attr_importance
)
# Calculate each predictor’s entropy
entropy_x <- purrr::map_dfr(
semua_prediktor,
function(pred) {
prop <- prop.table(
table(data_train_ig[[pred]])
)
prop <- as.numeric(prop)
prop <- prop[prop > 0]
tibble::tibble(
Predictor = pred,
Category_Count = length(prop),
Entropy_X = -sum(prop * log2(prop))
)
}
)
# Combine results
hasil_ig_gr <- skor_ig %>%
dplyr::left_join(
skor_gr,
by = "Predictor"
) %>%
dplyr::left_join(
entropy_x,
by = "Predictor"
) %>%
dplyr::mutate(
IG_Rank = dplyr::min_rank(
dplyr::desc(Information_Gain)
),
GR_Rank = dplyr::min_rank(
dplyr::desc(Gain_Ratio)
)
) %>%
dplyr::arrange(IG_Rank)
knitr::kable(
hasil_ig_gr,
digits = 4,
caption = "Predictor rankings by Information Gain and Gain Ratio."
)| Predictor | Information_Gain | Gain_Ratio | Category_Count | Entropy_X | IG_Rank | GR_Rank |
|---|---|---|---|---|---|---|
| lwt | 0.0557 | 0.0216 | 6 | 2.5815 | 1 | 4 |
| ptl | 0.0495 | 0.0805 | 2 | 0.6156 | 2 | 1 |
| ftv | 0.0241 | 0.0144 | 4 | 1.6787 | 3 | 5 |
| smoke | 0.0218 | 0.0227 | 2 | 0.9609 | 4 | 3 |
| ht | 0.0197 | 0.0493 | 2 | 0.4003 | 5 | 2 |
| age | 0.0177 | 0.0069 | 6 | 2.5697 | 6 | 7 |
| race | 0.0057 | 0.0040 | 3 | 1.4214 | 7 | 8 |
| ui | 0.0056 | 0.0102 | 2 | 0.5459 | 8 | 6 |
Training-data response entropy is 0.8946 bits. Information Gain ranks lwt first (0.0557), followed by ptl (0.0495). After normalization by predictor entropy, Gain Ratio ranks ptl first (0.0805), followed by ht (0.0493).
This change relates to the number and distribution of predictor categories. lwt has six categories and an entropy of 2.5815 bits, while ptl has two categories and an entropy of 0.6156 bits. Because ptl has a smaller entropy denominator, its Gain Ratio exceeds that of lwt despite having lower Information Gain. Thus, normalizing by predictor entropy can change the relevance ranking.
Visualizing Information Gain and Gain Ratio
data_plot_ig_gr <- hasil_ig_gr %>%
dplyr::select(
Predictor,
Information_Gain,
Gain_Ratio
) %>%
tidyr::pivot_longer(
cols = c(Information_Gain, Gain_Ratio),
names_to = "Method",
values_to = "Score"
) %>%
dplyr::mutate(
Method = factor(
Method,
levels = c("Information_Gain", "Gain_Ratio"),
labels = c("Information Gain", "Gain Ratio")
),
Predictor = factor(
Predictor,
levels = rev(hasil_ig_gr$Predictor)
)
)
ggplot(
data_plot_ig_gr,
aes(
x = Score,
y = Predictor,
fill = Method
)
) +
geom_col(width = 0.65) +
geom_text(
aes(label = sprintf("%.4f", Score)),
hjust = -0.15,
size = 3.4
) +
facet_wrap(
~ Method,
nrow = 1,
scales = "free_x"
) +
scale_fill_manual(
values = c(
"Information Gain" = "#235789",
"Gain Ratio" = "#E69F00"
)
) +
scale_x_continuous(
expand = expansion(mult = c(0, 0.25))
) +
labs(
x = "Score",
y = "Predictor"
) +
theme_minimal(base_size = 12) +
theme(
legend.position = "none",
panel.grid.major.y = element_blank(),
panel.grid.minor = element_blank()
)Each panel retains the original scale of its measure. Bar lengths should therefore be compared within a method, not directly between IG and GR.
2.6 Information Value
Information Value (IV) measures differences in a predictor’s category distribution between two response classes. Its calculation is related to the Weight of Evidence (WoE).
Let \(Y=1\) denote the Low class and \(Y=0\) the Not low class. For predictor category \(m\), define:
\[p_{m1}=P(X_j=m\mid Y=1)\]
\[p_{m0}=P(X_j=m\mid Y=0)\]
Weight of Evidence is:
\[WoE_m=\ln\left(\frac{p_{m1}}{p_{m0}}\right)\]
A positive WoE indicates that a category is proportionally more common within the Low class, while a negative WoE indicates that it is proportionally more common within the Not low class.
Information Value sums the contribution of each category:
\[IV(X_j)= \sum_{m=1}^{M_j} (p_{m1}-p_{m0}) \ln\left(\frac{p_{m1}}{p_{m0}}\right)\]
A larger IV indicates a greater difference in the predictor’s category distribution between response classes. Zero-frequency categories require special handling because their log-ratios are not finite.
Implementing Information Value
Information Value is calculated using the same discretized data as Information Gain and Gain Ratio, so differences in the rankings are not caused by changes in category boundaries.
hasil_iv_semua <- purrr::map_dfr(
semua_prediktor,
function(pred) {
tab <- table(
data_train_ig[[pred]],
data_train_ig$low
)
# Category proportions within each class
p0 <- tab[, "Not low"] /
sum(tab[, "Not low"])
p1 <- tab[, "Low"] /
sum(tab[, "Low"])
# Calculate IV without smoothing when there are no zero-frequency cells
iv <- if (any(tab == 0)) {
NA_real_
} else {
sum((p1 - p0) * log(p1 / p0))
}
tibble::tibble(
Predictor = pred,
Information_Value = iv,
Zero_Cells = sum(tab == 0),
Cells_Below_5 = sum(tab < 5)
)
}
) %>%
dplyr::mutate(
IV_Rank = dplyr::min_rank(
dplyr::desc(Information_Value)
)
) %>%
dplyr::arrange(IV_Rank)
knitr::kable(
hasil_iv_semua,
digits = 4,
caption = "Predictor rankings by Information Value."
)| Predictor | Information_Value | Zero_Cells | Cells_Below_5 | IV_Rank |
|---|---|---|---|---|
| lwt | 0.3647 | 0 | 1 | 1 |
| ptl | 0.3168 | 0 | 0 | 2 |
| ftv | 0.1586 | 0 | 0 | 3 |
| smoke | 0.1405 | 0 | 0 | 4 |
| ht | 0.1253 | 0 | 0 | 5 |
| age | 0.1186 | 0 | 1 | 6 |
| race | 0.0371 | 0 | 0 | 7 |
| ui | 0.0355 | 0 | 0 | 8 |
The ranking shows that lwt has the highest Information Value (0.3647), followed by ptl (0.3168) and ftv (0.1586). Under IV, these three predictors display the greatest differences in category distributions between the two response classes.
The IV ranking is identical to that of Information Gain, but differs from Gain Ratio. Although IV and IG are calculated differently, they prioritize the same predictors in these data. This agreement does not imply that the methods have the same score scales or interpretations.
No zero-frequency categories are found, so all IV scores can be calculated without smoothing. Nevertheless, several cells for age and lwt have fewer than five observations, which should be considered when assessing score stability.
2.7 Comparing Filtering Results
Each Filtering method uses a different basis for relevance. ANOVA and Kruskal–Wallis assess differences in numerical predictor characteristics across classes; Chi-Square assesses categorical dependence; AUC and oneR use simple classification performance; and IG, GR, and IV use information-based or class-distribution measures.
To illustrate these differences, the top-ranked predictor from each method is summarized in a table.
ringkasan_filtering <- tibble::tibble(
Method = c(
"ANOVA",
"Kruskal-Wallis",
"Chi-Square",
"AUC",
"oneR",
"Information Gain",
"Gain Ratio",
"Information Value"
),
Top_Predictor = c(
hasil_anova$Predictor[which.max(hasil_anova$F_ANOVA)],
hasil_kw$Predictor[which.max(hasil_kw$KW_Statistic)],
hasil_chisq_semua$Predictor[
which.max(hasil_chisq_semua$Chi_Square)
],
hasil_auc$Predictor[which.max(hasil_auc$AUC)],
hasil_oneR_semua$Predictor[
which.max(hasil_oneR_semua$oneR_Accuracy)
],
hasil_ig_gr$Predictor[
which.max(hasil_ig_gr$Information_Gain)
],
hasil_ig_gr$Predictor[
which.max(hasil_ig_gr$Gain_Ratio)
],
hasil_iv_semua$Predictor[
which.max(hasil_iv_semua$Information_Value)
]
)
)
knitr::kable(
ringkasan_filtering,
caption = "Top-ranked predictor from each Filtering method."
)| Method | Top_Predictor |
|---|---|
| ANOVA | ptl |
| Kruskal-Wallis | ptl |
| Chi-Square | ptl |
| AUC | lwt |
| oneR | ptl |
| Information Gain | lwt |
| Gain Ratio | ptl |
| Information Value | lwt |
Overall, ptl and lwt dominate the highest rankings, though not always in the same order. AUC ranks lwt first, while classical ANOVA, Kruskal–Wallis, Chi-Square, oneR, and Gain Ratio rank ptl first.
These differences show that predictor relevance is not unique, but depends on the chosen measure and data representation. Scores from different methods are not compared directly because their definitions and scales differ. Moreover, all Filtering results remain marginal and do not establish a predictor’s additional contribution when used with others.
Entropy respons binerBinary response entropy
Ubah proporsi kelas positif untuk melihat ketidakpastian kelas.Change the positive-class proportion to inspect uncertainty.
Data ilustratif, bukan hasil estimasi R pada dataset praktikum.Illustrative data, not estimated R results for the practicum dataset.
II · 3. Seleksi Variabel Menggunakan WrapperII · 3. Variable Selection Using Wrapper Methods
Best Subset mengevaluasi kombinasi koefisien; Boruta membandingkan kepentingan fitur dengan fitur bayangan. Kedua pendekatan menjawab pertanyaan yang berbeda.Best Subset evaluates coefficient combinations; Boruta compares importance with shadow features. These approaches answer different questions.
Berbeda dari Filtering, metode Wrapper mengevaluasi kandidat prediktor dengan melibatkan pembentukan model. Seleksi dilakukan terhadap kombinasi prediktor, sehingga kontribusi suatu prediktor dinilai dalam konteks prediktor lain yang digunakan bersama-sama.
Pada bagian ini, Best Subset Selection diterapkan untuk regresi berat lahir bayi menggunakan respons bwt.
Penggunaan Metode Wrapper Berdasarkan Tipe Peubah
Metode Wrapper mengevaluasi relevansi prediktor melalui pembentukan model. Oleh karena itu, kesesuaian metode tidak hanya bergantung pada tipe prediktor, tetapi juga pada model dasar dan fungsi evaluasi yang digunakan.
Berbeda dari sejumlah metode Filtering yang memerlukan kombinasi tipe peubah tertentu, pendekatan Wrapper umumnya dapat digunakan pada regresi maupun klasifikasi selama model yang dievaluasi mendukung tipe respons tersebut.
Prediktor numerik dan kategorik juga dapat digunakan secara bersama-sama. Namun, representasi prediktor perlu disesuaikan dengan kebutuhan model, misalnya melalui pembentukan variabel dummy pada regresi linear atau regresi logistik.
Kesesuaian Metode Wrapper
| Metode | Prediktor Numerik | Prediktor Kategorik | Regresi | Klasifikasi |
|---|---|---|---|---|
| Best Subset Selection | Dapat digunakan langsung | Dapat digunakan melalui representasi dummy atau seleksi faktor sebagai kelompok | Regresi linear | Dapat diterapkan melalui model klasifikasi, misalnya regresi logistik |
| Genetic Algorithm | Dapat digunakan | Dapat digunakan; kategori mengikuti kebutuhan model | Memerlukan fungsi evaluasi regresi | Memerlukan fungsi evaluasi klasifikasi |
| Simulated Annealing | Dapat digunakan | Dapat digunakan; kategori mengikuti kebutuhan model | Memerlukan fungsi evaluasi regresi | Memerlukan fungsi evaluasi klasifikasi |
| Boruta | Dapat digunakan | Dapat digunakan sebagai faktor | Menggunakan kepentingan prediktor pada model regresi | Menggunakan kepentingan prediktor pada model klasifikasi |
Pada Best Subset Selection, Genetic Algorithm, dan Simulated Annealing, yang dibedakan adalah strategi pencarian subset. Jenis respons ditangani oleh model yang digunakan untuk mengevaluasi setiap subset.
Boruta mempunyai mekanisme berbeda karena tidak mencari subset berdasarkan satu fungsi objektif global seperti AIC. Boruta mengevaluasi kepentingan setiap prediktor terhadap pembanding acak melalui model Random Forest.
Best Subset Selection untuk Regresi dan Klasifikasi
Best Subset Selection tidak terbatas pada regresi linear. Prinsip pencarian seluruh kombinasi prediktor dapat digunakan pada model lain, termasuk regresi logistik untuk klasifikasi biner.
Pada regresi linear, setiap subset \(S\) membentuk model:
\[Y_i=\beta_0+\sum_{j\in S}\beta_jX_{ij}+\varepsilon_i\]
Model dapat dipilih berdasarkan kriteria seperti Adjusted R-squared, Mallows’ \(C_p\), AIC, atau BIC.
Pada klasifikasi biner, setiap subset dapat membentuk model regresi logistik:
\[\log\left(\frac{\pi_i}{1-\pi_i}\right) = \beta_0+\sum_{j\in S}\beta_jX_{ij}\]
dengan \(\pi_i=P(Y_i=1\mid\mathbf{x}_i)\).
Kriteria seperti AIC dan BIC dapat digunakan untuk membandingkan model logistik dengan subset berbeda:
\[AIC_S=-2\ell_S+2k_S\]
\[BIC_S=-2\ell_S+k_S\ln(n)\]
dengan \(\ell_S\) merupakan log-likelihood maksimum model subset \(S\), sedangkan \(k_S\) adalah jumlah parameter yang diestimasi.
Dengan demikian, prinsip Best Subset tetap berupa pencarian kombinasi prediktor, tetapi proses estimasi dan ukuran evaluasi disesuaikan dengan jenis respons.
Perlu diperhatikan bahwa fungsi leaps::regsubsets() yang digunakan dalam praktikum sebelumnya ditujukan untuk pencarian subset pada regresi linear. Fungsi tersebut tidak secara langsung melakukan Best Subset untuk regresi logistik. Penerapan pada klasifikasi memerlukan prosedur pencarian subset yang mengevaluasi model klasifikasi, misalnya melalui glm() dengan keluarga binomial.
Seleksi Prediktor Kategorik sebagai Kelompok
Pada prediktor kategorik dengan lebih dari dua kategori, satu variabel asli dapat menghasilkan beberapa koefisien dummy.
Sebagai contoh, race mempunyai tiga kategori sehingga menghasilkan dua koefisien dengan kategori referensi White:
\[\beta_{\mathrm{Black}}X_{\mathrm{Black}} + \beta_{\mathrm{Other}}X_{\mathrm{Other}}\]
Jika pencarian subset dilakukan terhadap setiap kolom matriks desain secara individual, salah satu dummy dapat terpilih tanpa dummy lainnya.
Sebaliknya, jika unit seleksi ditetapkan sebagai variabel asli, kedua dummy tersebut perlu dimasukkan atau dikeluarkan bersama-sama sebagai satu kelompok.
Perbedaan unit seleksi ini perlu dijelaskan ketika menginterpretasikan jumlah prediktor terpilih. Pemilihan empat koefisien tidak selalu sama dengan pemilihan empat variabel asli.
Pada praktikum Best Subset sebelumnya, seleksi dilakukan terhadap koefisien matriks desain menggunakan regsubsets(). Sementara itu, Boruta dan Group LASSO memperlihatkan pendekatan yang mempertahankan struktur prediktor asli dalam proses seleksi.
3.1 Best Subset Selection
Best Subset Selection mencari kombinasi prediktor terbaik berdasarkan kriteria evaluasi model. Untuk \(p\) kandidat koefisien, terdapat \(2^p\) kemungkinan subset, termasuk model tanpa prediktor.
Model regresi linear untuk subset \(S\) dapat dituliskan sebagai:
\[Y_i=\beta_0+\sum_{j\in S}\beta_jX_{ij}+\varepsilon_i\]
Pada setiap ukuran subset, dipilih model dengan Residual Sum of Squares (RSS) terkecil:
\[RSS=\sum_{i=1}^{n}(Y_i-\hat Y_i)^2\]
RSS akan cenderung menurun ketika prediktor ditambahkan. Oleh karena itu, pemilihan ukuran subset terbaik memerlukan kriteria yang mempertimbangkan kompleksitas model.
Referensi: James et al. (2021), An Introduction to Statistical Learning, Gambar 6.1.
Gambar ini memperlihatkan setiap kemungkinan model sebagai titik, sedangkan kurva merah menunjukkan model dengan RSS terkecil pada setiap ukuran subset. Ini menjelaskan konsep exhaustive search jauh lebih baik daripada tabel kombinasi koefisien saja.
Kriteria yang digunakan pada praktikum ini meliputi:
Adjusted R-squared
\[R_{\mathrm{adj}}^2= 1- \frac{RSS/(n-k-1)} {TSS/(n-1)}\]
dengan \(k\) jumlah koefisien prediktor selain intersep.
Mallows’ \(C_p\)
\[C_p= \frac{RSS}{\hat{\sigma}_{\mathrm{full}}^2} -n+2(k+1)\]
dengan \(\hat{\sigma}_{\mathrm{full}}^2\) merupakan estimasi varians galat dari model lengkap.
Bayesian Information Criterion (BIC)
\[BIC= n\ln\left(\frac{RSS}{n}\right) +(k+1)\ln(n)\]
Persamaan BIC tersebut dituliskan hingga konstanta yang sama pada semua model dengan respons dan sampel identik. Nilai BIC yang dilaporkan regsubsets() menggunakan bentuk relatif, sehingga angka absolutnya tidak harus sama dengan keluaran BIC() pada objek lm, tetapi pemilihan model berdasarkan nilai minimum tetap berlaku.
Model dipilih berdasarkan Adjusted R-squared maksimum atau Cp dan BIC minimum. Pada praktikum ini, BIC ditetapkan sebagai kriteria utama untuk menentukan model akhir.
Implementasi Best Subset Selection
Prediktor numerik digunakan dalam bentuk aslinya, sedangkan prediktor kategorik direpresentasikan sebagai koefisien dummy.
# Formula regresi
formula_best_subset <- bwt ~
age + lwt + race + smoke + ptl + ht + ui + ftv
# Menyiapkan data regresi
data_best_subset <- data_train_regresi
# Memeriksa jumlah koefisien
matriks_best_subset <- model.matrix(
formula_best_subset,
data = data_best_subset
)
jumlah_koefisien <- ncol(matriks_best_subset) - 1
cat("Jumlah variabel asli:", 8, "\n")Jumlah variabel asli: 8
cat("Jumlah koefisien prediktor:", jumlah_koefisien, "\n")Jumlah koefisien prediktor: 9
# Pencarian exhaustive
model_best_subset <- leaps::regsubsets(
formula_best_subset,
data = data_best_subset,
nvmax = jumlah_koefisien,
method = "exhaustive",
nbest = 1
)
ringkasan_best_subset <- summary(
model_best_subset
)
# Menyusun hasil evaluasi
matriks_terpilih <- ringkasan_best_subset$which
nama_koefisien <- setdiff(
colnames(matriks_terpilih),
"(Intercept)"
)
hasil_best_subset <- tibble::tibble(
Ukuran_Subset = rowSums(
matriks_terpilih[, nama_koefisien, drop = FALSE]
),
RSS = ringkasan_best_subset$rss,
Adjusted_R2 = ringkasan_best_subset$adjr2,
Cp = ringkasan_best_subset$cp,
BIC = ringkasan_best_subset$bic,
Koefisien_Terpilih = apply(
matriks_terpilih[, nama_koefisien, drop = FALSE],
1,
function(x) {
paste(
nama_koefisien[x],
collapse = ", "
)
}
)
)
knitr::kable(
hasil_best_subset,
digits = 4,
caption = "Hasil Best Subset Selection berdasarkan ukuran subset."
)| Ukuran_Subset | RSS | Adjusted_R2 | Cp | BIC | Koefisien_Terpilih |
|---|---|---|---|---|---|
| 1 | 68354751 | 0.0484 | 28.8100 | 1.5367 | lwt |
| 2 | 64301618 | 0.0988 | 20.3853 | -2.6761 | lwt, htYa |
| 3 | 61241069 | 0.1358 | 14.5135 | -5.0226 | lwt, htYa, uiYa |
| 4 | 58740340 | 0.1654 | 10.0815 | -6.3007 | lwt, smokeYa, htYa, uiYa |
| 5 | 57014672 | 0.1844 | 7.6431 | -5.7859 | lwt, raceBlack, smokeYa, htYa, uiYa |
| 6 | 56212278 | 0.1903 | 7.5793 | -2.9089 | lwt, raceBlack, raceOther, smokeYa, htYa, uiYa |
| 7 | 55264988 | 0.1983 | 7.1428 | -0.4579 | age, lwt, raceBlack, raceOther, smokeYa, htYa, uiYa |
| 8 | 54826083 | 0.1991 | 8.0140 | 3.3554 | age, lwt, raceBlack, raceOther, smokeYa, ptl, htYa, uiYa |
| 9 | 54820652 | 0.1935 | 10.0000 | 8.3577 | age, lwt, raceBlack, raceOther, smokeYa, ptl, htYa, uiYa, ftv |
Terdapat delapan variabel asli, tetapi sembilan koefisien prediktor karena race memiliki tiga kategori dan menghasilkan dua dummy. Fungsi regsubsets() menyeleksi koefisien tersebut secara individual, sehingga salah satu dummy race dapat terpilih tanpa dummy lainnya.
Hasil menunjukkan bahwa RSS menurun seiring bertambahnya koefisien, tetapi kriteria pemilihan menghasilkan ukuran subset yang berbeda. BIC mencapai nilai minimum −6,3007 pada ukuran subset empat, Mallows’ Cp minimum 7,1428 pada ukuran tujuh, sedangkan Adjusted R² tertinggi 0,1991 diperoleh pada ukuran delapan.
Visualisasi Kriteria Pemilihan
data_plot_subset <- hasil_best_subset %>%
dplyr::select(
Ukuran_Subset,
Adjusted_R2,
Cp,
BIC
) %>%
tidyr::pivot_longer(
cols = c(Adjusted_R2, Cp, BIC),
names_to = "Kriteria",
values_to = "Nilai"
) %>%
dplyr::group_by(Kriteria) %>%
dplyr::mutate(
Terbaik = dplyr::if_else(
Kriteria == "Adjusted_R2",
Nilai == max(Nilai),
Nilai == min(Nilai)
)
) %>%
dplyr::ungroup() %>%
dplyr::mutate(
Kriteria = factor(
Kriteria,
levels = c("Adjusted_R2", "Cp", "BIC"),
labels = c(
"Adjusted R-squared",
"Mallows' Cp",
"BIC"
)
)
)
ggplot(
data_plot_subset,
aes(
x = Ukuran_Subset,
y = Nilai
)
) +
geom_line(
color = "#235789",
linewidth = 0.8
) +
geom_point(
aes(color = Terbaik),
size = 2.8
) +
geom_text(
data = function(x) {
dplyr::filter(x, Terbaik)
},
aes(label = sprintf("%.4f", Nilai)),
vjust = -1.1,
size = 3.3
) +
facet_wrap(
~ Kriteria,
nrow = 1,
scales = "free_y"
) +
scale_color_manual(
values = c(
"FALSE" = "#235789",
"TRUE" = "#D55E00"
)
) +
scale_x_continuous(
breaks = 1:jumlah_koefisien
) +
scale_y_continuous(
expand = expansion(mult = c(0.10, 0.20))
) +
labs(
x = "Ukuran subset (jumlah koefisien)",
y = "Nilai kriteria"
) +
theme_minimal(base_size = 11) +
theme(
legend.position = "none",
panel.grid.minor = element_blank()
)Ketiga kriteria mempunyai titik optimum yang berbeda. BIC memilih subset lebih kecil karena memberikan penalti kompleksitas yang lebih kuat pada ukuran sampel ini. Hal tersebut menunjukkan bahwa penambahan prediktor tidak selalu memberikan keuntungan yang sebanding dengan peningkatan kompleksitas model.
Pemilihan Model Akhir
Model akhir ditentukan menggunakan BIC minimum pada data latih.
# Menentukan ukuran subset berdasarkan BIC
ukuran_terbaik_bic <- hasil_best_subset$Ukuran_Subset[
which.min(hasil_best_subset$BIC)
]
# Mengambil koefisien model terpilih
koefisien_bic <- coef(
model_best_subset,
id = ukuran_terbaik_bic
)
tibble::tibble(
Koefisien = names(koefisien_bic),
Estimasi = as.numeric(koefisien_bic)
) %>%
knitr::kable(
digits = 4,
caption = "Koefisien model Best Subset berdasarkan BIC."
)| Koefisien | Estimasi |
|---|---|
| (Intercept) | 2320.2022 |
| lwt | 6.2992 |
| smokeYa | -264.9937 |
| htYa | -665.0854 |
| uiYa | -454.6350 |
Berdasarkan BIC, model akhir menggunakan lwt, smokeYa, htYa, dan uiYa. Koefisien lwt sebesar 6,2992 menunjukkan bahwa peningkatan berat badan ibu sebesar satu pon berkaitan dengan peningkatan berat lahir sekitar 6,30 gram, dengan prediktor lain dianggap tetap.
Sementara itu, smokeYa, htYa, dan uiYa mempunyai koefisien negatif masing-masing sebesar −264,99, −665,09, dan −454,64 gram dibandingkan kategori referensinya. Koefisien tersebut menggambarkan hubungan dalam model regresi dan tidak dapat langsung ditafsirkan sebagai pengaruh kausal.
Evaluasi Prediksi Model
Kemampuan prediksi model dievaluasi menggunakan RMSE dan MAE:
\[RMSE= \sqrt{ \frac{1}{n} \sum_{i=1}^{n}(y_i-\hat y_i)^2 }\]
\[MAE= \frac{1}{n} \sum_{i=1}^{n}|y_i-\hat y_i|\]
Kedua ukuran dinyatakan dalam gram. Semakin kecil RMSE dan MAE, semakin kecil kesalahan prediksi.
# Fungsi prediksi untuk regsubsets
prediksi_best_subset <- function(
model, id, data_baru, formula
) {
beta <- coef(model, id = id)
X <- model.matrix(
formula,
data = data_baru
)
as.numeric(
X[, names(beta), drop = FALSE] %*% beta
)
}
# Fungsi evaluasi
hitung_metrik_regresi <- function(aktual, prediksi) {
tibble::tibble(
RMSE = sqrt(mean((aktual - prediksi)^2)),
MAE = mean(abs(aktual - prediksi))
)
}
# Prediksi data latih dan data uji
pred_train <- prediksi_best_subset(
model_best_subset,
ukuran_terbaik_bic,
data_train_regresi,
formula_best_subset
)
pred_test <- prediksi_best_subset(
model_best_subset,
ukuran_terbaik_bic,
data_test_regresi,
formula_best_subset
)
# Prediksi baseline menggunakan rata-rata data latih
pred_baseline <- rep(
mean(data_train_regresi$bwt),
nrow(data_test_regresi)
)
# Ringkasan evaluasi
hasil_evaluasi_best_subset <- dplyr::bind_rows(
hitung_metrik_regresi(
data_train_regresi$bwt,
pred_train
) %>%
dplyr::mutate(
Model = "Best Subset",
Dataset = "Latih"
),
hitung_metrik_regresi(
data_test_regresi$bwt,
pred_test
) %>%
dplyr::mutate(
Model = "Best Subset",
Dataset = "Uji"
),
hitung_metrik_regresi(
data_test_regresi$bwt,
pred_baseline
) %>%
dplyr::mutate(
Model = "Baseline rata-rata",
Dataset = "Uji"
)
) %>%
dplyr::select(Model, Dataset, RMSE, MAE)
knitr::kable(
hasil_evaluasi_best_subset,
digits = 2,
caption = "Evaluasi model Best Subset dan baseline."
)| Model | Dataset | RMSE | MAE |
|---|---|---|---|
| Best Subset | Latih | 623.71 | 509.83 |
| Best Subset | Uji | 804.46 | 655.20 |
| Baseline rata-rata | Uji | 853.86 | 706.72 |
Hasil evaluasi menunjukkan bahwa RMSE model Best Subset meningkat dari 623,71 gram pada data latih menjadi 804,46 gram pada data uji. MAE data uji sebesar 655,20 gram. Sementara itu, baseline rata-rata menghasilkan RMSE 853,86 gram dan MAE 706,72 gram.
Dengan demikian, Best Subset menghasilkan RMSE sekitar 5,79% lebih rendah dan MAE sekitar 7,29% lebih rendah dibandingkan baseline pada data uji. Hasil ini menunjukkan adanya manfaat prediktif dari kombinasi prediktor terpilih, meskipun kesalahan prediksi masih cukup besar.
Pemilihan berdasarkan BIC dilakukan sepenuhnya pada data latih, sedangkan data uji hanya digunakan untuk mengevaluasi model yang telah ditetapkan.
3.2 Strategi Pencarian Subset: Genetic Algorithm dan Simulated Annealing
Pencarian exhaustive pada Best Subset mengevaluasi seluruh kombinasi koefisien yang memungkinkan. Ketika jumlah prediktor meningkat, banyaknya kombinasi berkembang secara eksponensial sehingga kebutuhan komputasi dapat menjadi sangat besar.
Dua alternatif strategi pencarian yang dibahas Sartono et al. (2024) adalah Genetic Algorithm (GA) dan Simulated Annealing (SA). Keduanya merupakan algoritma metaheuristik yang mencari subset melalui proses iteratif tanpa harus mengevaluasi seluruh kemungkinan kombinasi.
Penerapan pada Regresi dan Klasifikasi
Genetic Algorithm (GA) dan Simulated Annealing (SA) bukan metode yang hanya digunakan pada regresi atau klasifikasi. Keduanya merupakan strategi optimasi yang dapat digunakan untuk mencari kombinasi prediktor selama tersedia fungsi evaluasi yang sesuai.
Pada regresi, kandidat subset dapat dievaluasi menggunakan AIC, BIC, atau kesalahan prediksi seperti RMSE pada validasi silang. Pada klasifikasi, kandidat subset dapat dievaluasi menggunakan AIC atau BIC dari model logistik, maupun ukuran performa klasifikasi seperti AUC atau log-loss yang dihitung melalui validasi silang.
Apabila tujuan pencarian adalah meminimumkan fungsi objektif \(J(S)\), formulasi umumnya adalah:
\[S^*=\arg\min_{S\subseteq\{1,\ldots,p\}}J(S)\]
Fungsi objektif tersebut bergantung pada tujuan pemodelan. Untuk metrik yang perlu dimaksimumkan seperti AUC, fungsi pencarian dapat didefinisikan sebagai \(J(S)=1-AUC(S)\).
Prediktor numerik dapat digunakan sesuai representasinya dalam model, sedangkan prediktor kategorik dapat diwakili oleh variabel dummy. Jika unit seleksi merupakan variabel asli, seluruh dummy dari prediktor yang sama dipilih atau dikeluarkan bersama-sama.
Dengan demikian, GA dan SA menentukan bagaimana subset dicari, sedangkan model serta fungsi evaluasi menentukan bagaimana kualitas subset dinilai. Pada praktikum ini, implementasi penuh GA dan SA tidak dilakukan karena pencarian exhaustive pada delapan prediktor asli masih memungkinkan secara komputasi.
Subset direpresentasikan menggunakan vektor biner:
\[\mathbf{v}=(v_1,v_2,\ldots,v_p)\]
dengan \(v_j=1\) jika prediktor dipilih dan \(v_j=0\) jika tidak dipilih. Sebagai contoh, vektor \((1,0,1,0)\) menunjukkan pemilihan prediktor pertama dan ketiga.
Setiap subset dapat dievaluasi menggunakan Akaike Information Criterion (AIC):
\[AIC=-2\ln L(\hat{\boldsymbol{\theta}})+2k\]
dengan \(L(\hat{\boldsymbol{\theta}})\) merupakan likelihood maksimum dan \(k\) jumlah parameter yang diestimasi. Tujuan pencariannya adalah:
\[\mathbf{v}^{*} = \arg\min_{\mathbf{v}\in\{0,1\}^{p}} AIC(\mathbf{v})\]
Genetic Algorithm mengelola populasi kandidat subset. Pada setiap generasi, individu dengan nilai kriteria yang lebih baik mempunyai peluang lebih besar untuk dipilih sebagai induk. Kandidat baru dibentuk melalui crossover dan mutasi. Prosedur ini diulangi untuk mengeksplorasi kombinasi prediktor yang berbeda.
Simulated Annealing mengelola satu solusi aktif dan membentuk solusi tetangga melalui perubahan elemen vektor biner. Solusi dengan AIC lebih rendah diterima, sedangkan solusi yang lebih buruk masih dapat diterima dengan probabilitas:
\[P(\text{terima})= \min\left\{ 1, \exp\left(-\frac{\Delta AIC}{T}\right) \right\}\]
dengan:
\[\Delta AIC=AIC(\mathbf{w})-AIC(\mathbf{v})\]
\(T\) adalah temperatur yang diturunkan secara bertahap selama iterasi. Penerimaan solusi yang lebih buruk pada temperatur tinggi memungkinkan algoritma keluar dari optimum lokal.
| Aspek | Genetic Algorithm | Simulated Annealing |
|---|---|---|
| Solusi yang dikelola | Populasi subset | Satu solusi aktif |
| Pembentukan kandidat | Crossover dan mutasi | Perubahan solusi tetangga |
| Mekanisme pencarian | Seleksi antargenerasi | Penerimaan berdasarkan temperatur |
| Hasil | Subset terbaik yang ditemukan | Subset terbaik yang ditemukan |
Kedua algoritma tidak menjamin ditemukannya optimum global pada setiap proses. Hasilnya dapat dipengaruhi oleh inisialisasi dan parameter pencarian.
Pada data birthwt, jumlah kandidat variabel asli hanya delapan, sehingga pencarian exhaustive masih memungkinkan. Oleh karena itu, GA dan SA diperkenalkan untuk memahami alternatif strategi pencarian, tanpa memerlukan implementasi optimasi tersendiri pada praktikum ini.
Sebagai ilustrasi perbedaan kriteria, model Best Subset berdasarkan BIC dapat dibandingkan dengan model lengkap menggunakan AIC.
# Model hasil seleksi BIC
model_bic_lm <- stats::lm(
bwt ~ lwt + smoke + ht + ui,
data = data_train_regresi
)
# Model lengkap
model_lengkap_lm <- stats::lm(
formula_best_subset,
data = data_train_regresi
)
tibble::tibble(
Model = c("Subset BIC", "Model lengkap"),
Jumlah_Variabel = c(4, 8),
AIC = c(
AIC(model_bic_lm),
AIC(model_lengkap_lm)
)
) %>%
knitr::kable(
digits = 4,
caption = "Perbandingan AIC model subset BIC dan model lengkap."
)| Model | Jumlah_Variabel | AIC |
|---|---|---|
| Subset BIC | 4 | 2384.094 |
| Model lengkap | 8 | 2383.666 |
Model lengkap menghasilkan AIC sebesar 2383,666, sedikit lebih rendah daripada subset BIC dengan AIC sebesar 2384,094. Selisih tersebut memperlihatkan bahwa pilihan model dapat berbeda ketika kriteria evaluasi berubah. Hasil ini bukan keluaran optimasi GA atau SA, melainkan ilustrasi penggunaan AIC dalam evaluasi kandidat subset.
3.3 Boruta
Boruta merupakan metode seleksi variabel berbasis Random Forest yang bertujuan mengidentifikasi seluruh prediktor yang relevan terhadap respons (all-relevant feature selection). Berbeda dari Best Subset Selection yang mencari kombinasi prediktor berdasarkan kriteria kecocokan dan kompleksitas model, Boruta menilai apakah kepentingan setiap prediktor asli secara konsisten lebih tinggi daripada kepentingan prediktor acak.
Boruta dapat diterapkan pada klasifikasi maupun regresi. Perbedaan keduanya terletak pada tipe respons dan cara Random Forest mengukur kesalahan prediksi. Prosedur pembentukan shadow features dan pengambilan keputusan seleksi tetap sama.
Konsep Dasar dan Formulasi Matematis
Misalkan terdapat \(p\) prediktor asli:
\[\mathbf{X}=(X_1,X_2,\ldots,X_p)\]
Boruta membentuk prediktor bayangan (shadow features) dengan mengacak urutan nilai setiap prediktor asli antarobservasi:
\[\widetilde{\mathbf{X}}= (\widetilde X_1,\widetilde X_2,\ldots,\widetilde X_p)\]
Prediktor bayangan mempertahankan distribusi nilai prediktor asal, tetapi hubungan observasionalnya dengan respons dihilangkan melalui pengacakan.
Pada setiap iterasi \(t\), model Random Forest dibentuk menggunakan prediktor asli dan bayangan. Kepentingan setiap prediktor dapat diperkirakan melalui permutation importance, yaitu perubahan kesalahan prediksi setelah nilai prediktor diacak.
Secara konseptual, kepentingan permutasi mentah dapat dituliskan sebagai:
\[\Delta_j^{(t)} = L_{\mathrm{perm},j}^{(t)} - L_{\mathrm{awal}}^{(t)}\]
dengan \(L_{\mathrm{awal}}^{(t)}\) merupakan kesalahan prediksi sebelum permutasi, sedangkan \(L_{\mathrm{perm},j}^{(t)}\) merupakan kesalahan setelah prediktor ke-\(j\) diacak. Pengukuran umumnya dilakukan pada observasi out-of-bag (OOB) Random Forest.
Nilai \(\Delta_j^{(t)}\) yang lebih besar menunjukkan bahwa pengacakan prediktor menyebabkan peningkatan kesalahan prediksi yang lebih besar. Namun, implementasi Boruta dapat menggunakan skor kepentingan yang telah dinormalisasi oleh importance adapter, sehingga skor meanImp tidak harus memiliki satuan yang sama dengan kesalahan prediksi mentah.
Misalkan \(I_j^{(t)}\) adalah skor kepentingan prediktor asli ke-\(j\) yang dihasilkan oleh adapter. Kepentingan prediktor bayangan tertinggi didefinisikan sebagai:
\[I_{\mathrm{shadow,max}}^{(t)} = \max_{k=1,\ldots,p} I_{\widetilde X_k}^{(t)}\]
Prediktor memperoleh satu kemenangan (hit) ketika kepentingannya melebihi kepentingan bayangan tertinggi:
\[W_j^{(t)} = \begin{cases} 1, & I_j^{(t)}>I_{\mathrm{shadow,max}}^{(t)}\\ 0, & \text{lainnya} \end{cases}\]
Jumlah kemenangan selama \(T\) iterasi dinyatakan sebagai:
\[H_j=\sum_{t=1}^{T}W_j^{(t)}\]
Boruta menguji apakah frekuensi kemenangan secara signifikan lebih tinggi atau lebih rendah daripada kondisi pembanding acak. Pengujian didasarkan pada distribusi binomial dengan probabilitas acuan 0,5 dan dapat disertai koreksi pengujian berganda.
Keputusan seleksi terdiri atas tiga kategori:
| Keputusan | Makna |
|---|---|
| Confirmed | Prediktor dinyatakan relevan berdasarkan pengujian Boruta |
| Tentative | Belum diperoleh bukti yang cukup untuk menetapkan keputusan |
| Rejected | Prediktor tidak dinyatakan relevan berdasarkan prosedur Boruta |
Prinsip tersebut berlaku untuk klasifikasi dan regresi. Perbedaannya terdapat pada fungsi kesalahan yang digunakan dalam menghitung kepentingan prediktor.
Ilustrasi algoritma Boruta dari proyek BorutaPy oleh Daniel Homola.
3.3.1 Boruta untuk Klasifikasi
Pada klasifikasi, Random Forest memprediksi kategori respons. Salah satu ukuran kesalahan yang dapat digunakan dalam perhitungan kepentingan permutasi adalah proporsi salah klasifikasi:
\[L_{\mathrm{klasifikasi}} = \frac{1}{n_{\mathrm{OOB}}} \sum_{i=1}^{n_{\mathrm{OOB}}} \mathbb{I}(y_i\neq\hat y_i)\]
dengan \(\mathbb{I}(\cdot)\) merupakan fungsi indikator bernilai satu jika prediksi salah dan nol jika prediksi benar.
Pengacakan prediktor yang relevan cenderung meningkatkan kesalahan klasifikasi. Perubahan kesalahan tersebut menjadi dasar pengukuran kepentingan, yang selanjutnya dibandingkan dengan kepentingan shadow features.
Pada dataset birthwt, Boruta untuk klasifikasi menggunakan:
- Respons:
low(Rendah dan Tidak rendah). - Prediktor:
age,lwt,race,smoke,ptl,ht,ui, danftv. - Data:
data_train_klasifikasi.
Peubah bwt dikeluarkan dari prediktor karena digunakan untuk mendefinisikan status low.
Implementasi Boruta Klasifikasi
# Menjalankan Boruta untuk klasifikasi
set.seed(2026)
model_boruta_klasifikasi <- Boruta::Boruta(
low ~ .,
data = as.data.frame(data_train_klasifikasi),
maxRuns = 100,
pValue = 0.01,
mcAdj = TRUE,
holdHistory = TRUE,
doTrace = 0
)
# Mengambil statistik kepentingan dan keputusan
hasil_boruta_klasifikasi <- Boruta::attStats(
model_boruta_klasifikasi
) %>%
tibble::rownames_to_column("Prediktor") %>%
dplyr::arrange(dplyr::desc(meanImp))
knitr::kable(
hasil_boruta_klasifikasi %>%
dplyr::select(
Prediktor,
meanImp,
medianImp,
normHits,
decision
),
digits = 4,
col.names = c(
"Prediktor",
"Rata-rata Importance",
"Median Importance",
"Proporsi Hit",
"Keputusan"
),
caption = "Hasil seleksi Boruta untuk klasifikasi."
)| Prediktor | Rata-rata Importance | Median Importance | Proporsi Hit | Keputusan |
|---|---|---|---|---|
| ptl | 0.4093 | 0.3971 | 0.9759 | Confirmed |
| ht | 0.1992 | 0.1864 | 0.6747 | Confirmed |
| lwt | 0.1872 | 0.1648 | 0.6867 | Confirmed |
| ftv | 0.0906 | 0.0821 | 0.2651 | Rejected |
| age | 0.0426 | 0.0372 | 0.0723 | Rejected |
| smoke | 0.0400 | 0.0337 | 0.0964 | Rejected |
| ui | 0.0037 | 0.0032 | 0.0000 | Rejected |
| race | -0.1107 | -0.1033 | 0.0000 | Rejected |
Kolom meanImp dan medianImp menunjukkan ringkasan kepentingan prediktor selama iterasi, normHits menunjukkan proporsi kemenangan terhadap pembanding acak, sedangkan decision menunjukkan keputusan akhir seleksi.
Visualisasi Boruta Klasifikasi
plot(
model_boruta_klasifikasi,
sort = TRUE,
las = 2,
cex.axis = 0.85,
xlab = "",
ylab = "Kepentingan Prediktor",
main = "Boruta - Klasifikasi"
)Grafik menampilkan distribusi kepentingan prediktor asli dan pembanding shadow. Warna hijau menunjukkan Confirmed, kuning menunjukkan Tentative, merah menunjukkan Rejected, sedangkan biru menunjukkan pembanding acak.
Mengambil Prediktor Terpilih
# Prediktor yang memperoleh keputusan Confirmed
prediktor_boruta_klasifikasi <-
Boruta::getSelectedAttributes(
model_boruta_klasifikasi,
withTentative = FALSE
)
# Ringkasan keputusan
hasil_boruta_klasifikasi %>%
dplyr::group_by(decision) %>%
dplyr::summarise(
Jumlah = dplyr::n(),
Prediktor = paste(Prediktor, collapse = ", "),
.groups = "drop"
) %>%
knitr::kable(
caption = "Ringkasan keputusan Boruta klasifikasi."
)| decision | Jumlah | Prediktor |
|---|---|---|
| Confirmed | 3 | ptl, ht, lwt |
| Rejected | 5 | ftv, age, smoke, ui, race |
Interpretasi Hasil Klasifikasi
Berdasarkan hasil seleksi, Boruta mengonfirmasi tiga prediktor, yaitu ptl, ht, dan lwt. Lima prediktor lainnya, yaitu ftv, age, smoke, ui, dan race, memperoleh keputusan Rejected. Tidak terdapat prediktor berstatus Tentative.
Prediktor ptl memiliki rata-rata kepentingan tertinggi sebesar 0,4093 dengan proporsi hit sebesar 0,9759. Hal ini menunjukkan bahwa ptl secara konsisten mempunyai kepentingan lebih tinggi dibandingkan pembanding acak. Selanjutnya, ht dan lwt memiliki rata-rata kepentingan masing-masing sebesar 0,1992 dan 0,1872.
Hasil ini sejalan dengan beberapa metode Filtering yang menempatkan ptl dan lwt pada peringkat tinggi. Namun, smoke yang menunjukkan hubungan signifikan berdasarkan Chi-Square justru memperoleh keputusan Rejected pada Boruta. Perbedaan tersebut menunjukkan bahwa hubungan marginal dengan respons tidak selalu menghasilkan kepentingan yang memadai ketika prediktor dievaluasi bersama prediktor lainnya dalam Random Forest.
Dengan demikian, ptl, ht, dan lwt merupakan prediktor yang dinyatakan relevan untuk klasifikasi berat lahir rendah menurut prosedur Boruta pada data latih.
3.3.2 Boruta untuk Regresi
Pada regresi, Random Forest digunakan untuk memprediksi respons numerik. Prinsip Boruta tetap sama, tetapi kepentingan prediktor dinilai menggunakan perubahan kesalahan prediksi numerik.
Salah satu ukuran kesalahan yang digunakan pada Random Forest regresi adalah Mean Squared Error (MSE):
\[L_{\mathrm{regresi}} = \frac{1}{n_{\mathrm{OOB}}} \sum_{i=1}^{n_{\mathrm{OOB}}} (y_i-\hat y_i)^2\]
Pengacakan prediktor yang relevan cenderung memperbesar kesalahan prediksi. Perubahan kesalahan tersebut digunakan untuk memperoleh ukuran kepentingan prediktor, yang kemudian dibandingkan dengan kepentingan shadow features melalui prosedur Boruta yang sama seperti pada klasifikasi.
Pada dataset birthwt, Boruta untuk regresi menggunakan:
- Respons:
bwt(berat lahir bayi dalam gram). - Prediktor:
age,lwt,race,smoke,ptl,ht,ui, danftv. - Data:
data_train_regresi.
Peubah low tidak digunakan sebagai prediktor karena dibentuk langsung dari bwt.
Implementasi Boruta Regresi
# Menjalankan Boruta untuk regresi
set.seed(2026)
model_boruta_regresi <- Boruta::Boruta(
bwt ~ .,
data = as.data.frame(data_train_regresi),
maxRuns = 100,
pValue = 0.01,
mcAdj = TRUE,
holdHistory = TRUE,
doTrace = 0
)
# Mengambil hasil seleksi
hasil_boruta_regresi <- Boruta::attStats(
model_boruta_regresi
) %>%
tibble::rownames_to_column("Prediktor") %>%
dplyr::arrange(dplyr::desc(meanImp))
knitr::kable(
hasil_boruta_regresi %>%
dplyr::select(
Prediktor,
meanImp,
medianImp,
normHits,
decision
),
digits = 4,
col.names = c(
"Prediktor",
"Rata-rata Importance",
"Median Importance",
"Proporsi Hit",
"Keputusan"
),
caption = "Hasil seleksi Boruta untuk regresi."
)| Prediktor | Rata-rata Importance | Median Importance | Proporsi Hit | Keputusan |
|---|---|---|---|---|
| lwt | 0.3366 | 0.3360 | 0.9293 | Confirmed |
| ptl | 0.2795 | 0.2769 | 0.8283 | Confirmed |
| smoke | 0.2603 | 0.2654 | 0.8182 | Confirmed |
| ui | 0.2424 | 0.2537 | 0.7475 | Confirmed |
| race | 0.1243 | 0.1207 | 0.4646 | Tentative |
| ftv | 0.0480 | 0.0456 | 0.0505 | Rejected |
| ht | 0.0102 | -0.0021 | 0.0000 | Rejected |
| age | -0.0215 | -0.0091 | 0.0000 | Rejected |
Visualisasi Boruta Regresi
plot(
model_boruta_regresi,
sort = TRUE,
las = 2,
cex.axis = 0.85,
xlab = "",
ylab = "Kepentingan Prediktor",
main = "Boruta - Regresi"
)Mengambil Prediktor Terpilih
# Prediktor yang memperoleh keputusan Confirmed
prediktor_boruta_regresi <-
Boruta::getSelectedAttributes(
model_boruta_regresi,
withTentative = FALSE
)
# Ringkasan keputusan
hasil_boruta_regresi %>%
dplyr::group_by(decision) %>%
dplyr::summarise(
Jumlah = dplyr::n(),
Prediktor = paste(Prediktor, collapse = ", "),
.groups = "drop"
) %>%
knitr::kable(
caption = "Ringkasan keputusan Boruta regresi."
)| decision | Jumlah | Prediktor |
|---|---|---|
| Tentative | 1 | race |
| Confirmed | 4 | lwt, ptl, smoke, ui |
| Rejected | 3 | ftv, ht, age |
Hasil Boruta untuk regresi menunjukkan bahwa empat prediktor memperoleh keputusan Confirmed, yaitu lwt, ptl, smoke, dan ui. Prediktor lwt memiliki rata-rata kepentingan tertinggi sebesar 0,3366 dengan proporsi hit sebesar 0,9293, diikuti ptl (0,2795), smoke (0,2603), dan ui (0,2424). Keempat prediktor tersebut menunjukkan kepentingan yang secara konsisten lebih tinggi dibandingkan prediktor bayangan berdasarkan prosedur Boruta.
Prediktor race memperoleh keputusan Tentative, sehingga bukti dari proses seleksi yang dijalankan belum cukup untuk menetapkan status relevansinya secara pasti. Sementara itu, ftv, ht, dan age memperoleh keputusan Rejected karena tidak memenuhi kriteria konfirmasi relevansi Boruta.
Hasil tersebut menggambarkan relevansi prediktor terhadap berat lahir numerik (bwt) berdasarkan kepentingan dalam model Random Forest regresi. Keputusan seleksi tidak menunjukkan arah hubungan maupun pengaruh kausal prediktor terhadap berat lahir. Perbedaannya dengan hasil Boruta klasifikasi dibahas pada subbagian berikutnya.
3.3.3 Perbandingan Hasil Boruta Klasifikasi dan Regresi
Walaupun menggunakan delapan kandidat prediktor dan observasi latih yang sama, klasifikasi dan regresi menyelesaikan persoalan prediksi berbeda. Oleh karena itu, Boruta tidak harus menghasilkan keputusan seleksi yang identik.
Perbandingan dilakukan berdasarkan status keputusan seleksi, bukan dengan membandingkan nilai importance secara langsung karena skala serta dasar penghitungan kepentingan dapat berbeda antara kedua tugas.
# Menggabungkan keputusan klasifikasi dan regresi
perbandingan_boruta <-
hasil_boruta_klasifikasi %>%
dplyr::select(
Prediktor,
Klasifikasi = decision
) %>%
dplyr::left_join(
hasil_boruta_regresi %>%
dplyr::select(
Prediktor,
Regresi = decision
),
by = "Prediktor"
) %>%
dplyr::mutate(
Keterangan = dplyr::case_when(
Klasifikasi == "Confirmed" &
Regresi == "Confirmed" ~ "Relevan pada keduanya",
Klasifikasi == "Rejected" &
Regresi == "Rejected" ~ "Ditolak pada keduanya",
TRUE ~ "Keputusan berbeda atau belum pasti"
)
)
knitr::kable(
perbandingan_boruta,
caption = "Perbandingan keputusan seleksi Boruta untuk klasifikasi dan regresi."
)| Prediktor | Klasifikasi | Regresi | Keterangan |
|---|---|---|---|
| ptl | Confirmed | Confirmed | Relevan pada keduanya |
| ht | Confirmed | Rejected | Keputusan berbeda atau belum pasti |
| lwt | Confirmed | Confirmed | Relevan pada keduanya |
| ftv | Rejected | Rejected | Ditolak pada keduanya |
| age | Rejected | Rejected | Ditolak pada keduanya |
| smoke | Rejected | Confirmed | Keputusan berbeda atau belum pasti |
| ui | Rejected | Confirmed | Keputusan berbeda atau belum pasti |
| race | Rejected | Tentative | Keputusan berbeda atau belum pasti |
# Ringkasan jumlah prediktor terpilih
tibble::tibble(
Pemodelan = c("Klasifikasi", "Regresi"),
Jumlah_Confirmed = c(
length(prediktor_boruta_klasifikasi),
length(prediktor_boruta_regresi)
),
Prediktor_Confirmed = c(
paste(
prediktor_boruta_klasifikasi,
collapse = ", "
),
paste(
prediktor_boruta_regresi,
collapse = ", "
)
)
) %>%
knitr::kable(
caption = "Ringkasan prediktor terpilih pada kedua tugas pemodelan."
)| Pemodelan | Jumlah_Confirmed | Prediktor_Confirmed |
|---|---|---|
| Klasifikasi | 3 | lwt, ptl, ht |
| Regresi | 4 | lwt, smoke, ptl, ui |
Perbandingan ini digunakan untuk mengidentifikasi prediktor yang dinyatakan relevan pada kedua tugas, hanya pada salah satu tugas, atau ditolak pada keduanya.
Prediktor yang terpilih pada kedua tugas menunjukkan konsistensi keputusan menurut prosedur Boruta untuk dua bentuk respons yang berkaitan. Sebaliknya, perbedaan keputusan tidak langsung menunjukkan bahwa salah satu hasil seleksi keliru, karena masing-masing mengevaluasi relevansi terhadap respons dan fungsi kesalahan yang berbeda.
Hasil Boruta merupakan keputusan seleksi prediktor, bukan ukuran akhir kemampuan prediksi. Evaluasi kemampuan generalisasi memerlukan pembentukan model menggunakan prediktor terpilih dan pengujian pada data yang tidak digunakan selama proses seleksi.
Interpretasi Perbandingan Boruta Klasifikasi dan Regresi
Perbandingan hasil Boruta menunjukkan bahwa ptl dan lwt memperoleh keputusan Confirmed pada kedua tugas pemodelan. Hal ini menunjukkan konsistensi relevansi kedua prediktor, baik ketika respons dinyatakan sebagai status berat lahir rendah maupun sebagai berat lahir numerik. Sebaliknya, age dan ftv memperoleh keputusan Rejected pada kedua tugas.
Perbedaan keputusan ditemukan pada ht, smoke, dan ui. Prediktor ht dinyatakan Confirmed pada klasifikasi, tetapi Rejected pada regresi. Sebaliknya, smoke dan ui memperoleh keputusan Confirmed pada regresi, tetapi Rejected pada klasifikasi. Sementara itu, race memperoleh keputusan Rejected pada klasifikasi dan Tentative pada regresi sehingga relevansinya untuk pemodelan regresi belum dapat dipastikan berdasarkan proses seleksi yang dijalankan.
Perbedaan tersebut berkaitan dengan tujuan pemodelan. Pada klasifikasi, respons low hanya membedakan bayi dengan berat lahir kurang dari 2.500 gram dan bayi dengan berat lahir tidak rendah. Informasi mengenai variasi berat lahir dalam setiap kategori tidak lagi dipertahankan. Sebaliknya, regresi menggunakan bwt sebagai respons numerik sehingga model mempelajari variasi berat lahir dalam satuan gram.
Meskipun low dibentuk dari bwt, kedua tugas tidak memiliki fungsi kesalahan yang sama. Random Forest klasifikasi mengevaluasi kemampuan membedakan kelas respons, sedangkan Random Forest regresi mengevaluasi ketepatan prediksi nilai numerik. Akibatnya, kontribusi prediktor terhadap kesalahan prediksi dapat berbeda, termasuk ketika observasi dan kandidat prediktor yang digunakan sama.
Hasil ini memperlihatkan bahwa relevansi prediktor bersifat bergantung pada tujuan pemodelan dan ukuran kepentingan yang digunakan. Keputusan Rejected tidak dapat ditafsirkan sebagai bukti bahwa suatu prediktor sama sekali tidak memiliki hubungan dengan respons. Demikian pula, prediktor Confirmed tidak selalu diperlukan dalam model prediksi paling sederhana.
Dengan demikian, Boruta dapat diterapkan pada klasifikasi dan regresi menggunakan prinsip seleksi yang sama, tetapi keputusan akhir dapat berbeda karena respons dan fungsi kesalahan model berbeda. Perbandingan nilai kepentingan secara langsung antarkedua tugas juga tidak dilakukan karena skala dan dasar pengukurannya tidak harus identik.
Unlike Filtering, Wrapper methods evaluate candidate predictors by fitting models. Selection is performed over combinations of predictors, so each predictor’s contribution is assessed in the context of the other predictors included in the model.
In this section, Best Subset Selection is applied to infant birth-weight regression using bwt as the response.
Using Wrapper Methods with Different Variable Types
Wrapper methods assess predictor relevance through model fitting. Consequently, their applicability depends not only on predictor types but also on the underlying model and the evaluation function.
Unlike certain Filtering methods that require specific combinations of variable types, Wrapper approaches can generally be used for both regression and classification, provided the model supports the response type.
Numerical and categorical predictors can also be used together. However, predictors must be represented appropriately for the model, for example by creating dummy variables for linear or logistic regression.
Applicability of Wrapper Methods
| Method | Numerical Predictors | Categorical Predictors | Regression | Classification |
|---|---|---|---|---|
| Best Subset Selection | Can be used directly | Can be represented by dummies or selected as factor groups | Linear regression | Can be applied through classification models such as logistic regression |
| Genetic Algorithm | Can be used | Can be used; categories are represented as required by the model | Requires a regression evaluation function | Requires a classification evaluation function |
| Simulated Annealing | Can be used | Can be used; categories are represented as required by the model | Requires a regression evaluation function | Requires a classification evaluation function |
| Boruta | Can be used | Can be used as factors | Uses predictor importance in regression models | Uses predictor importance in classification models |
Best Subset Selection, Genetic Algorithm, and Simulated Annealing differ in their subset search strategies. The response type is handled by the model used to evaluate each subset.
Boruta uses a different mechanism: rather than searching for a subset by optimizing a single global objective such as AIC, it compares each predictor’s importance against randomized controls using Random Forest.
Best Subset Selection for Regression and Classification
Best Subset Selection is not limited to linear regression. The principle of searching over all predictor combinations can also be applied to other models, including logistic regression for binary classification.
In linear regression, each subset \(S\) defines a model:
\[Y_i=\beta_0+\sum_{j\in S}\beta_jX_{ij}+\varepsilon_i\]
Models can be chosen using criteria such as adjusted R-squared, Mallows’ \(C_p\), AIC, or BIC.
In binary classification, each subset can define a logistic regression model:
\[\log\left(\frac{\pi_i}{1-\pi_i}\right) = \beta_0+\sum_{j\in S}\beta_jX_{ij}\]
where \(\pi_i=P(Y_i=1\mid\mathbf{x}_i)\).
Criteria such as AIC and BIC can compare logistic models with different subsets:
\[AIC_S=-2\ell_S+2k_S\]
\[BIC_S=-2\ell_S+k_S\ln(n)\]
Here, \(\ell_S\) is the maximized log-likelihood of subset model \(S\) and \(k_S\) is the number of estimated parameters.
Thus, Best Subset Selection remains a search over predictor combinations, but model estimation and evaluation criteria are adapted to the response type.
Note that leaps::regsubsets(), used in the preceding practical example, is designed for subset searches in linear regression. It does not perform logistic-regression Best Subset Selection directly. Classification requires a search procedure that evaluates classification models, for example glm() with the binomial family.
Selecting Categorical Predictors as Groups
A categorical predictor with more than two categories can generate several dummy coefficients.
For example, race has three categories and therefore produces two coefficients with White as the reference category:
\[\beta_{\mathrm{Black}}X_{\mathrm{Black}} + \beta_{\mathrm{Other}}X_{\mathrm{Other}}\]
If the subset search treats every model-matrix column separately, one dummy may be selected while the other is omitted.
If, instead, the original variable is the unit of selection, both dummies must be included or excluded together as one group.
This distinction matters when interpreting the number of selected predictors: four selected coefficients do not necessarily correspond to four original variables.
The preceding Best Subset implementation uses regsubsets() to select model-matrix coefficients individually. Boruta and Group LASSO, by contrast, illustrate methods that preserve the structure of original predictors during selection.
3.1 Best Subset Selection
Best Subset Selection searches for the best predictor combination according to a model-evaluation criterion. For \(p\) candidate coefficients, there are \(2^p\) possible subsets, including the model without predictors.
A linear regression model for subset \(S\) is:
\[Y_i=\beta_0+\sum_{j\in S}\beta_jX_{ij}+\varepsilon_i\]
For each subset size, the model with the smallest Residual Sum of Squares (RSS) is chosen:
\[RSS=\sum_{i=1}^{n}(Y_i-\hat Y_i)^2\]
RSS tends to decrease as predictors are added. Selecting the best subset size therefore requires criteria that account for model complexity.
Reference: James et al. (2021), An Introduction to Statistical Learning, Figure 6.1.
The figure represents candidate models as points, while the red curve identifies the model with the smallest RSS for each subset size. It illustrates the logic of exhaustive search more clearly than a table of coefficient combinations alone.
The criteria used in this practical are:
Adjusted R-squared
\[R_{\mathrm{adj}}^2= 1- \frac{RSS/(n-k-1)} {TSS/(n-1)}\]
where \(k\) is the number of predictor coefficients excluding the intercept.
Mallows’ \(C_p\)
\[C_p= \frac{RSS}{\hat{\sigma}_{\mathrm{full}}^2} -n+2(k+1)\]
where \(\hat{\sigma}_{\mathrm{full}}^2\) is the error-variance estimate from the full model.
Bayesian Information Criterion (BIC)
\[BIC= n\ln\left(\frac{RSS}{n}\right) +(k+1)\ln(n)\]
This BIC expression omits a constant shared by models fitted to the same response and sample. regsubsets() reports a relative form of BIC, so its absolute values need not match BIC() applied to an lm object; choosing the minimum nevertheless remains appropriate.
Models are selected by maximizing adjusted R-squared or minimizing Cp or BIC. In this practical, BIC is designated the primary criterion for choosing the final model.
Implementing Best Subset Selection
Numerical predictors are used in their original form, while categorical predictors are represented by dummy coefficients.
# Regression formula
formula_best_subset <- bwt ~
age + lwt + race + smoke + ptl + ht + ui + ftv
# Prepare regression data
data_best_subset <- data_train_regresi
# Check the number of coefficients
matriks_best_subset <- model.matrix(
formula_best_subset,
data = data_best_subset
)
jumlah_koefisien <- ncol(matriks_best_subset) - 1
cat("Number of original variables:", 8, "\n")Number of original variables: 8
cat("Number of predictor coefficients:", jumlah_koefisien, "\n")Number of predictor coefficients: 9
# Exhaustive search
model_best_subset <- leaps::regsubsets(
formula_best_subset,
data = data_best_subset,
nvmax = jumlah_koefisien,
method = "exhaustive",
nbest = 1
)
ringkasan_best_subset <- summary(
model_best_subset
)
# Compile evaluation results
matriks_terpilih <- ringkasan_best_subset$which
nama_koefisien <- setdiff(
colnames(matriks_terpilih),
"(Intercept)"
)
hasil_best_subset <- tibble::tibble(
Subset_Size = rowSums(
matriks_terpilih[, nama_koefisien, drop = FALSE]
),
RSS = ringkasan_best_subset$rss,
Adjusted_R2 = ringkasan_best_subset$adjr2,
Cp = ringkasan_best_subset$cp,
BIC = ringkasan_best_subset$bic,
Selected_Coefficients = apply(
matriks_terpilih[, nama_koefisien, drop = FALSE],
1,
function(x) {
paste(
nama_koefisien[x],
collapse = ", "
)
}
)
)
knitr::kable(
hasil_best_subset,
digits = 4,
caption = "Best Subset Selection results by subset size."
)| Subset_Size | RSS | Adjusted_R2 | Cp | BIC | Selected_Coefficients |
|---|---|---|---|---|---|
| 1 | 68354751 | 0.0484 | 28.8100 | 1.5367 | lwt |
| 2 | 64301618 | 0.0988 | 20.3853 | -2.6761 | lwt, htYes |
| 3 | 61241069 | 0.1358 | 14.5135 | -5.0226 | lwt, htYes, uiYes |
| 4 | 58740340 | 0.1654 | 10.0815 | -6.3007 | lwt, smokeYes, htYes, uiYes |
| 5 | 57014672 | 0.1844 | 7.6431 | -5.7859 | lwt, raceBlack, smokeYes, htYes, uiYes |
| 6 | 56212278 | 0.1903 | 7.5793 | -2.9089 | lwt, raceBlack, raceOther, smokeYes, htYes, uiYes |
| 7 | 55264988 | 0.1983 | 7.1428 | -0.4579 | age, lwt, raceBlack, raceOther, smokeYes, htYes, uiYes |
| 8 | 54826083 | 0.1991 | 8.0140 | 3.3554 | age, lwt, raceBlack, raceOther, smokeYes, ptl, htYes, uiYes |
| 9 | 54820652 | 0.1935 | 10.0000 | 8.3577 | age, lwt, raceBlack, raceOther, smokeYes, ptl, htYes, uiYes, ftv |
There are eight original variables but nine predictor coefficients, because race has three categories and produces two dummy variables. regsubsets() selects coefficients individually, so one race dummy may be selected without the other.
RSS decreases as coefficients are added, but the selection criteria favor different subset sizes. BIC reaches its minimum of −6.3007 with four coefficients, Mallows’ Cp reaches its minimum of 7.1428 with seven, and the highest adjusted R² of 0.1991 occurs with eight coefficients.
Visualizing the Selection Criteria
data_plot_subset <- hasil_best_subset %>%
dplyr::select(
Subset_Size,
Adjusted_R2,
Cp,
BIC
) %>%
tidyr::pivot_longer(
cols = c(Adjusted_R2, Cp, BIC),
names_to = "Criterion",
values_to = "Value"
) %>%
dplyr::group_by(Criterion) %>%
dplyr::mutate(
Optimal = dplyr::if_else(
Criterion == "Adjusted_R2",
Value == max(Value),
Value == min(Value)
)
) %>%
dplyr::ungroup() %>%
dplyr::mutate(
Criterion = factor(
Criterion,
levels = c("Adjusted_R2", "Cp", "BIC"),
labels = c(
"Adjusted R-squared",
"Mallows' Cp",
"BIC"
)
)
)
ggplot(
data_plot_subset,
aes(
x = Subset_Size,
y = Value
)
) +
geom_line(
color = "#235789",
linewidth = 0.8
) +
geom_point(
aes(color = Optimal),
size = 2.8
) +
geom_text(
data = function(x) {
dplyr::filter(x, Optimal)
},
aes(label = sprintf("%.4f", Value)),
vjust = -1.1,
size = 3.3
) +
facet_wrap(
~ Criterion,
nrow = 1,
scales = "free_y"
) +
scale_color_manual(
values = c(
"FALSE" = "#235789",
"TRUE" = "#D55E00"
)
) +
scale_x_continuous(
breaks = 1:jumlah_koefisien
) +
scale_y_continuous(
expand = expansion(mult = c(0.10, 0.20))
) +
labs(
x = "Subset size (number of coefficients)",
y = "Criterion value"
) +
theme_minimal(base_size = 11) +
theme(
legend.position = "none",
panel.grid.minor = element_blank()
)The three criteria have different optima. BIC chooses a smaller subset because it imposes a stronger complexity penalty for this sample size. This illustrates why adding predictors does not necessarily improve a model enough to justify the added complexity.
Selecting the Final Model
The final model is chosen using the minimum training-data BIC.
# Determine the subset size using BIC
ukuran_terbaik_bic <- hasil_best_subset$Subset_Size[
which.min(hasil_best_subset$BIC)
]
# Extract coefficients of the selected model
koefisien_bic <- coef(
model_best_subset,
id = ukuran_terbaik_bic
)
tibble::tibble(
Coefficient = names(koefisien_bic),
Estimate = as.numeric(koefisien_bic)
) %>%
knitr::kable(
digits = 4,
caption = "Coefficients of the BIC-selected Best Subset model."
)| Coefficient | Estimate |
|---|---|
| (Intercept) | 2320.2022 |
| lwt | 6.2992 |
| smokeYes | -264.9937 |
| htYes | -665.0854 |
| uiYes | -454.6350 |
According to BIC, the final model contains lwt, smokeYes, htYes, and uiYes. The lwt coefficient of 6.2992 indicates that a one-pound increase in maternal weight is associated with an approximately 6.30-gram increase in infant birth weight, holding the other predictors constant.
The coefficients for smokeYes, htYes, and uiYes are negative, at −264.99, −665.09, and −454.64 grams, respectively, relative to their reference categories. These coefficients describe associations within the regression model and should not be interpreted directly as causal effects.
Evaluating Model Predictions
Predictive performance is evaluated using RMSE and MAE:
\[RMSE= \sqrt{ \frac{1}{n} \sum_{i=1}^{n}(y_i-\hat y_i)^2 }\]
\[MAE= \frac{1}{n} \sum_{i=1}^{n}|y_i-\hat y_i|\]
Both metrics are measured in grams; lower RMSE and MAE indicate smaller prediction errors.
# Prediction function for regsubsets
prediksi_best_subset <- function(
model, id, data_baru, formula
) {
beta <- coef(model, id = id)
X <- model.matrix(
formula,
data = data_baru
)
as.numeric(
X[, names(beta), drop = FALSE] %*% beta
)
}
# Evaluation function
hitung_metrik_regresi <- function(aktual, prediksi) {
tibble::tibble(
RMSE = sqrt(mean((aktual - prediksi)^2)),
MAE = mean(abs(aktual - prediksi))
)
}
# Predict on training and test data
pred_train <- prediksi_best_subset(
model_best_subset,
ukuran_terbaik_bic,
data_train_regresi,
formula_best_subset
)
pred_test <- prediksi_best_subset(
model_best_subset,
ukuran_terbaik_bic,
data_test_regresi,
formula_best_subset
)
# Mean-response baseline from training data
pred_baseline <- rep(
mean(data_train_regresi$bwt),
nrow(data_test_regresi)
)
# Evaluation summary
hasil_evaluasi_best_subset <- dplyr::bind_rows(
hitung_metrik_regresi(
data_train_regresi$bwt,
pred_train
) %>%
dplyr::mutate(
Model = "Best Subset",
Dataset = "Training"
),
hitung_metrik_regresi(
data_test_regresi$bwt,
pred_test
) %>%
dplyr::mutate(
Model = "Best Subset",
Dataset = "Test"
),
hitung_metrik_regresi(
data_test_regresi$bwt,
pred_baseline
) %>%
dplyr::mutate(
Model = "Mean baseline",
Dataset = "Test"
)
) %>%
dplyr::select(Model, Dataset, RMSE, MAE)
knitr::kable(
hasil_evaluasi_best_subset,
digits = 2,
caption = "Evaluation of Best Subset and baseline models."
)| Model | Dataset | RMSE | MAE |
|---|---|---|---|
| Best Subset | Training | 623.71 | 509.83 |
| Best Subset | Test | 804.46 | 655.20 |
| Mean baseline | Test | 853.86 | 706.72 |
Evaluation shows that Best Subset RMSE increases from 623.71 grams on the training data to 804.46 grams on the test data. Test MAE is 655.20 grams. The mean-prediction baseline has a test RMSE of 853.86 grams and an MAE of 706.72 grams.
Thus, Best Subset achieves approximately 5.79% lower RMSE and 7.29% lower MAE than the baseline on the test set. The selected predictors provide some predictive benefit, although prediction errors remain substantial.
BIC-based selection uses training data exclusively; the test data are used only to evaluate the prespecified model.
3.2 Subset Search Strategies: Genetic Algorithm and Simulated Annealing
The exhaustive search used by Best Subset evaluates every possible coefficient combination. As the number of predictors increases, the search space grows exponentially and computational requirements can become very high.
Two alternative search strategies discussed by Sartono et al. (2024) are the Genetic Algorithm (GA) and Simulated Annealing (SA). Both are metaheuristic methods that search iteratively without evaluating every possible subset.
Applications to Regression and Classification
Genetic Algorithm and Simulated Annealing are not restricted to either regression or classification. They are general optimization strategies for finding predictor combinations, provided an appropriate evaluation function is available.
In regression, subsets can be evaluated using AIC, BIC, or cross-validated prediction error such as RMSE. In classification, subsets can be evaluated using AIC or BIC from logistic regression, or cross-validated performance measures such as AUC or log-loss.
If the objective is to minimize a function \(J(S)\), the general formulation is:
\[S^*=\arg\min_{S\subseteq\{1,\ldots,p\}}J(S)\]
The objective depends on the modeling goal. For metrics that should be maximized, such as AUC, the search criterion can be defined as \(J(S)=1-AUC(S)\).
Numerical predictors can be included in the representation required by the model, while categorical predictors can be represented by dummy variables. If the unit of selection is the original variable, all dummy coefficients derived from one predictor are included or excluded together.
GA and SA determine how subsets are searched, while the model and evaluation function determine how subset quality is assessed. A full GA or SA implementation is omitted here because exhaustive searching is still computationally feasible for eight original predictors.
A subset is represented by a binary vector:
\[\mathbf{v}=(v_1,v_2,\ldots,v_p)\]
where \(v_j=1\) means predictor \(j\) is included and \(v_j=0\) means it is excluded. For example, \((1,0,1,0)\) selects the first and third predictors.
Each subset can be evaluated using the Akaike Information Criterion (AIC):
\[AIC=-2\ln L(\hat{\boldsymbol{\theta}})+2k\]
where \(L(\hat{\boldsymbol{\theta}})\) is the maximized likelihood and \(k\) is the number of estimated parameters. The search objective is:
\[\mathbf{v}^{*} = \arg\min_{\mathbf{v}\in\{0,1\}^{p}} AIC(\mathbf{v})\]
Genetic Algorithm maintains a population of candidate subsets. At each generation, candidates with better criterion values are more likely to be selected as parents. New candidates are generated through crossover and mutation. The procedure is repeated to explore different predictor combinations.
Simulated Annealing maintains one current solution and generates neighboring solutions by altering a binary-vector element. Solutions with lower AIC are accepted, while worse solutions may still be accepted with probability:
\[P(\text{accept})= \min\left\{ 1, \exp\left(-\frac{\Delta AIC}{T}\right) \right\}\]
where:
\[\Delta AIC=AIC(\mathbf{w})-AIC(\mathbf{v})\]
\(T\) denotes a temperature that is gradually reduced during the search. Accepting a worse solution at high temperatures allows the algorithm to escape local optima.
| Aspect | Genetic Algorithm | Simulated Annealing |
|---|---|---|
| Solutions maintained | Population of subsets | One current solution |
| Candidate generation | Crossover and mutation | Changes to neighboring solutions |
| Search mechanism | Selection between generations | Temperature-based acceptance |
| Output | Best subset found | Best subset found |
Neither algorithm guarantees finding the global optimum on every run. Results can depend on initialization and search parameters.
For birthwt, there are only eight original candidate predictors, so an exhaustive search remains feasible. GA and SA are therefore introduced to illustrate alternative search strategies without requiring a separate optimization implementation in this session.
As an illustration of different criteria, the BIC-selected Best Subset model can be compared with the full model using AIC.
# BIC-selected model
model_bic_lm <- stats::lm(
bwt ~ lwt + smoke + ht + ui,
data = data_train_regresi
)
# Full model
model_lengkap_lm <- stats::lm(
formula_best_subset,
data = data_train_regresi
)
tibble::tibble(
Model = c("Subset BIC", "Full model"),
Variable_Count = c(4, 8),
AIC = c(
AIC(model_bic_lm),
AIC(model_lengkap_lm)
)
) %>%
knitr::kable(
digits = 4,
caption = "AIC comparison of the BIC-selected subset and full model."
)| Model | Variable_Count | AIC |
|---|---|---|
| Subset BIC | 4 | 2384.094 |
| Full model | 8 | 2383.666 |
The full model has an AIC of 2383.666, slightly lower than the BIC-selected subset’s AIC of 2384.094. This difference demonstrates that the chosen model can change when the evaluation criterion changes. These values are not outputs of GA or SA optimization; they simply illustrate AIC-based evaluation of candidate subsets.
3.3 Boruta
Boruta is a Random Forest-based variable selection method designed to identify all predictors relevant to a response (all-relevant feature selection). Unlike Best Subset Selection, which seeks predictor combinations based on goodness of fit and model complexity, Boruta tests whether the importance of each original predictor consistently exceeds that of randomized predictors.
Boruta can be applied to both classification and regression. The distinction is the response type and how Random Forest measures prediction error. The creation of shadow features and the selection-decision procedure are the same.
Basic Concepts and Mathematical Formulation
Suppose there are \(p\) original predictors:
\[\mathbf{X}=(X_1,X_2,\ldots,X_p)\]
Boruta creates shadow features by randomly permuting each original predictor’s values across observations:
\[\widetilde{\mathbf{X}}= (\widetilde X_1,\widetilde X_2,\ldots,\widetilde X_p)\]
Shadow features preserve the marginal distribution of the original predictors but disrupt their observed relationships with the response.
At iteration \(t\), Random Forest is fitted using both original and shadow predictors. Each predictor’s importance can be assessed through permutation importance, which measures the change in prediction error after permuting that predictor.
Conceptually, raw permutation importance may be expressed as:
\[\Delta_j^{(t)} = L_{\mathrm{perm},j}^{(t)} - L_{\mathrm{baseline}}^{(t)}\]
Here, \(L_{\mathrm{baseline}}^{(t)}\) is the prediction error before permutation, and \(L_{\mathrm{perm},j}^{(t)}\) is the error after permuting predictor \(j\). This measurement is generally based on out-of-bag (OOB) observations from the Random Forest.
A larger \(\Delta_j^{(t)}\) indicates a greater increase in prediction error when the predictor is permuted. However, Boruta implementations may use importance scores normalized by an importance adapter, so meanImp need not have the same units as the raw increase in prediction error.
Let \(I_j^{(t)}\) be the adapter’s importance score for original predictor \(j\). The maximum shadow-feature importance is:
\[I_{\mathrm{shadow,max}}^{(t)} = \max_{k=1,\ldots,p} I_{\widetilde X_k}^{(t)}\]
A predictor earns one hit when its importance exceeds the highest shadow importance:
\[W_j^{(t)} = \begin{cases} 1, & I_j^{(t)}>I_{\mathrm{shadow,max}}^{(t)}\\ 0, & \text{otherwise} \end{cases}\]
The number of hits over \(T\) iterations is:
\[H_j=\sum_{t=1}^{T}W_j^{(t)}\]
Boruta tests whether the hit frequency is significantly higher or lower than that expected under a randomized reference. The test uses a binomial distribution with reference probability 0.5 and may incorporate multiple-testing corrections.
Selection decisions fall into three categories:
| Decision | Meaning |
|---|---|
| Confirmed | The predictor is deemed relevant by the Boruta test |
| Tentative | Insufficient evidence is available for a final decision |
| Rejected | The predictor is not established as relevant under the Boruta procedure |
These principles apply to both classification and regression. The difference lies in the loss function underpinning predictor importance.
Illustration of the Boruta algorithm from Daniel Homola’s BorutaPy project.
3.3.1 Boruta for Classification
In classification, Random Forest predicts response categories. One loss function that can underlie permutation importance is the misclassification rate:
\[L_{\mathrm{classification}} = \frac{1}{n_{\mathrm{OOB}}} \sum_{i=1}^{n_{\mathrm{OOB}}} \mathbb{I}(y_i\neq\hat y_i)\]
Here, \(\mathbb{I}(\cdot)\) is an indicator equal to one for incorrect predictions and zero otherwise.
Permuting a relevant predictor tends to increase classification error. The resulting change informs predictor importance, which is then compared against the shadow features.
For birthwt, classification Boruta uses:
- Response:
low(LowandNot low). - Predictors:
age,lwt,race,smoke,ptl,ht,ui, andftv. - Data:
data_train_klasifikasi.
The variable bwt is excluded from the predictors because it defines low.
Implementing Classification Boruta
# Run Boruta for classification
set.seed(2026)
model_boruta_klasifikasi <- Boruta::Boruta(
low ~ .,
data = as.data.frame(data_train_klasifikasi),
maxRuns = 100,
pValue = 0.01,
mcAdj = TRUE,
holdHistory = TRUE,
doTrace = 0
)
# Extract importance statistics and decisions
hasil_boruta_klasifikasi <- Boruta::attStats(
model_boruta_klasifikasi
) %>%
tibble::rownames_to_column("Predictor") %>%
dplyr::arrange(dplyr::desc(meanImp))
knitr::kable(
hasil_boruta_klasifikasi %>%
dplyr::select(
Predictor,
meanImp,
medianImp,
normHits,
decision
),
digits = 4,
col.names = c(
"Predictor",
"Mean importance",
"Median importance",
"Hit proportion",
"Decision"
),
caption = "Boruta selection results for classification."
)| Predictor | Mean importance | Median importance | Hit proportion | Decision |
|---|---|---|---|---|
| ptl | 0.4093 | 0.3971 | 0.9759 | Confirmed |
| ht | 0.1992 | 0.1864 | 0.6747 | Confirmed |
| lwt | 0.1872 | 0.1648 | 0.6867 | Confirmed |
| ftv | 0.0906 | 0.0821 | 0.2651 | Rejected |
| age | 0.0426 | 0.0372 | 0.0723 | Rejected |
| smoke | 0.0400 | 0.0337 | 0.0964 | Rejected |
| ui | 0.0037 | 0.0032 | 0.0000 | Rejected |
| race | -0.1107 | -0.1033 | 0.0000 | Rejected |
meanImp and medianImp summarize predictor importance across iterations; normHits is the proportion of hits relative to randomized controls; and decision gives the final selection result.
Visualizing Classification Boruta
plot(
model_boruta_klasifikasi,
sort = TRUE,
las = 2,
cex.axis = 0.85,
xlab = "",
ylab = "Predictor importance",
main = "Boruta - Classification"
)The plot displays importance distributions for the original and shadow predictors. Green indicates Confirmed, yellow Tentative, red Rejected, and blue randomized shadow references.
Extracting Selected Predictors
# Predictors with Confirmed decisions
prediktor_boruta_klasifikasi <-
Boruta::getSelectedAttributes(
model_boruta_klasifikasi,
withTentative = FALSE
)
# Decision summary
hasil_boruta_klasifikasi %>%
dplyr::group_by(decision) %>%
dplyr::summarise(
Count = dplyr::n(),
Predictor = paste(Predictor, collapse = ", "),
.groups = "drop"
) %>%
knitr::kable(
caption = "Summary of classification Boruta decisions."
)| decision | Count | Predictor |
|---|---|---|
| Confirmed | 3 | ptl, ht, lwt |
| Rejected | 5 | ftv, age, smoke, ui, race |
Interpretation of Classification Results
Boruta confirms three predictors: ptl, ht, and lwt. The remaining five—ftv, age, smoke, ui, and race—are Rejected. No predictor is classified as Tentative.
ptl has the highest mean importance (0.4093) and a hit proportion of 0.9759, suggesting that its importance consistently exceeds that of randomized controls. The corresponding mean importance scores for ht and lwt are 0.1992 and 0.1872.
These findings agree with several Filtering methods that place ptl and lwt near the top. However, smoke, which shows a significant relationship under Chi-Square, is Rejected by Boruta. This difference illustrates that a marginal relationship with the response does not always translate into sufficient model-based importance when predictors are assessed jointly in Random Forest.
Thus, under the Boruta procedure applied to training data, ptl, ht, and lwt are considered relevant for classifying low birth weight.
3.3.2 Boruta for Regression
In regression, Random Forest predicts a numerical response. Boruta follows the same selection mechanism, but predictor importance is measured through changes in numerical prediction error.
One loss function used in regression Random Forest is Mean Squared Error (MSE):
\[L_{\mathrm{regression}} = \frac{1}{n_{\mathrm{OOB}}} \sum_{i=1}^{n_{\mathrm{OOB}}} (y_i-\hat y_i)^2\]
Permuting a relevant predictor tends to increase prediction error. This change informs its importance, which is compared against shadow-feature importance using the same Boruta selection procedure as for classification.
For birthwt, regression Boruta uses:
- Response:
bwt(infant birth weight in grams). - Predictors:
age,lwt,race,smoke,ptl,ht,ui, andftv. - Data:
data_train_regresi.
The variable low is not used as a predictor because it is directly derived from bwt.
Implementing Regression Boruta
# Run Boruta for regression
set.seed(2026)
model_boruta_regresi <- Boruta::Boruta(
bwt ~ .,
data = as.data.frame(data_train_regresi),
maxRuns = 100,
pValue = 0.01,
mcAdj = TRUE,
holdHistory = TRUE,
doTrace = 0
)
# Extract selection results
hasil_boruta_regresi <- Boruta::attStats(
model_boruta_regresi
) %>%
tibble::rownames_to_column("Predictor") %>%
dplyr::arrange(dplyr::desc(meanImp))
knitr::kable(
hasil_boruta_regresi %>%
dplyr::select(
Predictor,
meanImp,
medianImp,
normHits,
decision
),
digits = 4,
col.names = c(
"Predictor",
"Mean importance",
"Median importance",
"Hit proportion",
"Decision"
),
caption = "Boruta selection results for regression."
)| Predictor | Mean importance | Median importance | Hit proportion | Decision |
|---|---|---|---|---|
| lwt | 0.3366 | 0.3360 | 0.9293 | Confirmed |
| ptl | 0.2795 | 0.2769 | 0.8283 | Confirmed |
| smoke | 0.2603 | 0.2654 | 0.8182 | Confirmed |
| ui | 0.2424 | 0.2537 | 0.7475 | Confirmed |
| race | 0.1243 | 0.1207 | 0.4646 | Tentative |
| ftv | 0.0480 | 0.0456 | 0.0505 | Rejected |
| ht | 0.0102 | -0.0021 | 0.0000 | Rejected |
| age | -0.0215 | -0.0091 | 0.0000 | Rejected |
Visualizing Regression Boruta
plot(
model_boruta_regresi,
sort = TRUE,
las = 2,
cex.axis = 0.85,
xlab = "",
ylab = "Predictor importance",
main = "Boruta - Regression"
)Extracting Selected Predictors
# Predictors with Confirmed decisions
prediktor_boruta_regresi <-
Boruta::getSelectedAttributes(
model_boruta_regresi,
withTentative = FALSE
)
# Decision summary
hasil_boruta_regresi %>%
dplyr::group_by(decision) %>%
dplyr::summarise(
Count = dplyr::n(),
Predictor = paste(Predictor, collapse = ", "),
.groups = "drop"
) %>%
knitr::kable(
caption = "Summary of regression Boruta decisions."
)| decision | Count | Predictor |
|---|---|---|
| Tentative | 1 | race |
| Confirmed | 4 | lwt, ptl, smoke, ui |
| Rejected | 3 | ftv, ht, age |
Regression Boruta labels four predictors as Confirmed: lwt, ptl, smoke, and ui. lwt has the highest mean importance (0.3366), with a hit proportion of 0.9293, followed by ptl (0.2795), smoke (0.2603), and ui (0.2424). All four exhibit importance that is consistently greater than the randomized controls under the Boruta procedure.
The predictor race is Tentative, indicating that the available selection evidence is insufficient for a definitive relevance decision. Meanwhile, ftv, ht, and age are Rejected because they do not satisfy Boruta’s relevance-confirmation criteria.
These results describe the relevance of predictors to numerical birth weight (bwt) based on importance in a regression Random Forest. Selection decisions do not establish the direction of association or a causal effect on birth weight. Differences from classification results are examined next.
3.3.3 Comparing Classification and Regression Boruta
Although the same eight predictors and training observations are used, classification and regression address different prediction tasks. Their Boruta selections need not be identical.
The comparison uses selection-decision status, rather than directly comparing importance scores, because the scales and calculation of importance may differ between tasks.
# Combine classification and regression decisions
perbandingan_boruta <-
hasil_boruta_klasifikasi %>%
dplyr::select(
Predictor,
Classification = decision
) %>%
dplyr::left_join(
hasil_boruta_regresi %>%
dplyr::select(
Predictor,
Regression = decision
),
by = "Predictor"
) %>%
dplyr::mutate(
Description = dplyr::case_when(
Classification == "Confirmed" &
Regression == "Confirmed" ~ "Relevant in both tasks",
Classification == "Rejected" &
Regression == "Rejected" ~ "Rejected in both tasks",
TRUE ~ "Different or tentative decisions"
)
)
knitr::kable(
perbandingan_boruta,
caption = "Comparison of Boruta decisions in classification and regression."
)| Predictor | Classification | Regression | Description |
|---|---|---|---|
| ptl | Confirmed | Confirmed | Relevant in both tasks |
| ht | Confirmed | Rejected | Different or tentative decisions |
| lwt | Confirmed | Confirmed | Relevant in both tasks |
| ftv | Rejected | Rejected | Rejected in both tasks |
| age | Rejected | Rejected | Rejected in both tasks |
| smoke | Rejected | Confirmed | Different or tentative decisions |
| ui | Rejected | Confirmed | Different or tentative decisions |
| race | Rejected | Tentative | Different or tentative decisions |
# Summary of selected predictors
tibble::tibble(
Modeling_Task = c("Classification", "Regression"),
Confirmed_Count = c(
length(prediktor_boruta_klasifikasi),
length(prediktor_boruta_regresi)
),
Confirmed_Predictors = c(
paste(
prediktor_boruta_klasifikasi,
collapse = ", "
),
paste(
prediktor_boruta_regresi,
collapse = ", "
)
)
) %>%
knitr::kable(
caption = "Summary of selected predictors in both modeling tasks."
)| Modeling_Task | Confirmed_Count | Confirmed_Predictors |
|---|---|---|
| Classification | 3 | lwt, ptl, ht |
| Regression | 4 | lwt, smoke, ptl, ui |
This comparison identifies predictors considered relevant in both tasks, in only one task, or rejected in both.
Predictors selected in both tasks show consistency in Boruta decisions across the two related response formulations. Different decisions, however, do not automatically indicate that one selection is incorrect, since each task assesses relevance with respect to a different response and loss function.
Boruta produces predictor selection decisions, not final estimates of predictive performance. Assessing generalization would require fitting models with selected predictors and evaluating them on data not used in selection.
Interpretation of Classification and Regression Boruta Comparisons
ptl and lwt are Confirmed for both modeling tasks, indicating consistent relevance whether the response is expressed as low-birth-weight status or numerical birth weight. Conversely, age and ftv are Rejected in both tasks.
Decisions differ for ht, smoke, and ui. ht is Confirmed in classification but Rejected in regression. Conversely, smoke and ui are Confirmed in regression but Rejected in classification. race is Rejected in classification and Tentative in regression, leaving its regression relevance unresolved under the current Boruta run.
These differences relate to the modeling objectives. The classification response low only distinguishes infants weighing less than 2,500 grams from those who are not low birth weight. Information about variation within each weight class is lost. Regression instead uses numerical bwt, allowing the model to learn variation in birth weight measured in grams.
Although low is derived from bwt, the tasks do not use the same loss function. Classification Random Forest evaluates its ability to distinguish response classes, whereas regression Random Forest measures the accuracy of numerical predictions. Predictor contributions to prediction error can therefore differ even with the same observations and candidates.
These results demonstrate that relevance depends on the modeling objective and chosen importance measure. A Rejected decision does not prove that a predictor has no relationship whatsoever with the response. Similarly, a Confirmed predictor is not necessarily required in the simplest predictive model.
Boruta therefore applies the same selection principles to classification and regression but may reach different decisions because the responses and model loss functions differ. Importance values are not compared directly across the tasks, since their measurement scales and definitions need not be identical.
II · 4. Seleksi Variabel Menggunakan EmbeddedII · 4. Variable Selection Using Embedded Methods
Group LASSO memberi penalti pada kelompok koefisien sehingga level satu prediktor kategorik dapat dipilih bersama.Group LASSO penalizes groups of coefficients, allowing levels of a categorical predictor to be selected together.
Metode Embedded melakukan seleksi variabel sebagai bagian dari proses estimasi model. Berbeda dari Filtering yang menghitung relevansi prediktor secara terpisah dan Wrapper yang mengevaluasi kandidat subset, pendekatan Embedded memasukkan mekanisme seleksi langsung ke dalam fungsi optimasi model.
Pada praktikum sebelumnya telah dibahas LASSO, yang dapat menyusutkan koefisien regresi menjadi nol melalui regularisasi. Pada bagian ini, pembahasan diperluas menggunakan Group LASSO, yaitu regularisasi yang memungkinkan beberapa koefisien diperlakukan sebagai satu kelompok.
4.1 Group LASSO
Konsep Dasar dan Formulasi Matematis
Pada LASSO biasa, penalti diberikan terhadap setiap koefisien secara individual:
\[P_{\mathrm{LASSO}}(\boldsymbol{\beta}) = \lambda\sum_{j=1}^{p}|\beta_j|\]
Sementara itu, Group LASSO membagi koefisien ke dalam \(G\) kelompok yang tidak saling tumpang tindih:
\[\boldsymbol{\beta} = (\boldsymbol{\beta}_1,\ldots,\boldsymbol{\beta}_G)\]
Setiap kelompok \(g\) memiliki \(d_g\) koefisien. Penalti Group LASSO dinyatakan sebagai:
\[P_{\mathrm{Group\ LASSO}}(\boldsymbol{\beta}) = \lambda \sum_{g=1}^{G} \sqrt{d_g}\, \|\boldsymbol{\beta}_g\|_2\]
dengan:
\[\|\boldsymbol{\beta}_g\|_2 = \sqrt{ \sum_{j=1}^{d_g}\beta_{gj}^2 }\]
Parameter \(\lambda\geq 0\) mengendalikan kekuatan regularisasi. Semakin besar \(\lambda\), semakin kuat penalti yang diberikan sehingga lebih banyak kelompok koefisien dapat menyusut menjadi nol. Faktor \(\sqrt{d_g}\) digunakan untuk menyesuaikan penalti terhadap ukuran kelompok.
Perbedaan utamanya terletak pada unit seleksi. LASSO dapat menghilangkan koefisien secara individual, sedangkan Group LASSO memberikan penalti terhadap norma seluruh koefisien dalam suatu kelompok. Suatu kelompok dipertahankan ketika norma koefisiennya tidak nol dan dikeluarkan ketika seluruh koefisiennya menyusut menjadi nol.
Ilustrasi Group LASSO — bagaimana koefisien terseleksi sebagai kelompok, Referensi: Breheny, dokumentasi resmi package grpreg, visualisasi jalur regularisasi.
Penggunaan pada Prediktor Numerik dan Kategorik
Group LASSO tidak terbatas pada prediktor kategorik. Metode ini dapat digunakan pada prediktor numerik, kategorik, maupun kelompok fitur yang ditetapkan berdasarkan struktur data.
Pada dataset birthwt, kelompok dibentuk berdasarkan delapan variabel asli.
| Prediktor | Representasi | Jumlah Koefisien |
|---|---|---|
age |
Numerik | 1 |
lwt |
Numerik | 1 |
race |
Faktor tiga kategori | 2 |
smoke |
Faktor biner | 1 |
ptl |
Numerik diskrit | 1 |
ht |
Faktor biner | 1 |
ui |
Faktor biner | 1 |
ftv |
Numerik diskrit | 1 |
Dengan demikian, terdapat delapan kelompok prediktor dan sembilan koefisien, tidak termasuk intersep.
Untuk prediktor numerik tunggal, ukuran kelompok adalah \(d_g=1\), sehingga penalti Group LASSO terhadap kelompok tersebut sama bentuknya dengan penalti LASSO biasa. Keunggulan seleksi kelompok menjadi lebih terlihat pada prediktor race, yang direpresentasikan oleh dua dummy tetapi diperlakukan sebagai satu kelompok.
Prediktor numerik juga dapat membentuk kelompok berisi beberapa koefisien, misalnya ketika suatu variabel diperluas menggunakan polinomial atau spline. Dalam kondisi tersebut, seluruh koefisien basis dapat ditempatkan dalam kelompok yang sama.
Group LASSO dapat digunakan untuk regresi dan klasifikasi. Formulasi penaltinya tetap sama, tetapi fungsi kerugian dalam proses optimasi berbeda sesuai tipe respons.
Group LASSO untuk Regresi
Pada regresi dengan respons numerik, Group LASSO dapat menggunakan fungsi kerugian kuadrat terkecil. Fungsi objektifnya adalah:
\[\min_{\beta_0,\boldsymbol{\beta}} \left[ \frac{1}{2n} \sum_{i=1}^{n} (y_i-\hat y_i)^2 + \lambda\sum_{g=1}^{G} \sqrt{d_g}\, \|\boldsymbol{\beta}_g\|_2 \right]\]
dengan:
\[\hat y_i= \beta_0+ \sum_{g=1}^{G} \mathbf{x}_{ig}^{\mathsf T} \boldsymbol{\beta}_g\]
Komponen pertama mengukur kesalahan prediksi berat lahir, sedangkan komponen kedua memberikan penalti terhadap kelompok koefisien. Intersep \(\beta_0\) tidak dikenai penalti.
Pada praktikum ini, respons regresi adalah bwt, yaitu berat lahir bayi dalam gram.
Group LASSO untuk Klasifikasi
Untuk klasifikasi biner, Group LASSO dapat diterapkan pada regresi logistik dengan mengganti fungsi kerugian kuadrat menjadi negative log-likelihood binomial.
Peluang suatu observasi berada pada kelas positif dinyatakan sebagai:
\[\pi_i=P(Y_i=1\mid\mathbf{x}_i) = \frac{\exp(\eta_i)}{1+\exp(\eta_i)}\]
dengan:
\[\eta_i= \beta_0+ \sum_{g=1}^{G} \mathbf{x}_{ig}^{\mathsf T} \boldsymbol{\beta}_g\]
Fungsi objektif Group LASSO untuk klasifikasi biner adalah:
\[\min_{\beta_0,\boldsymbol{\beta}} \left[ -\frac{1}{n} \sum_{i=1}^{n} \left\{ y_i\ln(\pi_i) + (1-y_i)\ln(1-\pi_i) \right\} + \lambda\sum_{g=1}^{G} \sqrt{d_g}\, \|\boldsymbol{\beta}_g\|_2 \right]\]
Pada formulasi ini, \(y_i\) bernilai satu untuk kelas Rendah dan nol untuk kelas Tidak rendah.
Dengan demikian, perbedaan Group LASSO regresi dan klasifikasi terletak pada fungsi kerugiannya, sedangkan mekanisme penalti kelompok tetap sama.
Persiapan Matriks Prediktor dan Kelompok Koefisien
Implementasi dilakukan menggunakan package grpreg. Package ini menerima matriks prediktor tanpa kolom intersep serta vektor yang menunjukkan keanggotaan kelompok setiap koefisien.
Pada praktikum ini, pengelompokan mengikuti variabel asli. Prediktor race diperlakukan sebagai satu kelompok meskipun menghasilkan dua koefisien dummy.
Langkah 1. Membentuk matriks desain dan kelompok prediktor
# Instalasi cukup dilakukan sekali jika diperlukan
# install.packages("grpreg")
# Formula prediktor yang digunakan bersama
formula_group <- ~ age + lwt + race + smoke +
ptl + ht + ui + ftv
# Membentuk matriks desain data latih
matriks_lengkap <- stats::model.matrix(
formula_group,
data = data_train_regresi
)
# Mengambil identitas kelompok sebelum intersep dibuang
id_group <- attr(matriks_lengkap, "assign")[-1]
# Nama kelompok mengikuti urutan formula
nama_group <- attr(
stats::terms(formula_group),
"term.labels"
)
# Matriks prediktor tanpa intersep
X_group_train <- matriks_lengkap[, -1, drop = FALSE]
# Matriks data uji dengan struktur yang sama
X_group_test <- stats::model.matrix(
formula_group,
data = data_test_regresi
)[, -1, drop = FALSE]
stopifnot(
identical(
colnames(X_group_train),
colnames(X_group_test)
)
)
# Menampilkan struktur kelompok
struktur_group <- tibble::tibble(
Koefisien = colnames(X_group_train),
Kelompok = nama_group[id_group]
)
knitr::kable(
struktur_group,
caption = "Pengelompokan koefisien pada Group LASSO."
)| Koefisien | Kelompok |
|---|---|
| age | age |
| lwt | lwt |
| raceBlack | race |
| raceOther | race |
| smokeYa | smoke |
| ptl | ptl |
| htYa | ht |
| uiYa | ui |
| ftv | ftv |
Kolom Kelompok menunjukkan variabel asli yang memiliki setiap koefisien. Pada race, dua koefisien dummy berada dalam kelompok yang sama. Hal ini berbeda dari Best Subset Selection sebelumnya yang dapat memilih koefisien dummy secara terpisah.
Package grpreg melakukan standardisasi prediktor secara internal. Oleh karena itu, standardisasi manual tidak dilakukan dalam praktikum ini.
4.1.1 Implementasi Group LASSO untuk Regresi
Group LASSO diterapkan pada respons bwt menggunakan keluarga Gaussian. Nilai regularisasi \(\lambda\) dipilih melalui validasi silang lima lipatan pada data latih.
Validasi silang digunakan untuk mencari nilai \(\lambda\) yang meminimumkan kesalahan prediksi rata-rata, bukan untuk mengevaluasi model pada data uji.
Langkah 2. Menjalankan Group LASSO regresi
# Respons regresi
y_group_regresi <- data_train_regresi$bwt
# Validasi silang Group LASSO regresi
set.seed(2026)
cv_group_regresi <- grpreg::cv.grpreg(
X = X_group_train,
y = y_group_regresi,
group = id_group,
penalty = "grLasso",
family = "gaussian",
nfolds = 5
)
# Parameter terbaik dari validasi silang
cat(
"Lambda minimum regresi:",
cv_group_regresi$lambda.min,
"\n"
)Lambda minimum regresi: 10.90144
# Mengambil koefisien pada lambda terpilih
koef_group_regresi <- as.numeric(
coef(cv_group_regresi)
)[-1]
# Menghitung norma koefisien setiap kelompok
hasil_group_regresi <- tibble::tibble(
Prediktor = nama_group[id_group],
Koefisien = koef_group_regresi
) %>%
dplyr::group_by(Prediktor) %>%
dplyr::summarise(
Jumlah_Koefisien = dplyr::n(),
Norma_Kelompok = sqrt(sum(Koefisien^2)),
.groups = "drop"
) %>%
dplyr::mutate(
Status = dplyr::if_else(
Norma_Kelompok > 1e-8,
"Terpilih",
"Tidak terpilih"
)
)
knitr::kable(
hasil_group_regresi,
digits = 4,
caption = "Hasil seleksi Group LASSO untuk regresi."
)| Prediktor | Jumlah_Koefisien | Norma_Kelompok | Status |
|---|---|---|---|
| age | 1 | 11.1613 | Terpilih |
| ftv | 1 | 0.0000 | Tidak terpilih |
| ht | 1 | 579.0712 | Terpilih |
| lwt | 1 | 6.1767 | Terpilih |
| ptl | 1 | 113.4065 | Terpilih |
| race | 2 | 390.8963 | Terpilih |
| smoke | 1 | 277.5938 | Terpilih |
| ui | 1 | 382.8516 | Terpilih |
Norma kelompok dihitung dari seluruh koefisien yang termasuk dalam kelompok tersebut. Kelompok dengan norma mendekati nol dianggap tidak terpilih, sedangkan kelompok dengan norma positif dipertahankan.
Nilai norma tidak digunakan untuk menyimpulkan arah hubungan terhadap bwt. Untuk melihat arah hubungan, perlu diperiksa tanda masing-masing koefisien, dengan mempertimbangkan kategori referensi pada variabel dummy.
4.1.2 Implementasi Group LASSO untuk Klasifikasi
Pada klasifikasi, Group LASSO diterapkan menggunakan keluarga binomial dengan respons low. Kelas Rendah dikodekan sebagai satu dan kelas Tidak rendah sebagai nol.
Matriks prediktor serta struktur kelompok yang digunakan sama dengan regresi. Dengan demikian, perbedaan hasil seleksi terutama dapat dibahas berdasarkan perbedaan respons dan fungsi kerugian yang digunakan.
Langkah 3. Menjalankan Group LASSO klasifikasi
# Respons klasifikasi biner
y_group_klasifikasi <- as.integer(
data_train_klasifikasi$low == "Rendah"
)
# Validasi silang Group LASSO klasifikasi
set.seed(2026)
cv_group_klasifikasi <- grpreg::cv.grpreg(
X = X_group_train,
y = y_group_klasifikasi,
group = id_group,
penalty = "grLasso",
family = "binomial",
nfolds = 5
)
# Parameter terbaik dari validasi silang
cat(
"Lambda minimum klasifikasi:",
cv_group_klasifikasi$lambda.min,
"\n"
)Lambda minimum klasifikasi: 0.01109791
# Mengambil koefisien pada lambda terpilih
koef_group_klasifikasi <- as.numeric(
coef(cv_group_klasifikasi)
)[-1]
# Menghitung norma koefisien setiap kelompok
hasil_group_klasifikasi <- tibble::tibble(
Prediktor = nama_group[id_group],
Koefisien = koef_group_klasifikasi
) %>%
dplyr::group_by(Prediktor) %>%
dplyr::summarise(
Jumlah_Koefisien = dplyr::n(),
Norma_Kelompok = sqrt(sum(Koefisien^2)),
.groups = "drop"
) %>%
dplyr::mutate(
Status = dplyr::if_else(
Norma_Kelompok > 1e-8,
"Terpilih",
"Tidak terpilih"
)
)
knitr::kable(
hasil_group_klasifikasi,
digits = 4,
caption = "Hasil seleksi Group LASSO untuk klasifikasi."
)| Prediktor | Jumlah_Koefisien | Norma_Kelompok | Status |
|---|---|---|---|
| age | 1 | 0.0137 | Terpilih |
| ftv | 1 | 0.0000 | Tidak terpilih |
| ht | 1 | 1.6505 | Terpilih |
| lwt | 1 | 0.0170 | Terpilih |
| ptl | 1 | 0.6758 | Terpilih |
| race | 2 | 0.5816 | Terpilih |
| smoke | 1 | 0.7233 | Terpilih |
| ui | 1 | 0.2703 | Terpilih |
Hasil Group LASSO klasifikasi menunjukkan kelompok prediktor yang memiliki koefisien tidak nol pada nilai \(\lambda\) hasil validasi silang.
Berbeda dari regresi linear, koefisien model logistik dinyatakan pada skala log-odds. Karena itu, nilai koefisien dan norma kelompok tidak dibandingkan secara langsung antara regresi dan klasifikasi.
4.1.3 Pemilihan Parameter Regularisasi
Parameter \(\lambda\) menentukan keseimbangan antara kecocokan model dan penyusutan kelompok koefisien. Nilai \(\lambda\) dipilih berdasarkan kesalahan validasi silang pada data latih.
Pada regresi, kesalahan validasi silang berhubungan dengan prediksi respons numerik. Pada klasifikasi, validasi silang menggunakan deviance binomial. Karena memiliki skala yang berbeda, nilai kesalahan kedua model tidak dibandingkan secara langsung.
Langkah 4. Memvisualisasikan hasil validasi silang
# Menyiapkan data grafik validasi silang
data_cv_group <- dplyr::bind_rows(
tibble::tibble(
Model = "Regresi",
Log_Lambda = log(cv_group_regresi$lambda),
Kesalahan_CV = cv_group_regresi$cve,
Terpilih = seq_along(
cv_group_regresi$lambda
) == cv_group_regresi$min
),
tibble::tibble(
Model = "Klasifikasi",
Log_Lambda = log(cv_group_klasifikasi$lambda),
Kesalahan_CV = cv_group_klasifikasi$cve,
Terpilih = seq_along(
cv_group_klasifikasi$lambda
) == cv_group_klasifikasi$min
)
)
ggplot(
data_cv_group,
aes(
x = Log_Lambda,
y = Kesalahan_CV
)
) +
geom_line(
color = "#235789",
linewidth = 0.9
) +
geom_point(
data = function(x) dplyr::filter(x, Terpilih),
color = "#D55E00",
size = 3
) +
facet_wrap(
~ Model,
nrow = 1,
scales = "free_y"
) +
labs(
x = "Log(lambda)",
y = "Kesalahan Validasi Silang"
) +
theme_minimal(base_size = 12) +
theme(
panel.grid.minor = element_blank(),
strip.text = element_text(face = "bold")
)Titik yang ditandai menunjukkan nilai \(\lambda\) dengan kesalahan validasi silang minimum pada setiap tugas. Nilai tersebut digunakan untuk memperoleh koefisien dan keputusan seleksi kelompok.
Pemilihan berdasarkan kesalahan prediksi minimum tidak selalu menghasilkan model dengan jumlah kelompok paling sedikit. Oleh karena itu, jumlah prediktor terpilih perlu dilaporkan bersama nilai \(\lambda\) dan hasil evaluasi model.
4.1.4 Evaluasi Model pada Data Uji
Setelah parameter regularisasi dan kelompok prediktor ditentukan menggunakan data latih, model dievaluasi pada data uji.
Pada regresi digunakan RMSE dan MAE, sedangkan pada klasifikasi digunakan AUC dan Balanced Accuracy.
\[RMSE= \sqrt{ \frac{1}{n} \sum_{i=1}^{n}(y_i-\hat y_i)^2 }\]
\[MAE= \frac{1}{n} \sum_{i=1}^{n}|y_i-\hat y_i|\]
Untuk klasifikasi, Balanced Accuracy merupakan rata-rata sensitivitas dan spesifisitas:
\[BA= \frac{\text{Sensitivity}+\text{Specificity}}{2}\]
Balanced Accuracy digunakan karena proporsi kelas low tidak seimbang. Sementara itu, AUC digunakan untuk mengevaluasi kemampuan diskriminasi berdasarkan peluang prediksi.
Langkah 5. Mengevaluasi hasil prediksi pada data uji
# Prediksi regresi pada data uji
pred_group_regresi <- as.numeric(
predict(
cv_group_regresi,
X = X_group_test,
type = "response"
)
)
# Evaluasi regresi
evaluasi_group_regresi <- tibble::tibble(
Model = "Group LASSO Regresi",
RMSE = sqrt(mean(
(data_test_regresi$bwt - pred_group_regresi)^2
)),
MAE = mean(abs(
data_test_regresi$bwt - pred_group_regresi
))
)
knitr::kable(
evaluasi_group_regresi,
digits = 4,
caption = "Evaluasi Group LASSO regresi pada data uji."
)| Model | RMSE | MAE |
|---|---|---|
| Group LASSO Regresi | 783.9936 | 623.2801 |
# Peluang prediksi kelas Rendah
prob_group_klasifikasi <- as.numeric(
predict(
cv_group_klasifikasi,
X = X_group_test,
type = "response"
)
)
# Respons aktual biner
aktual_klasifikasi <- as.integer(
data_test_klasifikasi$low == "Rendah"
)
# Prediksi kelas menggunakan ambang 0,5
prediksi_kelas <- as.integer(
prob_group_klasifikasi >= 0.5
)
# Menghitung AUC
roc_group <- pROC::roc(
response = aktual_klasifikasi,
predictor = prob_group_klasifikasi,
levels = c(0, 1),
direction = "<",
quiet = TRUE
)
# Menghitung sensitivitas dan spesifisitas
sensitivitas <- mean(
prediksi_kelas[aktual_klasifikasi == 1] == 1
)
spesifisitas <- mean(
prediksi_kelas[aktual_klasifikasi == 0] == 0
)
# Evaluasi klasifikasi
evaluasi_group_klasifikasi <- tibble::tibble(
Model = "Group LASSO Klasifikasi",
AUC = as.numeric(pROC::auc(roc_group)),
Balanced_Accuracy = (
sensitivitas + spesifisitas
) / 2
)
knitr::kable(
evaluasi_group_klasifikasi,
digits = 4,
caption = "Evaluasi Group LASSO klasifikasi pada data uji."
)| Model | AUC | Balanced_Accuracy |
|---|---|---|
| Group LASSO Klasifikasi | 0.7147 | 0.6506 |
Evaluasi data uji digunakan untuk mengukur kemampuan prediksi model yang telah ditentukan melalui validasi silang. Nilai RMSE dan MAE tidak dibandingkan dengan AUC atau Balanced Accuracy karena masing-masing digunakan untuk tujuan pemodelan berbeda.
4.1.5 Perbandingan Hasil Seleksi Group LASSO
Perbandingan dilakukan berdasarkan status kelompok terpilih, bukan berdasarkan besar koefisien atau norma kelompok antarmodel.
Langkah 6. Membandingkan kelompok terpilih
# Menggabungkan hasil seleksi regresi dan klasifikasi
perbandingan_group <- hasil_group_regresi %>%
dplyr::select(
Prediktor,
Regresi = Status
) %>%
dplyr::left_join(
hasil_group_klasifikasi %>%
dplyr::select(
Prediktor,
Klasifikasi = Status
),
by = "Prediktor"
) %>%
dplyr::mutate(
Keterangan = dplyr::case_when(
Regresi == "Terpilih" &
Klasifikasi == "Terpilih" ~
"Terpilih pada keduanya",
Regresi == "Tidak terpilih" &
Klasifikasi == "Tidak terpilih" ~
"Tidak terpilih pada keduanya",
Regresi == "Terpilih" ~
"Terpilih hanya pada regresi",
TRUE ~ "Terpilih hanya pada klasifikasi"
)
)
knitr::kable(
perbandingan_group,
caption = "Perbandingan hasil Group LASSO pada regresi dan klasifikasi."
)| Prediktor | Regresi | Klasifikasi | Keterangan |
|---|---|---|---|
| age | Terpilih | Terpilih | Terpilih pada keduanya |
| ftv | Tidak terpilih | Tidak terpilih | Tidak terpilih pada keduanya |
| ht | Terpilih | Terpilih | Terpilih pada keduanya |
| lwt | Terpilih | Terpilih | Terpilih pada keduanya |
| ptl | Terpilih | Terpilih | Terpilih pada keduanya |
| race | Terpilih | Terpilih | Terpilih pada keduanya |
| smoke | Terpilih | Terpilih | Terpilih pada keduanya |
| ui | Terpilih | Terpilih | Terpilih pada keduanya |
# Ringkasan banyaknya kelompok terpilih
tibble::tibble(
Model = c("Regresi", "Klasifikasi"),
Jumlah_Kelompok_Terpilih = c(
sum(hasil_group_regresi$Status == "Terpilih"),
sum(hasil_group_klasifikasi$Status == "Terpilih")
)
) %>%
knitr::kable(
caption = "Jumlah kelompok terpilih pada Group LASSO."
)| Model | Jumlah_Kelompok_Terpilih |
|---|---|
| Regresi | 7 |
| Klasifikasi | 7 |
Perbandingan ini digunakan untuk memeriksa apakah Group LASSO mempertahankan kelompok prediktor yang sama pada kedua tugas pemodelan.
Prediktor yang terpilih pada klasifikasi belum tentu terpilih pada regresi, meskipun keduanya menggunakan kandidat prediktor dan pembagian observasi yang sama. Perbedaan tersebut dapat muncul karena fungsi kerugian dan parameter regularisasi yang dipilih melalui validasi silang berbeda.
Pada Group LASSO, keputusan seleksi ditentukan pada tingkat kelompok koefisien. Dengan demikian, seluruh koefisien dummy dari suatu prediktor kategorik seperti race diperlakukan sebagai satu unit dalam proses regularisasi.
Hasil ini melengkapi pembahasan Best Subset Selection dan Boruta. Best Subset mengevaluasi kombinasi koefisien berdasarkan kriteria model, Boruta membandingkan kepentingan prediktor dengan pembanding acak, sedangkan Group LASSO melakukan seleksi kelompok secara langsung melalui fungsi optimasi model.
Interpretasi Hasil Group LASSO
Hasil Group LASSO untuk Regresi
Hasil Group LASSO pada pemodelan berat lahir numerik (bwt) menunjukkan bahwa tujuh dari delapan kelompok prediktor dipertahankan, yaitu age, ht, lwt, ptl, race, smoke, dan ui. Sementara itu, ftv tidak terpilih karena seluruh koefisien dalam kelompok tersebut menyusut menjadi nol pada nilai parameter regularisasi yang dipilih melalui validasi silang.
Pada prediktor kategorik race, kedua koefisien dummy diperlakukan sebagai satu kelompok dan menghasilkan norma kelompok sebesar 390,8963. Hal ini memperlihatkan mekanisme Group LASSO yang melakukan seleksi terhadap seluruh koefisien suatu prediktor kategorik secara bersama-sama. Berbeda dari Best Subset Selection sebelumnya, pemilihan race tidak dilakukan secara terpisah terhadap masing-masing dummy.
Nilai norma kelompok tidak dapat digunakan untuk membandingkan besarnya pengaruh antarprediktor secara langsung karena skala koefisien dan satuan pengukurannya berbeda. Oleh karena itu, interpretasi hasil seleksi difokuskan pada kelompok prediktor yang dipertahankan atau dikeluarkan dari model.
Pada data uji, Group LASSO regresi menghasilkan RMSE sebesar 783,99 gram dan MAE sebesar 623,28 gram. Kedua nilai tersebut lebih rendah dibandingkan model Best Subset berdasarkan BIC sebelumnya, yang menghasilkan RMSE sebesar 804,46 gram dan MAE sebesar 655,20 gram. Dengan demikian, Group LASSO memberikan kesalahan prediksi lebih kecil pada pembagian data uji yang digunakan, meskipun mempertahankan lebih banyak prediktor daripada model Best Subset.
Hasil Group LASSO untuk Klasifikasi
Pada pemodelan klasifikasi status berat lahir rendah (low), Group LASSO juga mempertahankan tujuh kelompok prediktor yang sama dan mengeluarkan ftv. Kesamaan tersebut menunjukkan bahwa parameter regularisasi yang dipilih melalui validasi silang menghasilkan keputusan seleksi kelompok yang identik pada kedua tugas pemodelan.
Meskipun prediktor terpilih sama, koefisien kedua model tidak dapat dibandingkan secara langsung. Pada regresi, koefisien digunakan untuk memprediksi berat lahir dalam gram, sedangkan pada regresi logistik, koefisien berhubungan dengan perubahan log-odds kelas berat lahir rendah.
Evaluasi pada data uji menghasilkan AUC sebesar 0,7147 dan Balanced Accuracy sebesar 0,6506. Nilai AUC menunjukkan bahwa model memiliki kemampuan diskriminasi yang lebih baik daripada pemeringkatan acak, sedangkan Balanced Accuracy menunjukkan rata-rata sensitivitas dan spesifisitas sebesar 65,06% pada ambang klasifikasi 0,5. Hasil ini memperlihatkan kemampuan klasifikasi yang masih terbatas meskipun sebagian besar kelompok prediktor dipertahankan.
Interpretasi Validasi Silang dan Perbandingan Kedua Model
Grafik validasi silang memperlihatkan perubahan kesalahan prediksi terhadap nilai \(\log(\lambda)\) pada model regresi dan klasifikasi. Titik yang ditandai menunjukkan parameter regularisasi dengan kesalahan validasi silang minimum. Pada kedua model, kesalahan meningkat ketika regularisasi menjadi terlalu kuat, yang menunjukkan bahwa penyusutan koefisien secara berlebihan dapat mengurangi kemampuan model menangkap informasi prediktif.
Nilai kesalahan validasi silang regresi dan klasifikasi tidak dibandingkan secara langsung karena keduanya menggunakan fungsi kerugian dan skala pengukuran berbeda. Nilai \(\lambda\) yang terpilih juga tidak harus sama antara kedua model.
Kesamaan tujuh kelompok terpilih menunjukkan konsistensi keputusan Group LASSO pada data dan pengaturan validasi silang yang digunakan. Namun, pemilihan parameter berdasarkan kesalahan validasi silang minimum tidak selalu menghasilkan model paling sederhana. Dalam kasus ini, regularisasi hanya mengeluarkan satu dari delapan kelompok prediktor.
Hasil Group LASSO juga berbeda dari Boruta. Pada klasifikasi, Boruta hanya mengonfirmasi ptl, ht, dan lwt, sedangkan pada regresi Boruta mengonfirmasi lwt, ptl, smoke, dan ui, dengan race berstatus Tentative. Sebaliknya, Group LASSO mempertahankan tujuh kelompok prediktor pada kedua tugas.
Perbedaan tersebut mencerminkan tujuan dan mekanisme seleksi yang tidak sama. Boruta berupaya mengidentifikasi seluruh prediktor yang relevan melalui perbandingan dengan shadow features, sedangkan Group LASSO memilih kelompok koefisien melalui keseimbangan antara fungsi kerugian dan penalti regularisasi. Oleh karena itu, perbedaan jumlah prediktor terpilih tidak dapat digunakan secara langsung untuk menyatakan bahwa salah satu metode lebih baik.
Secara keseluruhan, Group LASSO memperlihatkan bagaimana regularisasi dapat digunakan untuk menyeleksi prediktor numerik dan kategorik pada pemodelan regresi maupun klasifikasi. Keunggulan utamanya dalam praktikum ini adalah kemampuan mempertahankan atau menghilangkan seluruh koefisien suatu prediktor kategorik sebagai satu kelompok, sehingga keputusan seleksi mengikuti struktur variabel asli.
Embedded methods perform variable selection as part of model estimation. Unlike Filtering, which calculates relevance for predictors individually, and Wrapper methods, which evaluate candidate subsets, Embedded methods incorporate the selection mechanism directly into the model’s optimization objective.
The previous practical introduced LASSO, which can shrink regression coefficients to zero through regularization. This section extends the discussion to Group LASSO, which allows several coefficients to be treated as one group.
4.1 Group LASSO
Basic Concepts and Mathematical Formulation
Ordinary LASSO penalizes individual coefficients:
\[P_{\mathrm{LASSO}}(\boldsymbol{\beta}) = \lambda\sum_{j=1}^{p}|\beta_j|\]
Group LASSO instead partitions coefficients into \(G\) non-overlapping groups:
\[\boldsymbol{\beta} = (\boldsymbol{\beta}_1,\ldots,\boldsymbol{\beta}_G)\]
Each group \(g\) contains \(d_g\) coefficients. The Group LASSO penalty is:
\[P_{\mathrm{Group\ LASSO}}(\boldsymbol{\beta}) = \lambda \sum_{g=1}^{G} \sqrt{d_g}\, \|\boldsymbol{\beta}_g\|_2\]
where:
\[\|\boldsymbol{\beta}_g\|_2 = \sqrt{ \sum_{j=1}^{d_g}\beta_{gj}^2 }\]
The parameter \(\lambda\geq 0\) controls regularization strength. A larger \(\lambda\) imposes a stronger penalty, potentially shrinking more coefficient groups to zero. The factor \(\sqrt{d_g}\) adjusts the penalty for group size.
The key distinction is the unit of selection. LASSO may remove individual coefficients, whereas Group LASSO penalizes the norm of all coefficients in a group. A group is retained when its coefficient norm is nonzero and excluded when all its coefficients shrink to zero.
Group LASSO illustration: how coefficients are selected in groups. Reference: Breheny’s official grpreg package documentation, showing a regularization path.
Using Group LASSO with Numerical and Categorical Predictors
Group LASSO is not limited to categorical predictors. It can be applied to numerical predictors, categorical predictors, and sets of features grouped according to the structure of the data.
In birthwt, groups are defined by the eight original variables.
| Predictor | Representation | Number of Coefficients |
|---|---|---|
age |
Numerical | 1 |
lwt |
Numerical | 1 |
race |
Three-level factor | 2 |
smoke |
Binary factor | 1 |
ptl |
Discrete numerical | 1 |
ht |
Binary factor | 1 |
ui |
Binary factor | 1 |
ftv |
Discrete numerical | 1 |
There are therefore eight predictor groups and nine coefficients, excluding the intercept.
For a single numerical predictor, the group has \(d_g=1\), so its Group LASSO penalty has the same form as ordinary LASSO. Groupwise selection is especially useful for race, which is represented by two dummy coefficients but treated as one group.
Numerical predictors can also form multi-coefficient groups, for instance when a variable is expanded through polynomials or splines. All corresponding basis coefficients can then be placed in the same group.
Group LASSO can be used for regression and classification. The penalty has the same form, but the loss function in the optimization objective depends on the response type.
Group LASSO for Regression
With a numerical response, Group LASSO can use a least-squares loss. Its objective is:
\[\min_{\beta_0,\boldsymbol{\beta}} \left[ \frac{1}{2n} \sum_{i=1}^{n} (y_i-\hat y_i)^2 + \lambda\sum_{g=1}^{G} \sqrt{d_g}\, \|\boldsymbol{\beta}_g\|_2 \right]\]
where:
\[\hat y_i= \beta_0+ \sum_{g=1}^{G} \mathbf{x}_{ig}^{\mathsf T} \boldsymbol{\beta}_g\]
The first term measures birth-weight prediction error, while the second penalizes coefficient groups. The intercept \(\beta_0\) is not penalized.
In this practical, the regression response is bwt, infant birth weight in grams.
Group LASSO for Classification
For binary classification, Group LASSO can be applied to logistic regression by replacing squared-error loss with the binomial negative log-likelihood.
The probability of a positive-class outcome is:
\[\pi_i=P(Y_i=1\mid\mathbf{x}_i) = \frac{\exp(\eta_i)}{1+\exp(\eta_i)}\]
where:
\[\eta_i= \beta_0+ \sum_{g=1}^{G} \mathbf{x}_{ig}^{\mathsf T} \boldsymbol{\beta}_g\]
The binary classification objective is:
\[\min_{\beta_0,\boldsymbol{\beta}} \left[ -\frac{1}{n} \sum_{i=1}^{n} \left\{ y_i\ln(\pi_i) + (1-y_i)\ln(1-\pi_i) \right\} + \lambda\sum_{g=1}^{G} \sqrt{d_g}\, \|\boldsymbol{\beta}_g\|_2 \right]\]
Here, \(y_i=1\) denotes the Low class and \(y_i=0\) denotes Not low.
The difference between regression and classification Group LASSO therefore lies in their loss functions, not in the group penalty.
Preparing the Predictor Matrix and Coefficient Groups
The implementation uses the grpreg package, which takes a predictor matrix without an intercept column and a vector specifying the group membership of each coefficient.
Here, grouping follows the original variables. Although race produces two dummy coefficients, both belong to one group.
Step 1. Constructing the design matrix and predictor groups
# Installation is needed only once if the package is missing
# install.packages("grpreg")
# Common predictor formula
formula_group <- ~ age + lwt + race + smoke +
ptl + ht + ui + ftv
# Construct the training design matrix
matriks_lengkap <- stats::model.matrix(
formula_group,
data = data_train_regresi
)
# Extract group assignments before removing the intercept
id_group <- attr(matriks_lengkap, "assign")[-1]
# Group names follow the formula term order
nama_group <- attr(
stats::terms(formula_group),
"term.labels"
)
# Predictor matrix without the intercept
X_group_train <- matriks_lengkap[, -1, drop = FALSE]
# Test matrix with the same structure
X_group_test <- stats::model.matrix(
formula_group,
data = data_test_regresi
)[, -1, drop = FALSE]
stopifnot(
identical(
colnames(X_group_train),
colnames(X_group_test)
)
)
# Display the group structure
struktur_group <- tibble::tibble(
Coefficient = colnames(X_group_train),
Group = nama_group[id_group]
)
knitr::kable(
struktur_group,
caption = "Coefficient grouping for Group LASSO."
)| Coefficient | Group |
|---|---|
| age | age |
| lwt | lwt |
| raceBlack | race |
| raceOther | race |
| smokeYes | smoke |
| ptl | ptl |
| htYes | ht |
| uiYes | ui |
| ftv | ftv |
The Group column identifies the original variable to which each coefficient belongs. Both race dummy coefficients belong to the same group, unlike the earlier Best Subset implementation, which could select them separately.
grpreg standardizes predictors internally. Accordingly, no separate manual standardization is carried out here.
4.1.1 Implementing Group LASSO for Regression
Group LASSO is fitted to bwt using the Gaussian family. The regularization value \(\lambda\) is chosen by five-fold cross-validation using the training data.
Cross-validation is used to find the \(\lambda\) minimizing mean validation error, not to evaluate the model on the test set.
Step 2. Fitting regression Group LASSO
# Regression response
y_group_regresi <- data_train_regresi$bwt
# Cross-validate regression Group LASSO
set.seed(2026)
cv_group_regresi <- grpreg::cv.grpreg(
X = X_group_train,
y = y_group_regresi,
group = id_group,
penalty = "grLasso",
family = "gaussian",
nfolds = 5
)
# Best cross-validated parameter
cat(
"Minimum-error lambda for regression:",
cv_group_regresi$lambda.min,
"\n"
)Minimum-error lambda for regression: 10.90144
# Extract coefficients at the selected lambda
koef_group_regresi <- as.numeric(
coef(cv_group_regresi)
)[-1]
# Calculate each group coefficient norm
hasil_group_regresi <- tibble::tibble(
Predictor = nama_group[id_group],
Coefficient = koef_group_regresi
) %>%
dplyr::group_by(Predictor) %>%
dplyr::summarise(
Coefficient_Count = dplyr::n(),
Group_Norm = sqrt(sum(Coefficient^2)),
.groups = "drop"
) %>%
dplyr::mutate(
Status = dplyr::if_else(
Group_Norm > 1e-8,
"Selected",
"Not selected"
)
)
knitr::kable(
hasil_group_regresi,
digits = 4,
caption = "Group LASSO selection results for regression."
)| Predictor | Coefficient_Count | Group_Norm | Status |
|---|---|---|---|
| age | 1 | 11.1613 | Selected |
| ftv | 1 | 0.0000 | Not selected |
| ht | 1 | 579.0712 | Selected |
| lwt | 1 | 6.1767 | Selected |
| ptl | 1 | 113.4065 | Selected |
| race | 2 | 390.8963 | Selected |
| smoke | 1 | 277.5938 | Selected |
| ui | 1 | 382.8516 | Selected |
The group norm is calculated from all coefficients within each group. A group with a norm close to zero is regarded as unselected, whereas a group with a positive norm is retained.
The norm does not indicate the direction of association with bwt. To assess direction, the signs of the individual coefficients must be examined, taking the reference categories of dummy variables into account.
4.1.2 Implementing Group LASSO for Classification
For classification, Group LASSO uses the binomial family with low as the response. Low is coded as one and Not low as zero.
The predictor matrix and group structure are the same as in regression. Differences in the selected groups can therefore be discussed primarily in relation to the different responses and loss functions.
Step 3. Fitting classification Group LASSO
# Binary classification response
y_group_klasifikasi <- as.integer(
data_train_klasifikasi$low == "Low"
)
# Cross-validate classification Group LASSO
set.seed(2026)
cv_group_klasifikasi <- grpreg::cv.grpreg(
X = X_group_train,
y = y_group_klasifikasi,
group = id_group,
penalty = "grLasso",
family = "binomial",
nfolds = 5
)
# Best cross-validated parameter
cat(
"Minimum-error lambda for classification:",
cv_group_klasifikasi$lambda.min,
"\n"
)Minimum-error lambda for classification: 0.01109791
# Extract coefficients at the selected lambda
koef_group_klasifikasi <- as.numeric(
coef(cv_group_klasifikasi)
)[-1]
# Calculate each group coefficient norm
hasil_group_klasifikasi <- tibble::tibble(
Predictor = nama_group[id_group],
Coefficient = koef_group_klasifikasi
) %>%
dplyr::group_by(Predictor) %>%
dplyr::summarise(
Coefficient_Count = dplyr::n(),
Group_Norm = sqrt(sum(Coefficient^2)),
.groups = "drop"
) %>%
dplyr::mutate(
Status = dplyr::if_else(
Group_Norm > 1e-8,
"Selected",
"Not selected"
)
)
knitr::kable(
hasil_group_klasifikasi,
digits = 4,
caption = "Group LASSO selection results for classification."
)| Predictor | Coefficient_Count | Group_Norm | Status |
|---|---|---|---|
| age | 1 | 0.0137 | Selected |
| ftv | 1 | 0.0000 | Not selected |
| ht | 1 | 1.6505 | Selected |
| lwt | 1 | 0.0170 | Selected |
| ptl | 1 | 0.6758 | Selected |
| race | 2 | 0.5816 | Selected |
| smoke | 1 | 0.7233 | Selected |
| ui | 1 | 0.2703 | Selected |
The classification results identify the predictor groups whose coefficients are nonzero at the cross-validated value of \(\lambda\).
Unlike in linear regression, logistic coefficients are expressed on the log-odds scale. Coefficient values and group norms therefore should not be compared directly between regression and classification.
4.1.3 Selecting the Regularization Parameter
The parameter \(\lambda\) controls the trade-off between model fit and shrinkage of coefficient groups. It is selected from the training-data cross-validation error.
For regression, cross-validation error is related to predicting a numerical response. For classification, it is measured using binomial deviance. Because these quantities have different scales, their values should not be compared directly.
Step 4. Visualizing the cross-validation results
# Prepare cross-validation plotting data
data_cv_group <- dplyr::bind_rows(
tibble::tibble(
Model = "Regression",
Log_Lambda = log(cv_group_regresi$lambda),
CV_Error = cv_group_regresi$cve,
Selected = seq_along(
cv_group_regresi$lambda
) == cv_group_regresi$min
),
tibble::tibble(
Model = "Classification",
Log_Lambda = log(cv_group_klasifikasi$lambda),
CV_Error = cv_group_klasifikasi$cve,
Selected = seq_along(
cv_group_klasifikasi$lambda
) == cv_group_klasifikasi$min
)
)
ggplot(
data_cv_group,
aes(
x = Log_Lambda,
y = CV_Error
)
) +
geom_line(
color = "#235789",
linewidth = 0.9
) +
geom_point(
data = function(x) dplyr::filter(x, Selected),
color = "#D55E00",
size = 3
) +
facet_wrap(
~ Model,
nrow = 1,
scales = "free_y"
) +
labs(
x = "Log(lambda)",
y = "Cross-validation error"
) +
theme_minimal(base_size = 12) +
theme(
panel.grid.minor = element_blank(),
strip.text = element_text(face = "bold")
)The marked point identifies the \(\lambda\) with minimum cross-validation error for each task. This value is used to extract coefficients and make group selection decisions.
Selecting \(\lambda\) to minimize prediction error does not necessarily yield the model with the fewest groups. The number of selected predictors should therefore be reported alongside \(\lambda\) and the model-evaluation results.
4.1.4 Evaluating Models on the Test Set
Once the regularization parameter and predictor groups have been determined using training data, the models are evaluated on the test data.
RMSE and MAE are used for regression; AUC and Balanced Accuracy are used for classification.
\[RMSE= \sqrt{ \frac{1}{n} \sum_{i=1}^{n}(y_i-\hat y_i)^2 }\]
\[MAE= \frac{1}{n} \sum_{i=1}^{n}|y_i-\hat y_i|\]
For classification, Balanced Accuracy is the average of sensitivity and specificity:
\[BA= \frac{\text{Sensitivity}+\text{Specificity}}{2}\]
Balanced Accuracy is used because the low class proportions are imbalanced. AUC assesses class-discrimination ability based on predicted probabilities.
Step 5. Evaluating predictions on the test set
# Predict regression outcomes on the test set
pred_group_regresi <- as.numeric(
predict(
cv_group_regresi,
X = X_group_test,
type = "response"
)
)
# Regression evaluation
evaluasi_group_regresi <- tibble::tibble(
Model = "Group LASSO Regression",
RMSE = sqrt(mean(
(data_test_regresi$bwt - pred_group_regresi)^2
)),
MAE = mean(abs(
data_test_regresi$bwt - pred_group_regresi
))
)
knitr::kable(
evaluasi_group_regresi,
digits = 4,
caption = "Test-set evaluation of regression Group LASSO."
)| Model | RMSE | MAE |
|---|---|---|
| Group LASSO Regression | 783.9936 | 623.2801 |
# Predicted probability of the Low class
prob_group_klasifikasi <- as.numeric(
predict(
cv_group_klasifikasi,
X = X_group_test,
type = "response"
)
)
# Observed binary response
aktual_klasifikasi <- as.integer(
data_test_klasifikasi$low == "Low"
)
# Class predictions using a 0.5 threshold
prediksi_kelas <- as.integer(
prob_group_klasifikasi >= 0.5
)
# Calculate AUC
roc_group <- pROC::roc(
response = aktual_klasifikasi,
predictor = prob_group_klasifikasi,
levels = c(0, 1),
direction = "<",
quiet = TRUE
)
# Calculate sensitivity and specificity
sensitivitas <- mean(
prediksi_kelas[aktual_klasifikasi == 1] == 1
)
spesifisitas <- mean(
prediksi_kelas[aktual_klasifikasi == 0] == 0
)
# Classification evaluation
evaluasi_group_klasifikasi <- tibble::tibble(
Model = "Group LASSO Classification",
AUC = as.numeric(pROC::auc(roc_group)),
Balanced_Accuracy = (
sensitivitas + spesifisitas
) / 2
)
knitr::kable(
evaluasi_group_klasifikasi,
digits = 4,
caption = "Test-set evaluation of classification Group LASSO."
)| Model | AUC | Balanced_Accuracy |
|---|---|---|
| Group LASSO Classification | 0.7147 | 0.6506 |
Test-set evaluation assesses the predictive performance of models established through cross-validation. RMSE and MAE are not compared with AUC or Balanced Accuracy because they measure different prediction tasks.
4.1.5 Comparing Group LASSO Selection Results
The comparison uses selected-group status, rather than comparing coefficient sizes or group norms between models.
Step 6. Comparing selected groups
# Combine regression and classification selection results
perbandingan_group <- hasil_group_regresi %>%
dplyr::select(
Predictor,
Regression = Status
) %>%
dplyr::left_join(
hasil_group_klasifikasi %>%
dplyr::select(
Predictor,
Classification = Status
),
by = "Predictor"
) %>%
dplyr::mutate(
Description = dplyr::case_when(
Regression == "Selected" &
Classification == "Selected" ~
"Selected in both tasks",
Regression == "Not selected" &
Classification == "Not selected" ~
"Not selected in either task",
Regression == "Selected" ~
"Selected only in regression",
TRUE ~ "Selected only in classification"
)
)
knitr::kable(
perbandingan_group,
caption = "Comparison of Group LASSO results in regression and classification."
)| Predictor | Regression | Classification | Description |
|---|---|---|---|
| age | Selected | Selected | Selected in both tasks |
| ftv | Not selected | Not selected | Not selected in either task |
| ht | Selected | Selected | Selected in both tasks |
| lwt | Selected | Selected | Selected in both tasks |
| ptl | Selected | Selected | Selected in both tasks |
| race | Selected | Selected | Selected in both tasks |
| smoke | Selected | Selected | Selected in both tasks |
| ui | Selected | Selected | Selected in both tasks |
# Summary of the number of selected groups
tibble::tibble(
Model = c("Regression", "Classification"),
Selected_Group_Count = c(
sum(hasil_group_regresi$Status == "Selected"),
sum(hasil_group_klasifikasi$Status == "Selected")
)
) %>%
knitr::kable(
caption = "Number of groups selected by Group LASSO."
)| Model | Selected_Group_Count |
|---|---|
| Regression | 7 |
| Classification | 7 |
This comparison examines whether Group LASSO retains the same predictor groups in both modeling tasks.
A predictor selected for classification is not necessarily selected for regression, even though both tasks use the same candidates and data split. Differences may arise from distinct loss functions and the regularization parameters chosen by cross-validation.
Group LASSO makes selection decisions at the coefficient-group level. Thus, all dummy coefficients from a categorical predictor such as race are treated as one unit during regularization.
These results complement Best Subset Selection and Boruta. Best Subset evaluates coefficient combinations using model criteria, Boruta compares predictor importance with randomized controls, and Group LASSO selects groups directly through the model optimization objective.
Interpretation of Group LASSO Results
Group LASSO Results for Regression
For numerical birth-weight regression (bwt), Group LASSO retains seven of the eight predictor groups: age, ht, lwt, ptl, race, smoke, and ui. The ftv group is not selected because all its coefficients shrink to zero at the cross-validated regularization value.
For categorical predictor race, both dummy coefficients form a single group, with a group norm of 390.8963. This illustrates how Group LASSO selects the coefficients of a categorical predictor jointly. Unlike Best Subset Selection, race is not selected by considering its dummy coefficients separately.
Group norms cannot be used to compare the magnitude of predictor effects directly because coefficient scales and measurement units differ. Interpretation therefore focuses on which predictor groups are retained or excluded.
On the test set, Group LASSO regression yields an RMSE of 783.99 grams and MAE of 623.28 grams. Both are lower than the corresponding results from the earlier BIC-based Best Subset model (RMSE 804.46 grams; MAE 655.20 grams). Thus, Group LASSO has smaller prediction errors for this data split, although it retains more predictors than Best Subset.
Group LASSO Results for Classification
For classifying low-birth-weight status (low), Group LASSO retains the same seven groups and excludes ftv. This agreement indicates that the cross-validated regularization parameters produce identical group-selection decisions for the two tasks.
Although the same groups are selected, the models’ coefficients cannot be compared directly. Regression coefficients predict birth weight in grams, whereas logistic-regression coefficients describe changes in the log-odds of low birth weight.
The test-set AUC is 0.7147 and Balanced Accuracy is 0.6506. The AUC indicates better-than-random discrimination, while Balanced Accuracy indicates an average sensitivity and specificity of 65.06% at a classification threshold of 0.5. Classification performance remains limited even though most candidate groups are retained.
Interpretation of Cross-Validation and Model Comparisons
The cross-validation plots show how prediction error changes with \(\log(\lambda)\) in the regression and classification models. The highlighted points identify the regularization parameters with minimum cross-validation error. In both tasks, error rises when regularization becomes too strong, indicating that excessive coefficient shrinkage can weaken the model’s ability to capture predictive information.
Regression and classification cross-validation errors are not compared directly because they use different loss functions and scales. Their selected \(\lambda\) values also need not be equal.
Selection of the same seven groups indicates consistent Group LASSO decisions under the current data and cross-validation settings. However, choosing a parameter based on minimum validation error does not necessarily produce the simplest model. Here, regularization removes only one of the eight predictor groups.
Group LASSO also differs from Boruta. In classification, Boruta confirms only ptl, ht, and lwt. In regression, it confirms lwt, ptl, smoke, and ui, with race classified as Tentative. Group LASSO, by contrast, retains seven groups for both tasks.
These differences reflect distinct selection objectives and mechanisms. Boruta aims to identify all relevant predictors by comparing them with shadow features, while Group LASSO selects coefficient groups by balancing model loss against a regularization penalty. Different numbers of selected predictors therefore do not, by themselves, establish that one method is superior.
Overall, Group LASSO illustrates how regularization can select numerical and categorical predictors in both regression and classification. Its main advantage in this practical is the ability to retain or remove all coefficients belonging to a categorical predictor as one group, ensuring that selection respects the structure of the original variable.
Penyusutan kelompok koefisienGroup coefficient shrinkage
Ilustrasi proximal Group LASSO untuk satu kelompok koefisien (3, 4).Illustrative Group LASSO proximal operator for a coefficient group (3, 4).
Data ilustratif, bukan hasil estimasi R pada dataset praktikum.Illustrative data, not estimated R results for the practicum dataset.
II · 5. PenutupII · 5. Conclusion
Bandingkan hasil seleksi, kompleksitas, dan kemampuan generalisasi. Perbedaan prediktor terpilih tidak otomatis berarti metode lain salah.Compare selection, complexity and generalization. Different selected predictors do not automatically indicate that another method is wrong.
Praktikum ini memperlihatkan bahwa seleksi variabel tidak memiliki satu pendekatan yang selalu menghasilkan keputusan terbaik untuk seluruh persoalan pemodelan. Hasil seleksi bergantung pada tujuan analisis, tipe respons, representasi prediktor, model yang digunakan, dan kriteria evaluasi. Oleh karena itu, perbedaan prediktor terpilih antarmetode perlu dipahami berdasarkan mekanisme seleksinya, bukan langsung dianggap sebagai ketidakkonsistenan hasil.
5.1 Sintesis Hasil Seleksi Variabel
Pada pendekatan Filtering, relevansi prediktor dinilai secara individual melalui perbedaan karakteristik antarkelas, ketergantungan kategori, kemampuan diskriminasi, atau ukuran informasi. Hasil pada data birthwt menunjukkan bahwa ptl dan lwt relatif konsisten menempati peringkat tinggi, meskipun urutan keduanya berubah menurut ukuran relevansi yang digunakan. Temuan ini menunjukkan bahwa pemeringkatan marginal dipengaruhi oleh aspek hubungan prediktor dan respons yang diukur.
Pada pendekatan Wrapper, Best Subset Selection mengevaluasi kombinasi koefisien untuk memperoleh model yang memenuhi kriteria pemilihan. Berdasarkan BIC, model regresi terpilih menggunakan lwt, smoke, ht, dan ui. Sementara itu, Genetic Algorithm dan Simulated Annealing diperkenalkan sebagai strategi pencarian alternatif ketika banyaknya kemungkinan subset menyebabkan pencarian exhaustive menjadi mahal secara komputasi.
Boruta menggunakan pendekatan berbeda dengan membandingkan kepentingan prediktor asli terhadap prediktor bayangan (shadow features). Pada klasifikasi, Boruta mengonfirmasi ptl, ht, dan lwt, sedangkan pada regresi mengonfirmasi lwt, ptl, smoke, dan ui. Perbedaan tersebut menunjukkan bahwa relevansi prediktor dapat berubah ketika respons dinyatakan sebagai kategori atau sebagai nilai numerik.
Pada pendekatan Embedded, Group LASSO melakukan seleksi melalui regularisasi kelompok koefisien. Dalam praktikum ini, Group LASSO mempertahankan tujuh dari delapan kelompok prediktor, baik pada regresi maupun klasifikasi, dan mengeluarkan ftv. Berbeda dari Best Subset yang dapat menyeleksi koefisien dummy secara terpisah, Group LASSO memperlakukan seluruh koefisien suatu prediktor kategorik sebagai satu kelompok.
Ringkasan hasil metode yang diterapkan disajikan pada tabel berikut.
| Metode | Tujuan Pemodelan | Hasil Utama |
|---|---|---|
| Filtering | Klasifikasi | ptl dan lwt dominan pada pemeringkatan relevansi |
| Best Subset (BIC) | Regresi | lwt, smoke, ht, ui |
| Boruta | Klasifikasi | ptl, ht, lwt |
| Boruta | Regresi | lwt, ptl, smoke, ui; race berstatus Tentative |
| Group LASSO | Regresi | Tujuh kelompok terpilih; ftv tidak terpilih |
| Group LASSO | Klasifikasi | Tujuh kelompok terpilih; ftv tidak terpilih |
Tabel tersebut menunjukkan bahwa lwt merupakan salah satu prediktor yang paling konsisten memperoleh dukungan dari berbagai pendekatan. Sementara itu, ptl menempati peringkat tinggi pada sejumlah metode Filtering dan dikonfirmasi oleh Boruta pada kedua tugas pemodelan, tetapi tidak termasuk dalam model Best Subset berdasarkan BIC. Perbedaan ini menunjukkan bahwa relevansi individual tidak selalu sama dengan kontribusi suatu prediktor dalam kombinasi model tertentu.
Jumlah prediktor terpilih juga tidak dapat digunakan sebagai ukuran tunggal untuk menentukan metode terbaik. Best Subset berupaya menyeimbangkan kecocokan dan kompleksitas model, Boruta bertujuan mengidentifikasi seluruh prediktor yang relevan, sedangkan Group LASSO melakukan penyusutan koefisien berdasarkan parameter regularisasi. Ketiganya mempunyai tujuan seleksi yang berbeda.
5.2 Evaluasi Prediksi dan Implikasi Pemilihan Metode
Hasil evaluasi pada data uji menunjukkan bahwa Best Subset berdasarkan BIC menghasilkan RMSE sebesar 804,46 gram dan MAE sebesar 655,20 gram. Group LASSO regresi menghasilkan RMSE sebesar 783,99 gram dan MAE sebesar 623,28 gram. Pada pembagian data yang digunakan, Group LASSO memberikan kesalahan prediksi yang lebih kecil, meskipun mempertahankan lebih banyak prediktor.
Untuk klasifikasi, Group LASSO menghasilkan AUC sebesar 0,7147 dan Balanced Accuracy sebesar 0,6506. Hasil ini menunjukkan bahwa kemampuan diskriminasi model lebih baik daripada pemeringkatan acak, tetapi ketepatan klasifikasi masih terbatas.
Perbandingan tersebut perlu ditafsirkan secara hati-hati. Evaluasi didasarkan pada satu pembagian data latih dan data uji, sehingga belum cukup untuk menyimpulkan bahwa suatu metode secara umum lebih unggul. Selain itu, hasil seleksi prediktor dari Boruta belum dievaluasi menggunakan model prediksi tersendiri pada data uji. Oleh karena itu, keputusan seleksi Boruta tidak dapat langsung dibandingkan dengan kesalahan prediksi Best Subset atau Group LASSO.
Dalam penerapannya, pemilihan pendekatan seleksi variabel dapat mempertimbangkan tujuan berikut:
- Mengidentifikasi relevansi awal prediktor: Filtering dapat digunakan untuk melakukan pemeringkatan berdasarkan ukuran statistik atau informasi yang sesuai dengan tipe data.
- Mencari kombinasi prediktor untuk suatu model: Best Subset dapat digunakan ketika ruang pencarian masih memungkinkan; strategi metaheuristik dapat dipertimbangkan untuk ruang pencarian yang lebih besar.
- Mengidentifikasi seluruh prediktor yang relevan menurut model berbasis Random Forest: Boruta dapat digunakan pada regresi maupun klasifikasi.
- Melakukan seleksi sambil mempertahankan struktur kelompok koefisien: Group LASSO sesuai digunakan ketika prediktor, termasuk prediktor kategorik, direpresentasikan oleh satu atau beberapa koefisien yang ingin dipilih secara bersama.
Berdasarkan seluruh penerapan, terdapat tiga pemahaman utama mengenai seleksi variabel.
Pertama, hasil seleksi bergantung pada ukuran relevansi dan tujuan pemodelan. Prediktor yang menunjukkan hubungan marginal kuat belum tentu dipertahankan ketika dievaluasi bersama prediktor lain. Demikian pula, penggunaan respons kategorik dan numerik dapat menghasilkan keputusan seleksi berbeda meskipun berasal dari data yang sama.
Kedua, representasi prediktor memengaruhi unit seleksi. Prediktor numerik dapat digunakan secara langsung atau didiskretisasi sesuai persyaratan metode. Prediktor kategorik dapat direpresentasikan melalui sejumlah koefisien dummy, sehingga pemilihan koefisien individual perlu dibedakan dari pemilihan variabel sebagai satu kelompok.
Ketiga, seleksi variabel dan evaluasi prediksi merupakan dua tahap yang berbeda. Proses seleksi dilakukan menggunakan data latih, sedangkan data uji digunakan untuk menilai kemampuan model pada observasi yang tidak dilibatkan dalam pembentukan model. Banyaknya prediktor yang dipertahankan atau besarnya skor relevansi tidak dengan sendirinya menjamin kesalahan prediksi yang lebih rendah.
Dengan demikian, seleksi variabel sebaiknya dipahami sebagai proses memilih representasi prediktor yang sesuai dengan tujuan analisis dan karakteristik data. Hasil seleksi perlu diinterpretasikan berdasarkan asumsi, kriteria, serta mekanisme metode yang digunakan. Pada data empiris, prediktor yang terpilih menunjukkan relevansi menurut prosedur analisis tertentu dan tidak dapat langsung dinyatakan sebagai penyebab perubahan respons.
This practical demonstrates that no single variable selection approach consistently yields the best decision for every modeling problem. Selection results depend on analytical objectives, response types, predictor representations, the models used, and evaluation criteria. Differences in selected predictors should therefore be understood in terms of each method’s selection mechanism, rather than immediately treated as inconsistent findings.
5.1 Synthesis of Variable Selection Results
Under Filtering, each predictor is assessed individually through between-class differences, categorical dependence, discrimination ability, or information-based measures. The birthwt results show that ptl and lwt rank relatively consistently near the top, although their order varies with the relevance measure. This illustrates how marginal rankings depend on the aspect of the predictor–response relationship being measured.
Under Wrapper methods, Best Subset Selection evaluates coefficient combinations to identify models that satisfy a selection criterion. The BIC-selected regression model contains lwt, smoke, ht, and ui. Genetic Algorithm and Simulated Annealing are introduced as alternative search strategies for situations where an exhaustive search becomes computationally expensive due to a large number of possible subsets.
Boruta takes a different approach, comparing the importance of original predictors with randomized shadow features. In classification, Boruta confirms ptl, ht, and lwt, while in regression it confirms lwt, ptl, smoke, and ui. These differences show that relevance may change when the response is treated as a category rather than as a numerical value.
Under Embedded methods, Group LASSO selects predictors through the regularization of coefficient groups. Here, Group LASSO retains seven of the eight predictor groups in both regression and classification, excluding ftv. Unlike Best Subset, which can select individual dummy coefficients, Group LASSO treats all coefficients of a categorical predictor as a single group.
The results of the applied methods are summarized below.
| Method | Modeling Task | Main Result |
|---|---|---|
| Filtering | Classification | ptl and lwt frequently rank highest in relevance |
| Best Subset (BIC) | Regression | lwt, smoke, ht, ui |
| Boruta | Classification | ptl, ht, lwt |
| Boruta | Regression | lwt, ptl, smoke, ui; race is Tentative |
| Group LASSO | Regression | Seven selected groups; ftv excluded |
| Group LASSO | Classification | Seven selected groups; ftv excluded |
The table shows that lwt receives relatively consistent support across several approaches. Meanwhile, ptl ranks highly under a number of Filtering methods and is confirmed by Boruta for both tasks, but is absent from the BIC-selected Best Subset model. This difference demonstrates that individual relevance is not always equivalent to a predictor’s contribution within a particular multivariable model.
The number of selected predictors is also insufficient by itself to identify the best method. Best Subset seeks a balance between model fit and complexity, Boruta aims to identify all relevant predictors, and Group LASSO shrinks coefficient groups according to a regularization parameter. Their selection objectives are different.
5.2 Predictive Evaluation and Implications for Method Choice
Test-set evaluation shows that BIC-based Best Subset achieves an RMSE of 804.46 grams and MAE of 655.20 grams. Group LASSO regression achieves an RMSE of 783.99 grams and MAE of 623.28 grams. For the data split used, Group LASSO produces smaller prediction errors, although it retains more predictors.
For classification, Group LASSO achieves an AUC of 0.7147 and Balanced Accuracy of 0.6506. These results indicate better-than-random discrimination, although classification performance remains limited.
These comparisons require caution. Evaluation uses only one training–test split and therefore does not establish that a method is generally superior. In addition, the predictors selected by Boruta have not been evaluated through separate predictive models on the test data. Boruta selection decisions therefore cannot be compared directly with Best Subset or Group LASSO prediction errors.
In practice, the selection approach may be chosen according to the following objectives:
- Identifying initial predictor relevance: Filtering can rank predictors using statistical or information-based measures appropriate for the variable types.
- Searching for a predictor combination for a specific model: Best Subset can be used when the search space is manageable; metaheuristics may be considered for larger search spaces.
- Identifying all predictors relevant under a Random Forest-based approach: Boruta can be applied to regression and classification.
- Selecting predictors while preserving the structure of coefficient groups: Group LASSO is suitable when predictors, including categorical variables, are represented by one or more coefficients that should be selected together.
5.3 Key Takeaways
The practical leads to three key insights about variable selection.
First, selection results depend on the relevance measure and modeling objective. A predictor with a strong marginal relationship may not be retained when assessed jointly with other predictors. Similarly, categorical and numerical response formulations can produce different decisions from the same underlying data.
Second, predictor representation determines the unit of selection. Numerical predictors may be used directly or discretized according to a method’s requirements. Categorical predictors may be represented by multiple dummy coefficients, making it important to distinguish individual coefficient selection from selecting a whole variable as one group.
Third, variable selection and predictive evaluation are distinct stages. Selection uses the training data, while the test data assess predictive performance on previously unseen observations. Neither the number of retained predictors nor the magnitude of relevance scores guarantees lower prediction error.
Variable selection should therefore be viewed as choosing a predictor representation aligned with the analytical objective and characteristics of the data. Results must be interpreted in relation to the assumptions, criteria, and mechanisms of the methods employed. In empirical data, selected predictors show relevance under a particular procedure; they cannot automatically be identified as causes of changes in the response.
II · 6. Latihan Mandiri dan Diskusi KelompokII · 6. Independent Practice and Group Discussion
Gunakan data latihan dan diskusikan kesesuaian metode, bukan hanya jumlah prediktor terpilih.Use the practice datasets and discuss methodological appropriateness, not just the number of selected predictors.
Tujuan
Latihan ini bertujuan melatih mahasiswa menerapkan metode seleksi variabel pada dataset empiris yang berbeda dari contoh praktikum. Mahasiswa diharapkan dapat menentukan metode yang sesuai berdasarkan tipe respons dan prediktor, menginterpretasikan hasil seleksi, serta menjelaskan perbedaan keputusan antarmetode.
Dataset Latihan
Mahasiswa menggunakan salah satu dataset berikut sesuai pembagian kelompok:
| Dataset | Karakteristik | Contoh respons |
|---|---|---|
survey dari package MASS |
Data survei mahasiswa dengan prediktor numerik, kategorik, dan nilai hilang | Height untuk regresi atau Smoke untuk klasifikasi |
| German Credit Data | Data karakteristik pemohon kredit dengan respons kategorik biner | Class untuk klasifikasi risiko kredit |
Petunjuk Pengerjaan
Pelajari struktur dataset dan tentukan variabel respons serta kandidat prediktor. Periksa tipe variabel dan masalah kualitas data yang perlu ditangani.
Pilih minimal dua metode seleksi variabel dari pendekatan berbeda yang telah dibahas pada modul P8. Pemilihan metode harus mempertimbangkan tipe respons, tipe prediktor, serta kesesuaian metode.
Lakukan penyiapan data dan seleksi variabel menggunakan data latih. Gunakan data uji hanya untuk evaluasi akhir apabila membentuk model prediksi.
Bandingkan hasil seleksi kedua metode. Identifikasi prediktor yang konsisten terpilih, prediktor yang berbeda, dan kemungkinan alasan perbedaan tersebut.
Susun ringkasan temuan dan catat kendala yang ditemui selama analisis.
Diskusi pada Pertemuan Praktikum
Setiap mahasiswa diharapkan telah mencoba mengerjakan latihan sebelum pertemuan praktikum. Pada saat praktikum, mahasiswa mendiskusikan hasil pengerjaannya bersama anggota kelompok yang telah ditentukan sebelumnya.
Setelah diskusi internal, setiap kelompok menyampaikan temuan utama secara singkat di depan kelas, meliputi:
Karakteristik dataset dan alasan memilih metode.
Prediktor yang terpilih serta perbedaan hasil antarmetode.
Interpretasi, kendala, atau pertanyaan yang muncul selama analisis.
Penyampaian hasil dilakukan melalui diskusi singkat, bukan presentasi formal. Kelompok tidak diwajibkan membuat slide PowerPoint. Hasil analisis dapat ditunjukkan langsung melalui kode R, tabel, atau visualisasi yang telah dibuat.
Penilaian diskusi menekankan pemahaman konsep, kesesuaian metode, kemampuan menginterpretasikan hasil, dan partisipasi anggota kelompok, bukan semata-mata banyaknya metode yang dijalankan.
Objective
This exercise is designed to help students apply variable selection methods to empirical datasets different from the worked example. Students are expected to choose appropriate methods based on response and predictor types, interpret their selection results, and explain differences between the methods’ decisions.
Practice Datasets
Students use one of the following datasets according to their group assignments:
| Dataset | Characteristics | Example Response |
|---|---|---|
survey from the MASS package |
Student survey data containing numerical and categorical predictors and missing values | Height for regression or Smoke for classification |
| German Credit Data | Data on credit applicants with a binary categorical response | Class for credit-risk classification |
Instructions
Examine the structure of the dataset and identify the response variable and candidate predictors. Check variable types and data-quality issues requiring attention.
Choose at least two variable selection methods from different approaches covered in Practical 8. Consider the response type, predictor types, and methodological suitability when choosing the methods.
Prepare the data and perform variable selection using the training set. Use the test set only for final evaluation if a predictive model is fitted.
Compare the selection results of the two methods. Identify predictors consistently selected, predictors selected differently, and possible reasons for those differences.
Summarize your findings and note any difficulties encountered during the analysis.
Discussion During the Practical Session
Every student is expected to attempt the exercise before the practical session. During class, students discuss their results with members of the groups assigned previously.
After their internal discussions, each group briefly presents its main findings to the class, including:
Dataset characteristics and reasons for choosing the methods.
Selected predictors and differences between the methods’ results.
Interpretations, difficulties, or questions arising from the analysis.
The results are shared through a short discussion, not a formal presentation. Groups are not required to prepare PowerPoint slides. They may show relevant results directly through R code, tables, or previously created visualizations.
Discussion assessment emphasizes conceptual understanding, methodological appropriateness, interpretation of results, and participation by group members, rather than merely the number of methods implemented.