Classification and Regression Trees (CART) · Implementasi RStudio
Pada praktikum sebelumnya, kita telah mempelajari step function, yaitu pendekatan yang membagi rentang prediktor ke dalam beberapa interval dengan nilai prediksi konstan pada setiap interval. Pembagian ini memungkinkan hubungan antara prediktor dan respons direpresentasikan tanpa harus mengikuti satu bentuk kurva yang sama di seluruh rentang pengamatan.
Namun, bagaimana jika batas interval tersebut belum diketahui? Bagaimana jika pemisahan tidak cukup dilakukan berdasarkan satu prediktor, tetapi perlu mempertimbangkan beberapa karakteristik observasi sekaligus?
Persoalan ini dapat ditangani melalui Classification and Regression Trees (CART). Alih-alih menentukan batas pemisahan sejak awal, CART memilih prediktor dan titik pemisahannya berdasarkan data. Setiap pemisahan menghasilkan dua kelompok yang dapat dibagi kembali, hingga terbentuk struktur pohon dengan aturan keputusan dan nilai prediksi pada setiap terminal node.
Praktikum ini menggunakan lima package R untuk menyiapkan data, membangun dan memvisualisasikan model CART, serta mengevaluasi prediksi. Setiap package digunakan sesuai tahap analisisnya.
| Package | Fungsi dalam praktikum | Fungsi utama R |
|---|---|---|
| tidyverse | Mengolah data, menyiapkan prediktor, merangkum hasil, dan membuat visualisasi. | read_csv(), select(), mutate(), summarise(), ggplot() |
| rpart | Membentuk regression dan classification tree dengan CART serta mengendalikan kompleksitas model. | rpart(), rpart.control(), printcp(), plotcp(), prune(), predict() |
| rpart.plot | Menampilkan struktur pohon, aturan pemisahan, dan nilai prediksi pada terminal node. | rpart.plot() |
| caret | Melakukan cross-validation, membandingkan kompleksitas model, dan mengevaluasi prediksi. | train(), trainControl(), confusionMatrix(), postResample() |
| knitr | Menyajikan tabel ringkasan hasil analisis dalam dokumen Quarto. | kable() |
Instalasi cukup dijalankan satu kali apabila package belum tersedia.
#| eval: false
# Jalankan satu kali jika package belum terpasang.
install.packages(c(
"tidyverse",
"rpart",
"rpart.plot",
"caret",
"knitr"
))
# Dependensi pembagian train–test dari Praktikum 10
install.packages("rsample")Setelah package terpasang, aktifkan library yang digunakan selama praktikum.
#| message: false
#| warning: false
library(tidyverse)
library(rpart)
library(rpart.plot)
library(caret)
library(knitr)Fungsi rsample::initial_split(), rsample::training(), dan rsample::testing() dipanggil dengan namespace rsample::, tanpa menambah library utama.
CART merupakan metode supervised learning yang membagi ruang prediktor secara bertahap menjadi beberapa wilayah (regions). Setiap pemisahan membentuk dua cabang; hasil akhirnya berupa terminal nodes (leaves) yang digunakan untuk menghasilkan prediksi.
CART dapat digunakan untuk dua jenis respons:
| Regression Tree | Classification Tree |
|---|---|
| Respons numerik. | Respons kategorik. |
| Prediksi: rata-rata respons pada terminal node. | Prediksi: kelas dominan; probabilitas kelas juga dapat dihitung. |
| Kriteria pemisahan: jumlah kuadrat galat (RSS). | Kriteria pemisahan: Gini impurity atau entropy. |
Perhatikan hubungan antara wilayah prediktor, aturan keputusan, dan nilai prediksi dalam gambar berikut.
Pada gambar kiri atas, batas wilayah saling bertumpuk sehingga partisinya tidak dapat dibentuk dengan pemisahan biner rekursif yang memotong satu wilayah secara menyeluruh. Gambar kanan atas menunjukkan lima wilayah persegi panjang yang dapat dibentuk bertahap. Pohon di kiri bawah menyatakan urutan pemisahan yang sama, sedangkan permukaan di kanan bawah menunjukkan bahwa tiap wilayah memiliki satu tinggi prediksi yang konstan. Dengan demikian, tree, pembagian ruang, dan prediksi bertingkat merupakan tiga cara membaca model yang sama.
Dua jenis CART menggunakan cara pembentukan cabang yang sama, tetapi berbeda dalam cara menentukan pemisahan terbaik dan nilai prediksi di terminal node. Pembahasan dimulai dari regression tree dan RSS, dilanjutkan pruning, kemudian classification tree dengan Gini dan entropy.
Regression tree digunakan ketika respons bersifat numerik. Pohon menghasilkan prediksi konstan pada setiap terminal node, yaitu rata-rata respons observasi pelatihan yang masuk ke node tersebut. Contoh pemain bisbol berikut memperlihatkan bagaimana satu observasi ditelusuri dari root menuju prediksinya.
Gambar STATS 202 berikut menampilkan pohon regresi dan pembagian ruang Years–Hits untuk contoh prediksi logaritma gaji pemain bisbol. Kedua gambar memuat aturan pemisahan yang sama dalam bentuk berbeda.
Pada pohon di kiri, Years < 4,5 langsung menghasilkan prediksi 5,11 (wilayah R1). Pemain dengan Years ≥ 4,5 ditentukan lagi oleh Hits < 117,5: R2 memiliki prediksi 6,00 dan R3 sebesar 6,74. Garis vertikal dan horizontal pada gambar kanan adalah batas aturan yang sama. Nilai pada ujung pohon adalah rata-rata log salary observasi pelatihan pada wilayah tersebut, bukan nilai gaji individu yang tepat.
Nilai dihitung dari contoh pembelajaran yang dijelaskan di materi, bukan dari model Wine Quality.
Regression tree membentuk sejumlah wilayah (regions) melalui proses recursive binary splitting. Pada setiap pemisahan, algoritma memilih variabel prediktor dan titik pemisahan (cutpoint) yang menghasilkan dua kelompok dengan nilai respons paling homogen berdasarkan kriteria Residual Sum of Squares (RSS).
Ilustrasi STATS 202 sebelumnya memperlihatkan bagaimana partisi persegi panjang dapat diwakili oleh aturan pohon. Pada contoh berikut, pilih R1–R5 untuk memeriksa hubungan setiap wilayah terminal dengan proses pemisahan berurutan.
Nilai dihitung dari contoh pembelajaran yang dijelaskan di materi, bukan dari model Wine Quality.
Latihan membaca pembagian wilayah dan cabang pohon.
Pada setiap node, kandidat pemisahan berdasarkan prediktor Xj dan cutpoint s membentuk dua wilayah:
Dengan demikian, setiap observasi ditempatkan pada salah satu wilayah berdasarkan nilai prediktornya.
CART memilih variabel dan batas pemisahan yang memberikan pembagian terbaik menurut kriteria model. Untuk regression tree, nilai prediksi pada wilayah Rm merupakan rata-rata respons observasi pelatihan di wilayah tersebut:
Dalam persamaan tersebut, Rm adalah wilayah ke-m, Nm jumlah observasi di wilayah tersebut, xi nilai prediktor observasi ke-i, dan yi responsnya. Pembentukan regression tree memilih pemisahan yang meminimumkan jumlah kuadrat galat atau Residual Sum of Squares (RSS).
Pada regression tree, pemisahan terbaik ditentukan dengan meminimumkan jumlah kuadrat selisih antara respons aktual dan rata-rata respons dalam masing-masing kelompok.
Dalam persamaan tersebut, yi adalah respons aktual, xi adalah vektor prediktor observasi ke-i, Xj adalah prediktor ke-j, s adalah cutpoint, sedangkan ŷR1 dan ŷR2 adalah rata-rata respons di masing-masing wilayah.
Penurunan RSS akibat pemisahan dihitung menggunakan:
Split terbaik menghasilkan RSS setelah pemisahan paling kecil, atau penurunan RSS paling besar. Prosedur ini bersifat greedy karena setiap node memilih pemisahan terbaik berdasarkan kondisi saat itu, bukan mengevaluasi seluruh kemungkinan struktur pohon secara bersamaan.
Misalkan terdapat enam siswa dengan data hipotetis jam belajar dan nilai ujian berikut.
| Siswa | Jam Belajar (X) | Nilai Ujian (Y) |
|---|---|---|
| A | 1 | 40 |
| B | 2 | 42 |
| C | 3 | 44 |
| D | 4 | 70 |
| E | 5 | 72 |
| F | 6 | 74 |
Menghitung RSS pada Root Node
Sebelum dilakukan pemisahan, seluruh observasi berada dalam satu node. Prediksi awal merupakan rata-rata nilai ujian:
RSS awal dihitung sebagai:
Setiap selisih dikuadratkan, misalnya (40-57)2=289. Karena itu, RSS root adalah 289+225+169+169+225+289=1.366.
Menentukan Cutpoint Terbaik
Karena prediktor berupa angka, kandidat cutpoint diambil dari titik tengah antara dua nilai jam belajar yang berurutan.
| Cutpoint (s) | Observasi kiri | Observasi kanan | RSS setelah split |
|---|---|---|---|
| 1,5 | 1 | 5 | 1.019,2 |
| 2,5 | 2 | 4 | 598 |
| 3,5 (terbaik) | 3 | 3 | 16 |
| 4,5 | 4 | 2 | 598 |
| 5,5 | 5 | 1 | 1.019,2 |
Contoh pemeriksaan kandidat s=2,5: kelompok kiri berisi nilai 40 dan 42 (rata-rata 41), sedangkan kelompok kanan berisi 44, 70, 72, dan 74 (rata-rata 65).
Kandidat lainnya dihitung dengan cara yang sama. Nilai pada tabel dibandingkan untuk menentukan pemisahan dengan RSS terkecil.
Cutpoint 3,5 menghasilkan RSS terkecil sehingga dipilih sebagai pemisahan pertama.
Menghitung RSS Setelah Pemisahan
Kelompok kiri, X<3,5, terdiri atas nilai 40, 42, dan 44.
Kelompok kanan, X≥3,5, terdiri atas nilai 70, 72, dan 74.
Total RSS setelah pemisahan:
Penurunan RSS yang dihasilkan:
Hasil tersebut menunjukkan bahwa pemisahan pada jam belajar 3,5 menghasilkan dua kelompok dengan variasi nilai ujian yang jauh lebih kecil dibandingkan kelompok awal.
Setelah menghitung seluruh kandidat secara manual, ubah cutpoint untuk melihat perubahan rata-rata kedua kelompok, RSS, dan penurunan RSS. Perhitungan pada panel ini menggunakan enam siswa yang sama.
Nilai dihitung dari contoh pembelajaran yang dijelaskan di materi, bukan dari model Wine Quality.
Hasil pemisahan pertama membentuk dua kelompok dengan prediksi berbeda. Siswa yang belajar kurang dari 3,5 jam memiliki prediksi nilai ujian sebesar 42, sedangkan siswa dengan jam belajar setidaknya 3,5 jam memiliki prediksi sebesar 72.
Kedua nilai tersebut merupakan rata-rata respons pada masing-masing kelompok. Jika aturan pemisahan tidak dilanjutkan, kedua kelompok menjadi terminal nodes. Dalam pembentukan regression tree, proses pemisahan dapat diulangi pada node yang masih memenuhi kriteria pertumbuhan pohon.
Pohon dapat terus membagi observasi menjadi wilayah yang semakin kecil. Pada gambar STATS 202 berikut, pemisahan tidak berhenti pada Years dan Hits, tetapi melibatkan prediktor lain seperti RBI, Walks, dan Putouts. Bertambahnya cabang membuat model semakin rinci, tetapi kesalahan pada data pelatihan bukan satu-satunya ukuran kualitas prediksi.
Semakin banyak pemisahan, RSS pelatihan dapat semakin kecil. Namun, pohon yang terlalu kompleks berisiko mengalami overfitting: model mengikuti variasi khusus data latih dan belum tentu memprediksi data baru dengan baik. Pruning menyederhanakan pohon dengan menghapus cabang yang kontribusinya relatif kecil terhadap ketepatan prediksi.
Cost-complexity pruning (weakest-link pruning) membandingkan RSS dengan jumlah terminal node. Kriteria yang diminimumkan adalah:
Dalam persamaan ini, T adalah subtree yang diperiksa, |T| jumlah terminal node, Rm wilayah terminal node ke-m, dan α≥0 parameter penalti kompleksitas. Nilai ŷRm merupakan rata-rata respons pada wilayah tersebut.
Jika α=0, penalti ukuran pohon diabaikan. Semakin besar α, semakin besar biaya mempertahankan banyak terminal node, sehingga pohon lebih sederhana dapat dipilih meskipun RSS-nya sedikit meningkat.
Gunakan kembali enam siswa pada bagian Regression Tree, dengan nilai ujian 40, 42, 44, 70, 72, dan 74. Split pertama pada jam belajar 3,5 membentuk kelompok {40, 42, 44} dan {70, 72, 74}, dengan RSS total 16.
Sebagai ilustrasi, setiap kelompok kemudian dipisahkan sampai keenam siswa menjadi terminal node masing-masing. Untuk mempertahankan aturan pohon, cabang yang digabung kembali harus berasal dari node induk yang sama, bukan dipilih sembarangan.
Menghitung RSS saat cabang digabung
Awalnya terdapat enam terminal node. Karena setiap node hanya memuat satu siswa, prediksi sama dengan nilai aktual dan RSS pelatihan = 0.
Pertama, terminal node {40} dan {42} digabung. Prediksi kelompok baru adalah (40+42)/2=41, dengan RSS:
Pohon kini mempunyai lima terminal node dengan RSS total 2. Penggabungan berikutnya dilakukan pada {72} dan {74}; rata-ratanya 73 dan tambahan RSS-nya 2. Karena itu, pohon empat terminal node memiliki RSS 2+2=4.
Selanjutnya, {40, 42} digabung dengan {44}. Rata-rata kelompok {40, 42, 44} adalah 42 dan RSS-nya 8. Karena kelompok {72, 74} masih menyumbang RSS 2, total RSS pohon tiga terminal node menjadi 8+2=10.
Kelompok {70} kemudian digabung dengan {72, 74}. Rata-ratanya 72 dan RSS kelompok kanan menjadi 8. Dengan kelompok kiri yang juga memiliki RSS 8, diperoleh pohon dua terminal node dengan RSS 8+8=16.
Jika kedua kelompok terakhir digabung, hanya tersisa root node. Rata-rata seluruh nilai ujian menjadi 57 dan RSS kembali menjadi 1.366.
| Tahap | Terminal node yang digabung | Jumlah node | RSS total |
|---|---|---|---|
| Pohon awal | Masing-masing siswa terpisah | 6 | 0 |
| 6 → 5 | {40} + {42} → {40, 42} | 5 | 2 |
| 5 → 4 | {72} + {74} → {72, 74} | 4 | 4 |
| 4 → 3 | {40, 42} + {44} → {40, 42, 44} | 3 | 10 |
| 3 → 2 | {70} + {72, 74} → {70, 72, 74} | 2 | 16 |
| 2 → 1 | Dua kelompok terakhir digabung | 1 | 1.366 |
Urutan tersebut menggambarkan penghapusan cabang dari pohon besar. Penggabungan dengan kenaikan RSS per terminal node yang dihapus paling kecil diprioritaskan; pada contoh ini terdapat beberapa penggabungan dengan nilai kenaikan yang sama (tie).
Memilih pohon untuk penalti tertentu
Misalkan digunakan α=7 semata-mata untuk latihan. Untuk setiap kandidat, jumlahkan RSS dengan tujuh kali jumlah terminal node:
| Terminal node | RSS | Penalti 7|T| | Nilai C7(T) |
|---|---|---|---|
| 6 | 0 | 42 | 42 |
| 5 | 2 | 35 | 37 |
| 4 | 4 | 28 | 32 |
| 3 | 10 | 21 | 31 |
| 2 (terpilih) | 16 | 14 | 30 |
| 1 | 1.366 | 7 | 1.373 |
Sebagai contoh, perbandingan antara pohon enam dan dua terminal node adalah:
Nilai cost-complexity terkecil adalah 30, sehingga untuk α=7 dipilih pohon dengan dua terminal node. Pohon enam node mempunyai RSS pelatihan paling kecil, tetapi penalti kompleksitasnya lebih besar. Nilai α=7 adalah contoh perhitungan, bukan parameter optimal hasil validasi.
Nilai penalti dapat diubah pada contoh berikut untuk membandingkan subtree berdasarkan RSS dan jumlah terminal node. Pilihan pohon mengikuti nilai cost-complexity terkecil pada kandidat yang tersedia.
Nilai dihitung dari contoh pembelajaran yang dijelaskan di materi, bukan dari model Wine Quality.
Kurva hitam pada gambar menunjukkan galat pelatihan yang terus menurun saat ukuran pohon bertambah. Sebaliknya, galat cross-validation (hijau) mencapai titik rendah pada pohon yang relatif kecil, lalu cenderung meningkat atau mendatar. Kurva test (oranye) juga tidak harus mengikuti galat pelatihan. Artinya, memilih pohon hanya berdasarkan galat training dapat mempertahankan cabang yang tidak membantu generalisasi; tingkat kompleksitas dipilih menggunakan cross-validation.
Pohon akhir pada gambar berikut kembali memiliki tiga terminal node dengan batas Years = 4,5 dan Hits = 117,5. Hasil ini memperlihatkan bagaimana model yang lebih sederhana dapat dipertahankan setelah evaluasi kompleksitas; pemilihan parameter dilakukan tanpa menggunakan error test sebagai kriteria tuning.
Dalam cost-complexity pruning, pohon yang relatif besar dibentuk terlebih dahulu, lalu disederhanakan menjadi kandidat subtree. Parameter kompleksitas dipilih menggunakan K-fold cross-validation berdasarkan kesalahan prediksi pada data validasi.
Pada setiap fold, pohon dilatih dengan bagian data pelatihan, lalu dievaluasi pada bagian validasi. Untuk setiap kandidat α, nilai kesalahan antarfold dirata-ratakan:
MSEk(α) menyatakan mean squared error pada fold validasi ke-k. Parameter dengan rata-rata MSE validasi terkecil digunakan untuk memilih ukuran pohon. Data uji tetap terpisah dan hanya digunakan untuk mengevaluasi model yang sudah dipilih.
Nilai dihitung dari contoh pembelajaran yang dijelaskan di materi, bukan dari model Wine Quality.
Ilustrasi konseptual hubungan kompleksitas dan galat validasi. Grafik asli STATS 202 telah ditampilkan pada bagian pemilihan ukuran pohon.
Pada Ilustrasi interaktif berikut, kesalahan pelatihan (training MSE) terus menurun ketika pohon membesar. Sebaliknya, kesalahan cross-validation mencapai titik terendah pada pohon tiga terminal node dalam contoh ISLR, lalu meningkat atau relatif stabil. Kurva data uji tidak harus mencapai minimum pada ukuran pohon yang sama. Karena itu, kompleksitas dipilih dari hasil validasi, bukan dari RSS pelatihan yang paling kecil.
Dalam package rpart, pengendalian kompleksitas menggunakan parameter cp yang dinyatakan secara relatif terhadap galat root node. Nilai cp tidak identik secara numerik dengan α pada ilustrasi manual.
Classification tree membagi observasi melalui recursive binary splitting untuk menghasilkan node dengan komposisi kelas yang semakin homogen. Berbeda dari regression tree yang menggunakan RSS untuk meminimumkan variasi respons, classification tree memilih pemisahan berdasarkan ketidakmurnian kelas (node impurity).
| Aspek | Regression Tree | Classification Tree |
|---|---|---|
| Dasar pemilihan split | Nilai respons dalam satu node dibuat lebih berdekatan. | Proporsi kelas dalam satu node dibuat semakin homogen. |
| Kriteria pemisahan | RSS setelah split paling kecil. | Gini atau entropy tertimbang setelah split paling kecil. |
| Isi terminal node | Rata-rata nilai respons. | Proporsi tiap kelas serta kelas dengan proporsi terbesar. |
| Hasil prediksi | Nilai numerik dari rata-rata node. | Label kelas (serta estimasi peluang kelas dari proporsi node). |
Untuk node ke-m, proporsi kelas ke-k dihitung dari jumlah observasi kelas tersebut dibandingkan jumlah observasi dalam node:
Di sini nmk adalah jumlah observasi kelas ke-k, Nm adalah banyaknya observasi pada node, dan K adalah jumlah kelas.
Classification error rate menghitung proporsi observasi yang bukan kelas mayoritas:
Gini index dan entropy lebih peka terhadap perubahan komposisi kelas, sehingga lebih umum digunakan sebagai kriteria pemisahan:
Nilai Gini atau entropy sama dengan nol apabila seluruh observasi berada dalam satu kelas. Untuk entropy, digunakan logaritma natural dengan ketentuan 0log(0)=0.
Setiap kandidat split menghasilkan dua kelompok. Tingkat impurity keduanya digabung menggunakan bobot jumlah observasi; untuk Gini:
Split terbaik menghasilkan Gini tertimbang terkecil, atau penurunan Gini terbesar. Jika memakai entropy, perhitungan dilakukan dengan mengganti G1 dan G2 menggunakan entropy masing-masing kelompok.
Setelah memahami cara menghitung Gini, gunakan contoh kecil berikut untuk melihat bagaimana pemilihan cutpoint mengubah komposisi kelas, nilai Gini pada dua anak node, dan penurunan impurity. Hanya batas yang membentuk dua kelompok tak kosong yang layak dibandingkan.
Dua terminal node dari contoh Heart berikut sama-sama menghasilkan prediksi Yes, tetapi komposisi kelasnya berbeda.
Node A memuat 7 observasi Yes dan 4 No, sehingga proporsi Yes sebesar 63,6% dan Gini = 0,463. Node B memuat 9 observasi Yes tanpa kelas No (Gini = 0). Walaupun keduanya memprediksi Yes, komposisi Node B lebih homogen. Gini mengukur kemurnian kelas dalam node; nilainya tidak menunjukkan seberapa akurat pohon akan memprediksi data uji.
Nilai dihitung dari contoh pembelajaran yang dijelaskan di materi, bukan dari model Wine Quality.
Perbandingan dua node pada contoh Heart: keduanya memprediksi kelas Yes, tetapi komposisi kelasnya berbeda.
Gunakan delapan observasi hipotetis berikut. Data ini hanya untuk memahami proses pemilihan split, bukan dataset utama praktikum.
| Siswa | Jam belajar (X) | Status (Y) |
|---|---|---|
| A | 1 | Tidak Lulus |
| B | 2 | Tidak Lulus |
| C | 3 | Lulus |
| D | 4 | Tidak Lulus |
| E | 5 | Lulus |
| F | 6 | Lulus |
| G | 7 | Lulus |
| H | 8 | Lulus |
Menghitung Gini pada root node
Dari delapan siswa, terdapat 5 Lulus dan 3 Tidak Lulus. Maka proporsinya adalah pL=5/8=0,625 dan pT=3/8=0,375.
Mengevaluasi salah satu kandidat cutpoint
Misalkan diuji cutpoint s=4,5. Empat siswa di kiri memiliki 1 Lulus dan 3 Tidak Lulus, sedangkan empat siswa di kanan semuanya Lulus. Dengan demikian:
Karena jumlah observasi kiri dan kanan masing-masing empat, kontribusinya ditimbang dengan 4/8:
Pemisahan pada 4,5 menurunkan Gini dari 0,46875 menjadi 0,1875. Namun, batas ini harus dibandingkan dengan seluruh kandidat lain sebelum dipilih.
Membandingkan seluruh kandidat cutpoint
| Cutpoint | Kiri (L / TL) | Kanan (L / TL) | Gini tertimbang |
|---|---|---|---|
| 1,5 | 0 L / 1 TL | 5 L / 2 TL | 0,3571 |
| 2,5 | 0 L / 2 TL | 5 L / 1 TL | 0,2083 |
| 3,5 | 1 L / 2 TL | 4 L / 1 TL | 0,3667 |
| 4,5 (terbaik) | 1 L / 3 TL | 4 L / 0 TL | 0,1875 |
| 5,5 | 2 L / 3 TL | 3 L / 0 TL | 0,3000 |
| 6,5 | 3 L / 3 TL | 2 L / 0 TL | 0,3750 |
| 7,5 | 4 L / 3 TL | 1 L / 0 TL | 0,4286 |
Keterangan: L = Lulus dan TL = Tidak Lulus. Cutpoint 4,5 menghasilkan Gini tertimbang paling kecil, yakni 0,1875. Pada cutpoint 2,5 nilai Gini masih 0,2083, meskipun kedua split tersebut sama-sama hanya menyisakan satu kesalahan klasifikasi pada data pelatihan. Ini menunjukkan bahwa Gini lebih peka terhadap komposisi kelas daripada classification error.
Memeriksa cutpoint yang dipilih dengan entropy
Pada root node, entropy dihitung dari proporsi 5/8 dan 3/8:
Untuk cutpoint 4,5, kelompok kiri memiliki proporsi 1/4 dan 3/4, sedangkan kelompok kanan hanya memiliki kelas Lulus:
Pada contoh ini, cutpoint 4,5 juga memberikan entropy tertimbang terkecil dibandingkan kandidat lainnya. Kesamaan pilihan cutpoint tidak berarti Gini dan entropy selalu menghasilkan pohon identik pada seluruh dataset.
Nilai dihitung dari contoh pembelajaran yang dijelaskan di materi, bukan dari model Wine Quality.
Ilustrasi pembelajaran. Rekonstruksi hasil split pertama dari delapan observasi siswa hipotetis. Nilai pada node berasal dari perhitungan manual; bukan hasil pemodelan Wine Quality.
Siswa dengan jam belajar kurang dari 4,5 mengikuti cabang kiri dan diprediksi Tidak Lulus karena 3 dari 4 observasi dalam node tersebut termasuk kelas itu (75%). Siswa dengan jam belajar setidaknya 4,5 mengikuti cabang kanan dan diprediksi Lulus karena seluruh empat observasinya termasuk kelas Lulus (100%).
Angka 100% hanya menunjukkan proporsi kelas pada kelompok pelatihan dalam contoh hipotetis ini, bukan jaminan prediksi selalu benar pada data baru. Pada rpart, kriteria pemisahan klasifikasi bawaan adalah Gini, sedangkan entropy dapat dipilih melalui opsi information.
Setelah menghitung Gini pada delapan siswa dalam contoh klasifikasi di atas, kita dapat melihat bagaimana perubahan cutpoint memengaruhi proporsi kelas dan Gini tertimbang pada 16 observasi sintetis.
Geser batas alkohol pada 16 pengamatan sintetis. Perhatikan posisi titik, komposisi kelas, dan perubahan Gini tertimbang.
Penerapan CART menggunakan data Wine Quality mencakup enam tahap baseline dan eksplorasi parameter dengan 10-fold cross-validation. Grafik dan tabel merupakan hasil pemodelan RStudio yang telah dievaluasi pada data praktikum.
Dataset Wine Quality berasal dari UCI Machine Learning Repository dan memuat 6.497 observasi anggur vinho verde dari Portugal: 1.599 anggur merah dan 4.898 anggur putih. Dataset yang digunakan dalam praktikum ini memiliki 13 kolom, yaitu type (jenis anggur), 11 karakteristik fisikokimia—fixed acidity, volatile acidity, citric acid, residual sugar, chlorides, free sulfur dioxide, total sulfur dioxide, density, pH, sulphates, dan alcohol—serta quality, yakni skor penilaian sensoris. Sumber data dan penelitian terkait dijelaskan oleh Cortez et al. (2009).
Dua tugas CART menggunakan 12 prediktor yang sama. Regression tree memprediksi quality sebagai respons numerik, sedangkan classification tree memprediksi quality_class, yang dibentuk sebagai Not Good untuk quality < 6 dan Good untuk quality ≥ 6. Pada setiap model, respons model yang lain dikeluarkan dari prediktor untuk menghindari target leakage.
Sesuai prosedur Praktikum 10, observasi identik dihapus terlebih dahulu, lalu data dibagi secara stratifikasi menjadi 80% training dan 20% testing. Prediktor numerik digunakan pada skala asli dan type diperlakukan sebagai factor. Setiap hasil penyiapan data disajikan pada tab tersendiri di bawah blok kode.
Mulai dengan memahami distribusi kelas, memastikan data tidak mengandung nilai hilang, dan menghapus baris identik. Setelah itu, lakukan pembagian data dan siapkan dua respons yang berbeda.
wine_data <- wine_data %>%
mutate(quality_class = factor(
if_else(quality >= 6, "Good", "Not Good"),
levels = c("Not Good", "Good")
))
class_distribution <- wine_data %>%
count(quality_class, name = "frequency") %>%
mutate(percentage = round(100 * frequency / sum(frequency), 2))
knitr::kable(class_distribution,
caption = "Initial distribution of wine quality categories")
| Class | Count | Percent |
|---|---|---|
| Not Good | 2,384 | 36.69% |
| Good | 4,113 | 63.31% |
Interpretasi. Dari 6.497 observasi, kategori Not Good berjumlah 2.384 (36,69%) dan Good sebanyak 4.113 (63,31%). Distribusi ini dihitung sebelum penghapusan baris identik.
wine_data <- wine_data %>%
mutate(quality_class = factor(
if_else(quality >= 6, "Good", "Not Good"),
levels = c("Not Good", "Good")
))
class_distribution <- wine_data %>%
count(quality_class, name = "frequency") %>%
mutate(percentage = round(100 * frequency / sum(frequency), 2))
knitr::kable(class_distribution,
caption = "Initial distribution of wine quality categories")
missing_wine <- wine_data %>%
summarise(across(everything(), ~ sum(is.na(.x)))) %>%
pivot_longer(cols = everything(), names_to = "variable",
values_to = "missing_count")
knitr::kable(missing_wine, caption = "Missing values by variable")
| Variable | Missing |
|---|---|
| type | 0 |
| fixed acidity | 0 |
| volatile acidity | 0 |
| citric acid | 0 |
| residual sugar | 0 |
| chlorides | 0 |
| free sulfur dioxide | 0 |
| total sulfur dioxide | 0 |
| density | 0 |
| pH | 0 |
| sulphates | 0 |
| alcohol | 0 |
| quality | 0 |
| quality_class | 0 |
Interpretasi. Seluruh 14 variabel (termasuk quality_class yang dibentuk kemudian) tidak memiliki nilai hilang. Karena itu, tidak diperlukan imputasi sebelum model CART dibentuk.
wine_clean <- wine_data %>% distinct()
stopifnot(nrow(wine_clean) == 5320L)
duplicate_summary <- tibble(
stage = c("Before removal", "After removal"),
observations = c(nrow(wine_data), nrow(wine_clean))
)
knitr::kable(duplicate_summary,
caption = "Observations before and after duplicate removal")
| Tahap | Observasi |
|---|---|
| Sebelum penghapusan duplikasi | 6.497 |
| Sesudah penghapusan duplikasi | 5.320 |
Interpretasi. Jumlah observasi berkurang dari 6.497 menjadi 5.320 setelah 1.177 baris identik dihapus. Langkah ini dilakukan sebelum pemisahan train–test agar observasi yang identik tidak berada pada kedua subset.
wine_clean <- wine_data %>% distinct()
stopifnot(nrow(wine_clean) == 5320L)
duplicate_summary <- tibble(
stage = c("Before removal", "After removal"),
observations = c(nrow(wine_data), nrow(wine_clean))
)
knitr::kable(duplicate_summary,
caption = "Observations before and after duplicate removal")
wine_clean %>% count(quality_class, name = "frequency") %>%
mutate(percentage = round(100 * frequency / sum(frequency), 2)) %>%
knitr::kable(caption = "Class distribution after duplicate removal")
| Class | Count | Percent |
|---|---|---|
| Not Good | 1,988 | 37.37% |
| Good | 3,332 | 62.63% |
Interpretasi. Setelah penghapusan duplikasi, terdapat 1.988 Not Good (37,37%) dan 3.332 Good (62,63%). Kelas Good masih menjadi mayoritas, sehingga evaluasi klasifikasi tidak cukup ditentukan dari accuracy saja.
set.seed(123)
split_wine <- rsample::initial_split(
wine_clean, prop = 0.80, strata = quality_class)
wine_train <- rsample::training(split_wine)
wine_test <- rsample::testing(split_wine)
dim(wine_train)
dim(wine_test)
split_summary <- bind_rows(
wine_train %>% mutate(dataset = "Training"),
wine_test %>% mutate(dataset = "Testing")
) %>% count(dataset, quality_class, name = "frequency") %>%
group_by(dataset) %>%
mutate(percentage = round(100 * frequency / sum(frequency), 2)) %>%
ungroup()
knitr::kable(split_summary,
caption = "Class distribution in training and testing data")
| Subset | Not Good | Good | Total |
|---|---|---|---|
| Training | 1.590 (37,37%) | 2.665 (62,63%) | 4.255 |
| Testing | 398 (37,37%) | 667 (62,63%) | 1.065 |
Interpretasi. Pembagian stratifikasi mempertahankan persentase kedua kelas secara konsisten pada train dan test. Seluruh pemilihan parameter dilakukan dengan training, sedangkan testing tetap menjadi data evaluasi akhir.
reg_train <- wine_train %>% select(-quality_class) %>%
mutate(type = factor(type, levels = c("red", "white")))
reg_test <- wine_test %>% select(-quality_class) %>%
mutate(type = factor(type, levels = c("red", "white")))
cls_train <- wine_train %>% select(-quality) %>%
mutate(type = factor(type, levels = c("red", "white")),
quality_class = factor(quality_class,
levels = c("Not Good", "Good")))
cls_test <- wine_test %>% select(-quality) %>%
mutate(type = factor(type, levels = c("red", "white")),
quality_class = factor(quality_class,
levels = c("Not Good", "Good")))
stopifnot(
identical(names(reg_train), names(reg_test)),
identical(names(cls_train), names(cls_test)),
is.numeric(reg_train$quality),
is.factor(cls_train$quality_class),
!anyNA(reg_train), !anyNA(reg_test),
!anyNA(cls_train), !anyNA(cls_test)
)
data_summary <- tibble(
method = c("Regression", "Regression",
"Classification", "Classification"),
dataset = c("Training", "Testing", "Training", "Testing"),
observations = c(nrow(reg_train), nrow(reg_test),
nrow(cls_train), nrow(cls_test)),
predictors = c(ncol(reg_train)-1, ncol(reg_test)-1,
ncol(cls_train)-1, ncol(cls_test)-1)
)
knitr::kable(data_summary,
caption = "Final data preparation summary for CART")
| Metode | Subset | Observasi | Prediktor | Respons |
|---|---|---|---|---|
| Regression | Training | 4.255 | 12 | quality (numeric) |
| Regression | Testing | 1.065 | 12 | quality (numeric) |
| Classification | Training | 4.255 | 12 | quality_class (factor) |
| Classification | Testing | 1.065 | 12 | quality_class (factor) |
Interpretasi. Variabel quality_class dikeluarkan dari prediktor regression tree, dan quality dikeluarkan dari prediktor classification tree untuk mencegah target leakage. Prediktor type diperlakukan sebagai factor; semua prediktor numerik tetap menggunakan skala aslinya.
Kode lengkap ini menunjukkan urutan komputasi tahap tersebut. Jalankan tahapan mulai dari Data Preparation agar objek yang diperlukan telah tersedia.
# PRACTICUM 11 — DATA PREPARATION (continuation of P10)
library(tidyverse)
library(rpart)
library(rpart.plot)
library(caret)
library(knitr)
if (!requireNamespace("rsample", quietly = TRUE)) {
stop("Install package rsample terlebih dahulu.")
}
# Temukan CSV Praktikum 10 secara otomatis dalam project RStudio yang sama.
# Pencarian dimulai dari lokasi dokumen dan dilanjutkan di project Sains Data 2026.
find_p10_wine_csv <- function(filename = "wine-quality-white-and-red.csv") {
wd <- normalizePath(getwd(), winslash = "/", mustWork = TRUE)
# Urutkan folder dari working directory hingga induknya.
ancestors <- wd
current <- wd
repeat {
parent <- dirname(current)
if (identical(parent, current)) break
ancestors <- c(ancestors, parent)
current <- parent
}
# Utamakan project Sains Data 2026 yang sudah digunakan sejak P10.
named_project <- ancestors[
tolower(basename(ancestors)) == "sains data 2026"
]
if (length(named_project) > 0) {
project_root <- named_project[1]
} else {
has_rproj <- vapply(ancestors, function(d) {
length(list.files(d, pattern = "[.]Rproj$")) > 0
}, logical(1))
project_candidates <- ancestors[has_rproj]
project_root <- if (length(project_candidates) > 0) {
tail(project_candidates, 1)
} else {
wd
}
}
# Cari CSV di dalam project aktif, bukan di luar direktori project.
project_idx <- match(project_root, ancestors)
search_dirs <- if (is.na(project_idx)) wd else ancestors[seq_len(project_idx)]
direct <- file.path(search_dirs, filename)
direct <- direct[file.exists(direct)]
matches <- list.files(
project_root,
pattern = "^wine-quality-white-and-red[.]csv$",
recursive = TRUE,
full.names = TRUE,
ignore.case = TRUE
)
candidates <- unique(normalizePath(
c(direct, matches), winslash = "/", mustWork = FALSE
))
candidates <- candidates[file.exists(candidates)]
if (length(candidates) == 0) {
stop("CSV P10 tidak ditemukan di project: ", project_root,
". Simpan wine-quality-white-and-red.csv dalam folder project Sains Data 2026.")
}
# Dua berkas bernama sama tidak boleh diam-diam dianggap dataset identik.
if (length(candidates) > 1) {
signatures <- unname(tools::md5sum(candidates))
if (length(unique(signatures)) != 1) {
stop("Beberapa CSV P10 dengan isi berbeda ditemukan: ",
paste(candidates, collapse = " | "),
". Tentukan satu versi CSV P10 yang benar sebelum render.")
}
}
in_p10 <- grepl("praktikum[ _-]*10|p10", candidates, ignore.case = TRUE)
candidates <- candidates[order(!in_p10, nchar(candidates), candidates)]
normalizePath(candidates[1], winslash = "/", mustWork = TRUE)
}
file_path <- find_p10_wine_csv()
wine_data <- read_csv(file_path, show_col_types = FALSE)
# Menjaga kesesuaian dengan dataset P10 yang digunakan dalam modul.
stopifnot(
nrow(wine_data) == 6497L,
ncol(wine_data) == 13L,
identical(names(wine_data), c(
"type", "fixed acidity", "volatile acidity", "citric acid",
"residual sugar", "chlorides", "free sulfur dioxide",
"total sulfur dioxide", "density", "pH", "sulphates", "alcohol",
"quality"
)),
sum(wine_data$type == "red") == 1599L,
sum(wine_data$type == "white") == 4898L,
sum(wine_data$quality >= 6) == 4113L
)
head(wine_data)
dim(wine_data)
names(wine_data)
glimpse(wine_data)
wine_data <- wine_data %>%
mutate(quality_class = factor(
if_else(quality >= 6, "Good", "Not Good"),
levels = c("Not Good", "Good")
))
class_distribution <- wine_data %>%
count(quality_class, name = "frequency") %>%
mutate(percentage = round(100 * frequency / sum(frequency), 2))
knitr::kable(class_distribution,
caption = "Initial distribution of wine quality categories")
missing_wine <- wine_data %>%
summarise(across(everything(), ~ sum(is.na(.x)))) %>%
pivot_longer(cols = everything(), names_to = "variable",
values_to = "missing_count")
knitr::kable(missing_wine, caption = "Missing values by variable")
stopifnot(!anyNA(wine_data))
wine_clean <- wine_data %>% distinct()
stopifnot(nrow(wine_clean) == 5320L)
duplicate_summary <- tibble(
stage = c("Before removal", "After removal"),
observations = c(nrow(wine_data), nrow(wine_clean))
)
knitr::kable(duplicate_summary,
caption = "Observations before and after duplicate removal")
wine_clean %>% count(quality_class, name = "frequency") %>%
mutate(percentage = round(100 * frequency / sum(frequency), 2)) %>%
knitr::kable(caption = "Class distribution after duplicate removal")
set.seed(123)
split_wine <- rsample::initial_split(
wine_clean, prop = 0.80, strata = quality_class)
wine_train <- rsample::training(split_wine)
wine_test <- rsample::testing(split_wine)
dim(wine_train)
dim(wine_test)
split_summary <- bind_rows(
wine_train %>% mutate(dataset = "Training"),
wine_test %>% mutate(dataset = "Testing")
) %>% count(dataset, quality_class, name = "frequency") %>%
group_by(dataset) %>%
mutate(percentage = round(100 * frequency / sum(frequency), 2)) %>%
ungroup()
knitr::kable(split_summary,
caption = "Class distribution in training and testing data")
reg_train <- wine_train %>% select(-quality_class) %>%
mutate(type = factor(type, levels = c("red", "white")))
reg_test <- wine_test %>% select(-quality_class) %>%
mutate(type = factor(type, levels = c("red", "white")))
cls_train <- wine_train %>% select(-quality) %>%
mutate(type = factor(type, levels = c("red", "white")),
quality_class = factor(quality_class,
levels = c("Not Good", "Good")))
cls_test <- wine_test %>% select(-quality) %>%
mutate(type = factor(type, levels = c("red", "white")),
quality_class = factor(quality_class,
levels = c("Not Good", "Good")))
stopifnot(
identical(names(reg_train), names(reg_test)),
identical(names(cls_train), names(cls_test)),
is.numeric(reg_train$quality),
is.factor(cls_train$quality_class),
!anyNA(reg_train), !anyNA(reg_test),
!anyNA(cls_train), !anyNA(cls_test)
)
data_summary <- tibble(
method = c("Regression", "Regression",
"Classification", "Classification"),
dataset = c("Training", "Testing", "Training", "Testing"),
observations = c(nrow(reg_train), nrow(reg_test),
nrow(cls_train), nrow(cls_test)),
predictors = c(ncol(reg_train)-1, ncol(reg_test)-1,
ncol(cls_train)-1, ncol(cls_test)-1)
)
knitr::kable(data_summary,
caption = "Final data preparation summary for CART")
class(reg_train$quality)
class(cls_train$quality_class)
levels(cls_train$quality_class)
glimpse(reg_train)
glimpse(cls_train)
cat("\nDATA PREPARATION COMPLETED\n")Baseline regression tree menggunakan method = "anova", parameter cp = 0,01, minsplit = 20, minbucket = 7, dan 10-fold cross-validation internal. Struktur serta aturan node dibaca dari model yang sama.
Satu pohon baseline menghasilkan beberapa jenis keluaran: ringkasan struktur, aturan split, gambar pohon, dan RSS tiap node.
Bangun model baseline terlebih dahulu, periksa simpul dan aturan pemisahannya, lalu hubungkan struktur tersebut dengan gambar pohon dan besarnya RSS.
set.seed(123)
reg_tree <- rpart(
quality ~ ., data = reg_train, method = "anova",
control = rpart.control(
minsplit = 20, minbucket = 7, cp = 0.01, xval = 10
)
)
tree_frame <- reg_tree$frame
tree_structure <- tibble(
internal_nodes = sum(tree_frame$var != "<leaf>"),
terminal_nodes = sum(tree_frame$var == "<leaf>"),
total_nodes = nrow(tree_frame)
)
knitr::kable(tree_structure,
caption = "Initial regression tree structure")
| Internal nodes | Terminal nodes | Total nodes | Observasi training |
|---|---|---|---|
| 4 | 5 | 9 | 4.255 |
Interpretasi. Model awal membentuk empat internal node dan lima terminal node dari 4.255 data latih. Artinya, CART membagi ruang prediktor menjadi lima wilayah; setiap wilayah memberikan satu nilai prediksi kualitas. Nilai rata-rata pada root, 5,798, menjadi titik awal sebelum data dipisahkan.
set.seed(123)
reg_tree <- rpart(
quality ~ ., data = reg_train, method = "anova",
control = rpart.control(
minsplit = 20, minbucket = 7, cp = 0.01, xval = 10
)
)
print(reg_tree)
| Node akhir | Jalur pemisahan (ambang presisi) | # observasi | Prediksi quality |
|---|---|---|---|
| 4 | alcohol < 11,05833; volatile acidity ≥ 0,2825 | 1.520 | 5,338816 |
| 10 | alcohol < 10,11667; volatile acidity < 0,2825 | 807 | 5,629492 |
| 11 | 10,11667 ≤ alcohol < 11,05833; volatile acidity < 0,2825 | 590 | 6,011864 |
| 6 | 11,05833 ≤ alcohol < 11,92 | 660 | 6,124242 |
| 7 | alcohol ≥ 11,92 | 678 | 6,525074 |
Interpretasi. Pemisahan pertama terjadi pada kadar alcohol 11,05833. Cabang dengan alcohol lebih rendah memiliki rata-rata kualitas sekitar 5,555, sedangkan cabang di sebelah kanan sekitar 6,327. Pemisahan lanjutan menggunakan alcohol dan volatile acidity; prediksi terminal berada sekitar 5,339 hingga 6,525. Ini adalah pola prediktif dalam sampel, bukan bukti bahwa alkohol menyebabkan skor kualitas tertentu.
set.seed(123)
reg_tree <- rpart(
quality ~ ., data = reg_train, method = "anova",
control = rpart.control(
minsplit = 20, minbucket = 7, cp = 0.01, xval = 10
)
)
rpart.plot(
reg_tree, type = 2, extra = 101, under = TRUE,
fallen.leaves = TRUE, faclen = 0, digits = 3,
main = "Initial Regression Tree — Wine Quality"
)
Interpretasi. Diagram menunjukkan lima ujung pohon (terminal node), sehingga hanya ada lima nilai prediksi yang mungkin pada baseline. Amati bagaimana alcohol digunakan sebagai pemisah pertama, lalu alcohol dan volatile acidity menentukan cabang berikutnya. Pohon yang mudah dibaca ini menjadi pembanding ketika model tuned memiliki lebih banyak terminal node.
set.seed(123)
reg_tree <- rpart(
quality ~ ., data = reg_train, method = "anova",
control = rpart.control(
minsplit = 20, minbucket = 7, cp = 0.01, xval = 10
)
)
tree_frame <- reg_tree$frame
node_summary <- tibble(
node = as.integer(rownames(tree_frame)),
split_variable = tree_frame$var,
observations = tree_frame$n,
predicted_quality = round(tree_frame$yval, 3),
RSS = round(tree_frame$dev, 3)
)
knitr::kable(node_summary,
caption = "Regression tree node summary")
| Node | Jenis | n | RSS |
|---|---|---|---|
| 1 | Root | 4.255 | 3.285,585 |
| 4 | Leaf | 1.520 | 724,510 |
| 10 | Leaf | 807 | 428,218 |
| 11 | Leaf | 590 | 398,917 |
| 6 | Leaf | 660 | 489,812 |
| 7 | Leaf | 678 | 445,074 |
Interpretasi. RSS pada root sebesar 3.285,585 merupakan jumlah kuadrat galat jika seluruh data memperoleh satu prediksi rata-rata. Setelah lima wilayah dibentuk, jumlah RSS terminal menjadi 2.486,531, berkurang sekitar 799,054. Penurunan ini menggambarkan kecocokan pada data latih; manfaat prediktifnya tetap perlu diuji pada data yang tidak dipakai melatih model.
Kode lengkap ini menunjukkan urutan komputasi tahap tersebut. Jalankan tahapan mulai dari Data Preparation agar objek yang diperlukan telah tersedia.
# REGRESSION TREE — BASELINE
set.seed(123)
reg_tree <- rpart(
quality ~ ., data = reg_train, method = "anova",
control = rpart.control(
minsplit = 20, minbucket = 7, cp = 0.01, xval = 10
)
)
print(reg_tree)
reg_tree$control
tree_frame <- reg_tree$frame
tree_structure <- tibble(
internal_nodes = sum(tree_frame$var != "<leaf>"),
terminal_nodes = sum(tree_frame$var == "<leaf>"),
total_nodes = nrow(tree_frame)
)
knitr::kable(tree_structure,
caption = "Initial regression tree structure")
node_summary <- tibble(
node = as.integer(rownames(tree_frame)),
split_variable = tree_frame$var,
observations = tree_frame$n,
predicted_quality = round(tree_frame$yval, 3),
RSS = round(tree_frame$dev, 3)
)
knitr::kable(node_summary,
caption = "Regression tree node summary")
rpart.plot(
reg_tree, type = 2, extra = 101, under = TRUE,
fallen.leaves = TRUE, faclen = 0, digits = 3,
main = "Initial Regression Tree — Wine Quality"
)Tabel kompleksitas dan cross-validation digunakan untuk menentukan subtree dengan xerror minimum. Pruning diterapkan pada baseline tanpa melibatkan data uji.
Perhitungan CP dan pruning menggunakan objek baseline yang sama. Setiap tab menampilkan bagian hasil yang berbeda.
Baca tabel CP dan kesalahan cross-validation terlebih dahulu. Setelah CP terpilih, bandingkan pohon sebelum dan sesudah pruning.
printcp(reg_tree)
reg_cp_table <- reg_tree$cptable
knitr::kable(round(reg_cp_table, 5),
caption = "Complexity parameter table — Regression Tree")
| CP | nsplit | rel error | xerror | xstd |
|---|---|---|---|---|
| 0,16638 | 0 | 1,00000 | 1,00046 | 0,02309 |
| 0,04530 | 1 | 0,83362 | 0,85649 | 0,02216 |
| 0,01635 | 2 | 0,78832 | 0,80259 | 0,02145 |
| 0,01517 | 3 | 0,77197 | 0,79260 | 0,02117 |
| 0,01000 | 4 | 0,75680 | 0,77728 | 0,02076 |
Interpretasi. Kolom nsplit bertambah dari 0 sampai 4, sementara xerror cenderung menurun. Nilai xerror terendah pada tabel adalah 0,77728 untuk empat split (lima terminal node) dengan cp = 0,01. Karena xerror berbentuk galat relatif, angkanya tidak boleh langsung disamakan dengan RMSE data uji.
plotcp(reg_tree, minline = TRUE)
title(main = "Regression Tree — Cross-Validation Error")
Interpretasi. Grafik memvisualisasikan isi CP table: kesalahan validasi relatif menurun ketika subtree bertambah kompleks hingga lima terminal node. Titik minimum yang tersedia pada kurva merupakan dasar pemilihan CP; grafik ini tidak membuktikan bahwa pohon yang semakin besar selalu lebih baik.
best_cp_index <- which.min(reg_cp_table[, "xerror"])
best_cp <- reg_cp_table[best_cp_index, "CP"]
cp_selection <- tibble(
selected_cp = best_cp,
nsplit = reg_cp_table[best_cp_index, "nsplit"],
terminal_nodes = nsplit + 1,
relative_error = reg_cp_table[best_cp_index, "rel error"],
cv_error = reg_cp_table[best_cp_index, "xerror"],
cv_std = reg_cp_table[best_cp_index, "xstd"]
)
knitr::kable(cp_selection, digits = 5,
caption = "Selected CP based on minimum CV error")
| Selected CP | Split | Terminal nodes | Relative error | CV error | xstd |
|---|---|---|---|---|---|
| 0,01000 | 4 | 5 | 0,75680 | 0,77728 | 0,02076 |
Interpretasi. Parameter yang terpilih adalah cp = 0,01 karena menghasilkan minimum xerror di antara kandidat subtree baseline. Hasil ini tidak menyimpulkan bahwa lima terminal node merupakan struktur terbaik dari seluruh kemungkinan konfigurasi hyperparameter.
best_cp_index <- which.min(reg_cp_table[, "xerror"])
best_cp <- reg_cp_table[best_cp_index, "CP"]
cp_selection <- tibble(
selected_cp = best_cp,
nsplit = reg_cp_table[best_cp_index, "nsplit"],
terminal_nodes = nsplit + 1,
relative_error = reg_cp_table[best_cp_index, "rel error"],
cv_error = reg_cp_table[best_cp_index, "xerror"],
cv_std = reg_cp_table[best_cp_index, "xstd"]
)
knitr::kable(cp_selection, digits = 5,
caption = "Selected CP based on minimum CV error")
reg_tree_pruned <- prune(reg_tree, cp = best_cp)
print(reg_tree_pruned)
rpart.plot(
reg_tree_pruned, type = 2, extra = 101,
under = TRUE, fallen.leaves = TRUE,
faclen = 0, digits = 3,
main = "Pruned Regression Tree — Wine Quality"
)
Interpretasi. Gambar pohon setelah pruning sama dengan baseline: masih ada lima terminal node dan aturan pemisahan utamanya tidak berubah. Hal ini terjadi karena cp = 0,01 sudah memilih subtree paling kompleks yang tersedia pada lintasan CP baseline. Tidak adanya cabang yang terhapus merupakan hasil pemilihan model yang sah, bukan kesalahan fungsi prune().
best_cp_index <- which.min(reg_cp_table[, "xerror"])
best_cp <- reg_cp_table[best_cp_index, "CP"]
cp_selection <- tibble(
selected_cp = best_cp,
nsplit = reg_cp_table[best_cp_index, "nsplit"],
terminal_nodes = nsplit + 1,
relative_error = reg_cp_table[best_cp_index, "rel error"],
cv_error = reg_cp_table[best_cp_index, "xerror"],
cv_std = reg_cp_table[best_cp_index, "xstd"]
)
knitr::kable(cp_selection, digits = 5,
caption = "Selected CP based on minimum CV error")
reg_tree_pruned <- prune(reg_tree, cp = best_cp)
print(reg_tree_pruned)
rpart.plot(
reg_tree_pruned, type = 2, extra = 101,
under = TRUE, fallen.leaves = TRUE,
faclen = 0, digits = 3,
main = "Pruned Regression Tree — Wine Quality"
)
tree_info <- function(model, label) {
frame <- model$frame
is_leaf <- frame$var == "<leaf>"
tibble(
model = label,
internal_nodes = sum(!is_leaf),
terminal_nodes = sum(is_leaf),
total_nodes = nrow(frame),
training_RSS = sum(frame$dev[is_leaf])
)
}
tree_comparison <- bind_rows(
tree_info(reg_tree, "Initial Tree"),
tree_info(reg_tree_pruned, "Pruned Tree")
)
| Model | Internal nodes | Terminal nodes | Total nodes | Training RSS |
|---|---|---|---|---|
| Initial Tree | 4 | 5 | 9 | 2.486,531 |
| Pruned Tree | 4 | 5 | 9 | 2.486,531 |
Interpretasi. RSS training dan jumlah terminal node identik sebelum dan sesudah pruning. Tidak ada pemilihan ulang CP berdasarkan hasil testing; eksplorasi kompleksitas yang lebih luas dilakukan terpisah setelah keenam tahapan baseline selesai.
Kode lengkap ini menunjukkan urutan komputasi tahap tersebut. Jalankan tahapan mulai dari Data Preparation agar objek yang diperlukan telah tersedia.
# TREE COMPLEXITY AND PRUNING
printcp(reg_tree)
reg_cp_table <- reg_tree$cptable
knitr::kable(round(reg_cp_table, 5),
caption = "Complexity parameter table — Regression Tree")
plotcp(reg_tree, minline = TRUE)
title(main = "Regression Tree — Cross-Validation Error")
best_cp_index <- which.min(reg_cp_table[, "xerror"])
best_cp <- reg_cp_table[best_cp_index, "CP"]
cp_selection <- tibble(
selected_cp = best_cp,
nsplit = reg_cp_table[best_cp_index, "nsplit"],
terminal_nodes = nsplit + 1,
relative_error = reg_cp_table[best_cp_index, "rel error"],
cv_error = reg_cp_table[best_cp_index, "xerror"],
cv_std = reg_cp_table[best_cp_index, "xstd"]
)
knitr::kable(cp_selection, digits = 5,
caption = "Selected CP based on minimum CV error")
reg_tree_pruned <- prune(reg_tree, cp = best_cp)
print(reg_tree_pruned)
rpart.plot(
reg_tree_pruned, type = 2, extra = 101,
under = TRUE, fallen.leaves = TRUE,
faclen = 0, digits = 3,
main = "Pruned Regression Tree — Wine Quality"
)
tree_info <- function(model, label) {
frame <- model$frame
is_leaf <- frame$var == "<leaf>"
tibble(
model = label,
internal_nodes = sum(!is_leaf),
terminal_nodes = sum(is_leaf),
total_nodes = nrow(frame),
training_RSS = sum(frame$dev[is_leaf])
)
}
tree_comparison <- bind_rows(
tree_info(reg_tree, "Initial Tree"),
tree_info(reg_tree_pruned, "Pruned Tree")
)
knitr::kable(tree_comparison, digits = 3,
caption = "Regression Tree complexity before/after pruning")
if (tree_comparison$terminal_nodes[1] ==
tree_comparison$terminal_nodes[2]) {
cat("Pruning mempertahankan ukuran pohon baseline.\n")
} else {
cat("Pruning menghasilkan pohon yang lebih sederhana.\n")
}Prediksi model terpilih dievaluasi pada 1.065 observasi testing dengan RMSE, MAE, dan R². Grafik aktual–prediksi menunjukkan hubungan antara skor asli dan hasil prediksi.
Evaluasi dilakukan setelah kompleksitas model dipilih, tanpa menggunakan data testing untuk memilih parameter.
Mulai dari prediksi beberapa observasi, lanjutkan dengan metrik pada data uji, kemudian gunakan grafik untuk melihat pola kesalahan yang tidak tampak dalam satu angka.
reg_pred <- predict(reg_tree_pruned, newdata = reg_test, type = "vector")
reg_results <- tibble(
actual = reg_test$quality,
predicted = as.numeric(reg_pred)
) %>% mutate(residual = actual - predicted)
stopifnot(nrow(reg_results) == nrow(reg_test),
all(is.finite(reg_results$predicted)))
knitr::kable(head(reg_results, 10), digits = 3,
caption = "First 10 regression predictions on test data")
| Actual | Predicted | Residual |
|---|---|---|
| 6 | 5,629 | 0,371 |
| 5 | 5,339 | −0,339 |
| 6 | 5,629 | 0,371 |
| 6 | 6,012 | −0,012 |
| 4 | 5,339 | −1,339 |
| 7 | 6,525 | 0,475 |
| 7 | 6,525 | 0,475 |
| 5 | 5,339 | −0,339 |
| 6 | 5,339 | 0,661 |
| 5 | 5,629 | −0,629 |
Interpretasi. Tabel mempertemukan skor aktual, skor yang diprediksi pohon, dan residual pada observasi data uji. Residual positif berarti skor aktual lebih tinggi daripada prediksi; residual negatif berarti prediksi terlalu tinggi. Nilai prediksi yang berulang adalah konsekuensi lima terminal node, bukan pembulatan acak.
reg_pred <- predict(reg_tree_pruned, newdata = reg_test, type = "vector")
reg_results <- tibble(
actual = reg_test$quality,
predicted = as.numeric(reg_pred)
) %>% mutate(residual = actual - predicted)
stopifnot(nrow(reg_results) == nrow(reg_test),
all(is.finite(reg_results$predicted)))
knitr::kable(head(reg_results, 10), digits = 3,
caption = "First 10 regression predictions on test data")
actual <- reg_results$actual
predicted <- reg_results$predicted
rmse <- sqrt(mean((actual - predicted)^2))
mae <- mean(abs(actual - predicted))
r2 <- 1 - sum((actual - predicted)^2) /
sum((actual - mean(actual))^2)
reg_metrics <- tibble(
model = "Regression Tree (Baseline + Pruning)",
RMSE = rmse, MAE = mae, R2 = r2
)
knitr::kable(reg_metrics, digits = 4,
caption = "Regression Tree performance on test data")
| Model | RMSE | MAE | R² |
|---|---|---|---|
| Regression Tree Baseline + Pruning | 0,7733 | 0,6067 | 0,2338 |
Interpretasi. Pada data uji, RMSE = 0,7733 lebih besar daripada MAE = 0,6067 karena RMSE memberi bobot lebih besar kepada kesalahan ekstrem. R² = 0,2338 menunjukkan model hanya mengurangi sebagian galat kuadrat dibanding pembanding konstan pada data uji. Kinerja ini menjadi baseline yang nantinya dibandingkan dengan grid search.
reg_pred <- predict(reg_tree_pruned, newdata = reg_test, type = "vector")
reg_results <- tibble(
actual = reg_test$quality,
predicted = as.numeric(reg_pred)
) %>% mutate(residual = actual - predicted)
stopifnot(nrow(reg_results) == nrow(reg_test),
all(is.finite(reg_results$predicted)))
knitr::kable(head(reg_results, 10), digits = 3,
caption = "First 10 regression predictions on test data")
actual <- reg_results$actual
predicted <- reg_results$predicted
rmse <- sqrt(mean((actual - predicted)^2))
mae <- mean(abs(actual - predicted))
r2 <- 1 - sum((actual - predicted)^2) /
sum((actual - mean(actual))^2)
reg_metrics <- tibble(
model = "Regression Tree (Baseline + Pruning)",
RMSE = rmse, MAE = mae, R2 = r2
)
knitr::kable(reg_metrics, digits = 4,
caption = "Regression Tree performance on test data")
reg_plot <- ggplot(reg_results,
aes(x = actual, y = predicted)) +
geom_point(alpha = 0.25, size = 1.6) +
geom_abline(intercept = 0, slope = 1, linetype = "dashed") +
labs(title = "Actual vs Predicted Wine Quality",
subtitle = "Baseline Regression Tree — Test Data",
x = "Actual Quality", y = "Predicted Quality") +
theme_minimal(base_size = 12)
print(reg_plot)
Interpretasi. Titik-titik membentuk lima jalur horizontal karena setiap observasi dalam terminal node yang sama menerima satu nilai prediksi. Nilai skor aktual lebih menyebar, sehingga ada kecenderungan model menarik skor rendah dan tinggi ke tengah. Garis diagonal membantu melihat seberapa jauh prediksi menyimpang dari skor sebenarnya.
Kode lengkap ini menunjukkan urutan komputasi tahap tersebut. Jalankan tahapan mulai dari Data Preparation agar objek yang diperlukan telah tersedia.
# REGRESSION TREE — TEST EVALUATION
reg_pred <- predict(reg_tree_pruned, newdata = reg_test, type = "vector")
reg_results <- tibble(
actual = reg_test$quality,
predicted = as.numeric(reg_pred)
) %>% mutate(residual = actual - predicted)
stopifnot(nrow(reg_results) == nrow(reg_test),
all(is.finite(reg_results$predicted)))
knitr::kable(head(reg_results, 10), digits = 3,
caption = "First 10 regression predictions on test data")
actual <- reg_results$actual
predicted <- reg_results$predicted
rmse <- sqrt(mean((actual - predicted)^2))
mae <- mean(abs(actual - predicted))
r2 <- 1 - sum((actual - predicted)^2) /
sum((actual - mean(actual))^2)
reg_metrics <- tibble(
model = "Regression Tree (Baseline + Pruning)",
RMSE = rmse, MAE = mae, R2 = r2
)
knitr::kable(reg_metrics, digits = 4,
caption = "Regression Tree performance on test data")
reg_plot <- ggplot(reg_results,
aes(x = actual, y = predicted)) +
geom_point(alpha = 0.25, size = 1.6) +
geom_abline(intercept = 0, slope = 1, linetype = "dashed") +
labs(title = "Actual vs Predicted Wine Quality",
subtitle = "Baseline Regression Tree — Test Data",
x = "Actual Quality", y = "Predicted Quality") +
theme_minimal(base_size = 12)
print(reg_plot)
reg_pred_initial <- predict(reg_tree, newdata = reg_test,
type = "vector")
identical(as.numeric(reg_pred_initial), as.numeric(reg_pred))Dua baseline classification tree dibangun menggunakan Gini dan Entropy pada data training yang sama. Kriteria impurity berbeda, sementara parameter pertumbuhan dan pembagian data dipertahankan sama.
Gini dan entropy sama-sama membentuk pohon biner; perbedaan kriteria terlihat pada struktur dan proporsi kelas di terminal node.
Periksa struktur kedua model, baca masing-masing gambar pohon, kemudian telaah probabilitas pada terminal node. Perbedaan bentuk pohon tidak otomatis menentukan mana yang paling akurat.
set.seed(123)
cls_tree_gini <- rpart(
quality_class ~ ., data = cls_train, method = "class",
parms = list(split = "gini"),
control = rpart.control(
minsplit = 20, minbucket = 7, cp = 0.01, xval = 10
)
)
set.seed(123)
cls_tree_entropy <- rpart(
quality_class ~ ., data = cls_train, method = "class",
parms = list(split = "information"),
control = rpart.control(
minsplit = 20, minbucket = 7, cp = 0.01, xval = 10
)
)
class_tree_info <- function(model, label) {
frame <- model$frame
is_leaf <- frame$var == "<leaf>"
tibble(model = label, internal_nodes = sum(!is_leaf),
terminal_nodes = sum(is_leaf), total_nodes = nrow(frame))
}
cls_structure <- bind_rows(
class_tree_info(cls_tree_gini, "Gini"),
class_tree_info(cls_tree_entropy, "Entropy")
)
knitr::kable(cls_structure,
caption = "Baseline classification tree structures")
| Model | Internal nodes | Terminal nodes | Total nodes | Root split |
|---|---|---|---|---|
| Gini | 2 | 3 | 5 | alcohol |
| Entropy | 5 | 6 | 11 | alcohol |
Interpretasi. Kedua model menggunakan alcohol < 10,01667 sebagai split pertama, tetapi pohon Gini hanya mempunyai tiga terminal node sedangkan entropy mempunyai enam. Kesamaan root menunjukkan dua kriteria mengenali pemisahan awal yang serupa; perbedaan cabang menunjukkan kriteria impurity dapat memilih keputusan selanjutnya secara berbeda.
set.seed(123)
cls_tree_gini <- rpart(
quality_class ~ ., data = cls_train, method = "class",
parms = list(split = "gini"),
control = rpart.control(
minsplit = 20, minbucket = 7, cp = 0.01, xval = 10
)
)
set.seed(123)
cls_tree_entropy <- rpart(
quality_class ~ ., data = cls_train, method = "class",
parms = list(split = "information"),
control = rpart.control(
minsplit = 20, minbucket = 7, cp = 0.01, xval = 10
)
)
rpart.plot(cls_tree_gini, type = 2, extra = 104,
under = TRUE, fallen.leaves = TRUE,
faclen = 0, digits = 3,
main = "Classification Tree — Gini Index")
Interpretasi. Pada cabang alcohol rendah, volatile acidity digunakan untuk membedakan wilayah dengan komposisi kelas berbeda. Pohon Gini menghasilkan tiga terminal node, sehingga keputusan akhirnya relatif sederhana. Label kelas pada tiap ujung menunjukkan kelas mayoritas observasi latih di wilayah tersebut, bukan kepastian bahwa semua observasinya termasuk kelas itu.
set.seed(123)
cls_tree_gini <- rpart(
quality_class ~ ., data = cls_train, method = "class",
parms = list(split = "gini"),
control = rpart.control(
minsplit = 20, minbucket = 7, cp = 0.01, xval = 10
)
)
set.seed(123)
cls_tree_entropy <- rpart(
quality_class ~ ., data = cls_train, method = "class",
parms = list(split = "information"),
control = rpart.control(
minsplit = 20, minbucket = 7, cp = 0.01, xval = 10
)
)
rpart.plot(cls_tree_entropy, type = 2, extra = 104,
under = TRUE, fallen.leaves = TRUE,
faclen = 0, digits = 3,
main = "Classification Tree — Entropy")
Interpretasi. Pohon entropy memulai dari batas alcohol yang sama, tetapi melanjutkan lebih banyak split hingga enam terminal node. Variabel lanjutan meliputi volatile acidity, free sulfur dioxide, dan sulphates. Struktur yang lebih rinci dapat membedakan kelompok tambahan, namun nilai tambahnya harus dinilai dari confusion matrix dan metrik uji.
set.seed(123)
cls_tree_gini <- rpart(
quality_class ~ ., data = cls_train, method = "class",
parms = list(split = "gini"),
control = rpart.control(
minsplit = 20, minbucket = 7, cp = 0.01, xval = 10
)
)
set.seed(123)
cls_tree_entropy <- rpart(
quality_class ~ ., data = cls_train, method = "class",
parms = list(split = "information"),
control = rpart.control(
minsplit = 20, minbucket = 7, cp = 0.01, xval = 10
)
)
class_leaf_summary <- function(model, label) {
frame <- model$frame
is_leaf <- frame$var == "<leaf>"
node_values <- frame$yval2
tibble(
model = label,
node = as.integer(rownames(frame)[is_leaf]),
observations = frame$n[is_leaf],
predicted_class = levels(cls_train$quality_class)[
frame$yval[is_leaf]
],
prob_not_good = round(node_values[is_leaf, 4], 4),
prob_good = round(node_values[is_leaf, 5], 4)
)
}
cls_leaf_summary <- bind_rows(
class_leaf_summary(cls_tree_gini, "Gini"),
class_leaf_summary(cls_tree_entropy, "Entropy")
)
knitr::kable(cls_leaf_summary,
caption = "Predicted class and probabilities at terminal nodes")
| Model | Node | n | Kelas | P(Not Good) | P(Good) |
|---|---|---|---|---|---|
| Gini | 4 | 1.361 | Not Good | 0,6694 | 0,3306 |
| Gini | 5 | 407 | Good | 0,3366 | 0,6634 |
| Gini | 3 | 2.487 | Good | 0,2179 | 0,7821 |
| Entropy | 4 | 1.230 | Not Good | 0,6854 | 0,3146 |
| Entropy | 5 | 538 | Good | 0,3810 | 0,6190 |
| Entropy | 24 | 209 | Not Good | 0,6220 | 0,3780 |
| Entropy | 25 | 204 | Good | 0,2843 | 0,7157 |
| Entropy | 13 | 1.277 | Good | 0,2349 | 0,7651 |
| Entropy | 7 | 797 | Good | 0,0678 | 0,9322 |
Interpretasi. Kelas prediksi ditentukan oleh proporsi terbesar dalam node. Nilai yprob adalah komposisi kelas pada observasi training, bukan tingkat kepastian yang sudah dikalibrasi. Kolom loss pada print(classification tree) menunjukkan jumlah kesalahan apabila semua observasi node diberikan kelas mayoritas; loss bukan nilai Gini atau Entropy.
Kode lengkap ini menunjukkan urutan komputasi tahap tersebut. Jalankan tahapan mulai dari Data Preparation agar objek yang diperlukan telah tersedia.
# CLASSIFICATION TREE — GINI AND ENTROPY
set.seed(123)
cls_tree_gini <- rpart(
quality_class ~ ., data = cls_train, method = "class",
parms = list(split = "gini"),
control = rpart.control(
minsplit = 20, minbucket = 7, cp = 0.01, xval = 10
)
)
set.seed(123)
cls_tree_entropy <- rpart(
quality_class ~ ., data = cls_train, method = "class",
parms = list(split = "information"),
control = rpart.control(
minsplit = 20, minbucket = 7, cp = 0.01, xval = 10
)
)
print(cls_tree_gini)
print(cls_tree_entropy)
cls_tree_gini$parms
cls_tree_entropy$parms
class_tree_info <- function(model, label) {
frame <- model$frame
is_leaf <- frame$var == "<leaf>"
tibble(model = label, internal_nodes = sum(!is_leaf),
terminal_nodes = sum(is_leaf), total_nodes = nrow(frame))
}
cls_structure <- bind_rows(
class_tree_info(cls_tree_gini, "Gini"),
class_tree_info(cls_tree_entropy, "Entropy")
)
knitr::kable(cls_structure,
caption = "Baseline classification tree structures")
rpart.plot(cls_tree_gini, type = 2, extra = 104,
under = TRUE, fallen.leaves = TRUE,
faclen = 0, digits = 3,
main = "Classification Tree — Gini Index")
rpart.plot(cls_tree_entropy, type = 2, extra = 104,
under = TRUE, fallen.leaves = TRUE,
faclen = 0, digits = 3,
main = "Classification Tree — Entropy")
class_leaf_summary <- function(model, label) {
frame <- model$frame
is_leaf <- frame$var == "<leaf>"
node_values <- frame$yval2
tibble(
model = label,
node = as.integer(rownames(frame)[is_leaf]),
observations = frame$n[is_leaf],
predicted_class = levels(cls_train$quality_class)[
frame$yval[is_leaf]
],
prob_not_good = round(node_values[is_leaf, 4], 4),
prob_good = round(node_values[is_leaf, 5], 4)
)
}
cls_leaf_summary <- bind_rows(
class_leaf_summary(cls_tree_gini, "Gini"),
class_leaf_summary(cls_tree_entropy, "Entropy")
)
knitr::kable(cls_leaf_summary,
caption = "Predicted class and probabilities at terminal nodes")Kinerja kedua pohon klasifikasi dinilai melalui confusion matrix serta Accuracy, Precision, Recall, F1-score, dan Specificity. Kelas positif adalah Good.
Confusion matrix dibaca dengan kelas Good sebagai positif. Setiap tabel dan interpretasinya berada dalam tab tersendiri.
Perhatikan probabilitas dan kelas hasil prediksi, baca confusion matrix dari kedua model, kemudian bandingkan metrik yang menggambarkan pengenalan kelas Good dan Not Good.
cls_pred_gini <- predict(cls_tree_gini, newdata = cls_test,
type = "class")
cls_prob_gini <- predict(cls_tree_gini, newdata = cls_test,
type = "prob")
cls_pred_entropy <- predict(cls_tree_entropy, newdata = cls_test,
type = "class")
cls_prob_entropy <- predict(cls_tree_entropy,
newdata = cls_test, type = "prob")
stopifnot(
length(cls_pred_gini) == nrow(cls_test),
length(cls_pred_entropy) == nrow(cls_test),
identical(levels(cls_pred_gini), levels(cls_test$quality_class)),
identical(levels(cls_pred_entropy), levels(cls_test$quality_class)),
all(is.finite(cls_prob_gini)),
all(is.finite(cls_prob_entropy))
)
cls_results <- tibble(
actual = cls_test$quality_class,
predicted_gini = cls_pred_gini,
prob_good_gini = cls_prob_gini[, "Good"],
predicted_entropy = cls_pred_entropy,
prob_good_entropy = cls_prob_entropy[, "Good"]
)
knitr::kable(head(cls_results, 10), digits = 4,
caption = "First 10 classification predictions on test data")
| Actual | Pred. Gini | P(Good) Gini | Pred. Entropy | P(Good) Entropy |
|---|---|---|---|---|
| Good | Good | 0,7821 | Good | 0,7651 |
| Not Good | Not Good | 0,3306 | Not Good | 0,3146 |
| Good | Not Good | 0,3306 | Not Good | 0,3146 |
| Good | Good | 0,7821 | Good | 0,7651 |
| Not Good | Not Good | 0,3306 | Not Good | 0,3146 |
| Good | Good | 0,7821 | Good | 0,9322 |
| Good | Good | 0,7821 | Good | 0,9322 |
| Not Good | Not Good | 0,3306 | Not Good | 0,3146 |
| Good | Not Good | 0,3306 | Not Good | 0,3146 |
| Not Good | Not Good | 0,3306 | Not Good | 0,3146 |
Interpretasi. Dua pohon dapat memprediksi kelas yang sama tetapi memberikan proporsi Good berbeda, karena terminal node dan komposisinya tidak identik. Misalnya pada observasi keenam, Gini memberikan P(Good) 0,7821 dan Entropy 0,9322, keduanya tetap memprediksi Good.
cls_pred_gini <- predict(cls_tree_gini, newdata = cls_test,
type = "class")
cls_prob_gini <- predict(cls_tree_gini, newdata = cls_test,
type = "prob")
cm_gini <- caret::confusionMatrix(
data = cls_pred_gini,
reference = cls_test$quality_class,
positive = "Good", mode = "everything"
)
cat("\nCLASSIFICATION TREE — GINI\n")
print(cm_gini)
| Prediksi \ Aktual | Not Good | Good |
|---|---|---|
| Not Good | 231 (TN) | 122 (FN) |
| Good | 167 (FP) | 545 (TP) |
Interpretasi. Dari 667 anggur Good pada data uji, Gini mengklasifikasikan 545 dengan benar dan melewatkan 122. Sebaliknya, dari 398 anggur Not Good, sebanyak 231 dikenali dengan benar. Karena lebih baik mengenali Good daripada Not Good, recall Good (81,71%) lebih tinggi daripada specificity (58,04%).
cls_pred_entropy <- predict(cls_tree_entropy, newdata = cls_test,
type = "class")
cls_prob_entropy <- predict(cls_tree_entropy,
newdata = cls_test, type = "prob")
cm_entropy <- caret::confusionMatrix(
data = cls_pred_entropy,
reference = cls_test$quality_class,
positive = "Good", mode = "everything"
cat("\nCLASSIFICATION TREE — ENTROPY\n")
print(cm_entropy)
| Prediksi \ Aktual | Not Good | Good |
|---|---|---|
| Not Good | 246 (TN) | 134 (FN) |
| Good | 152 (FP) | 533 (TP) |
Interpretasi. Entropy mengklasifikasikan 533 dari 667 anggur Good dengan benar, lebih sedikit daripada Gini (545). Namun entropy mengenali 246 dari 398 anggur Not Good, lebih banyak daripada Gini (231). Tabel ini memperlihatkan pertukaran kemampuan mengenali dua kelas yang tidak terlihat apabila hanya membaca accuracy.
cls_pred_gini <- predict(cls_tree_gini, newdata = cls_test,
type = "class")
cls_prob_gini <- predict(cls_tree_gini, newdata = cls_test,
type = "prob")
cls_pred_entropy <- predict(cls_tree_entropy, newdata = cls_test,
type = "class")
cls_prob_entropy <- predict(cls_tree_entropy,
newdata = cls_test, type = "prob")
stopifnot(
length(cls_pred_gini) == nrow(cls_test),
length(cls_pred_entropy) == nrow(cls_test),
identical(levels(cls_pred_gini), levels(cls_test$quality_class)),
identical(levels(cls_pred_entropy), levels(cls_test$quality_class)),
all(is.finite(cls_prob_gini)),
all(is.finite(cls_prob_entropy))
)
cls_results <- tibble(
actual = cls_test$quality_class,
predicted_gini = cls_pred_gini,
prob_good_gini = cls_prob_gini[, "Good"],
predicted_entropy = cls_pred_entropy,
prob_good_entropy = cls_prob_entropy[, "Good"]
)
knitr::kable(head(cls_results, 10), digits = 4,
caption = "First 10 classification predictions on test data")
cm_gini <- caret::confusionMatrix(
data = cls_pred_gini,
reference = cls_test$quality_class,
positive = "Good", mode = "everything"
)
cm_entropy <- caret::confusionMatrix(
data = cls_pred_entropy,
reference = cls_test$quality_class,
positive = "Good", mode = "everything"
)
cat("\nCLASSIFICATION TREE — GINI\n")
print(cm_gini)
cat("\nCLASSIFICATION TREE — ENTROPY\n")
print(cm_entropy)
get_class_metrics <- function(cm, model_name) {
tibble(
model = model_name,
Accuracy = unname(cm$overall["Accuracy"]),
Precision = unname(cm$byClass["Precision"]),
Recall = unname(cm$byClass["Recall"]),
F1_score = unname(cm$byClass["F1"]),
Specificity = unname(cm$byClass["Specificity"])
)
}
cls_metrics <- bind_rows(
get_class_metrics(cm_gini, "Gini"),
get_class_metrics(cm_entropy, "Entropy")
)
knitr::kable(cls_metrics, digits = 4,
| Metrik | Gini | Entropy |
|---|---|---|
| Accuracy | 0,7286 | 0,7315 |
| Precision | 0,7654 | 0,7781 |
| Recall | 0,8171 | 0,7991 |
| F1-score | 0,7904 | 0,7885 |
| Specificity | 0,5804 | 0,6181 |
| Balanced Accuracy | 0,6987 | 0,7086 |
Interpretasi. Entropy sedikit unggul dalam accuracy (0,7315 vs 0,7286), precision, dan specificity (0,6181 vs 0,5804). Gini sedikit unggul pada recall Good (0,8171 vs 0,7991) dan F1. Tidak ada pemenang mutlak untuk seluruh ukuran; penilaian tergantung apakah kesalahan pada kelas Not Good atau Good lebih menjadi perhatian.
Kode lengkap ini menunjukkan urutan komputasi tahap tersebut. Jalankan tahapan mulai dari Data Preparation agar objek yang diperlukan telah tersedia.
# CLASSIFICATION TREE — TEST EVALUATION
cls_pred_gini <- predict(cls_tree_gini, newdata = cls_test,
type = "class")
cls_prob_gini <- predict(cls_tree_gini, newdata = cls_test,
type = "prob")
cls_pred_entropy <- predict(cls_tree_entropy, newdata = cls_test,
type = "class")
cls_prob_entropy <- predict(cls_tree_entropy,
newdata = cls_test, type = "prob")
stopifnot(
length(cls_pred_gini) == nrow(cls_test),
length(cls_pred_entropy) == nrow(cls_test),
identical(levels(cls_pred_gini), levels(cls_test$quality_class)),
identical(levels(cls_pred_entropy), levels(cls_test$quality_class)),
all(is.finite(cls_prob_gini)),
all(is.finite(cls_prob_entropy))
)
cls_results <- tibble(
actual = cls_test$quality_class,
predicted_gini = cls_pred_gini,
prob_good_gini = cls_prob_gini[, "Good"],
predicted_entropy = cls_pred_entropy,
prob_good_entropy = cls_prob_entropy[, "Good"]
)
knitr::kable(head(cls_results, 10), digits = 4,
caption = "First 10 classification predictions on test data")
cm_gini <- caret::confusionMatrix(
data = cls_pred_gini,
reference = cls_test$quality_class,
positive = "Good", mode = "everything"
)
cm_entropy <- caret::confusionMatrix(
data = cls_pred_entropy,
reference = cls_test$quality_class,
positive = "Good", mode = "everything"
)
cat("\nCLASSIFICATION TREE — GINI\n")
print(cm_gini)
cat("\nCLASSIFICATION TREE — ENTROPY\n")
print(cm_entropy)
get_class_metrics <- function(cm, model_name) {
tibble(
model = model_name,
Accuracy = unname(cm$overall["Accuracy"]),
Precision = unname(cm$byClass["Precision"]),
Recall = unname(cm$byClass["Recall"]),
F1_score = unname(cm$byClass["F1"]),
Specificity = unname(cm$byClass["Specificity"])
)
}
cls_metrics <- bind_rows(
get_class_metrics(cm_gini, "Gini"),
get_class_metrics(cm_entropy, "Entropy")
)
knitr::kable(cls_metrics, digits = 4,
caption = "Baseline Classification Tree performance on test data")Eksplorasi menggabungkan cp, minsplit, minbucket, dan maxdepth dalam full grid search. Sepuluh fold yang sama digunakan untuk seluruh model; konfigurasi terpilih dilatih kembali pada seluruh training, kemudian dibandingkan dengan baseline pada data testing.
Seluruh konfigurasi grid dan fold ditentukan sekali, sehingga evaluasi ketiga model dapat dibandingkan pada partisi training yang identik.
Tetapkan kombinasi hyperparameter dan sepuluh fold yang sama untuk ketiga model. Hasil benchmark membantu memperlihatkan mengapa kompleksitas komputasi perlu dikelola.
param_grid <- expand.grid(
cp = c(0, 0.0005, 0.001, 0.003, 0.005, 0.01, 0.02, 0.05),
minsplit = c(10, 20, 40, 80),
minbucket = c(5, 7, 15),
maxdepth = c(3, 5, 8, 15, 30)
) %>% as_tibble() %>%
filter(minsplit >= 2 * minbucket) %>%
arrange(cp, minsplit, minbucket, maxdepth) %>%
mutate(configuration = row_number())
nrow(param_grid)
param_grid %>% filter(
cp == 0.01, minsplit == 20,
minbucket == 7, maxdepth == 30
)
compute_summary <- tibble(
models = c("Regression", "Gini", "Entropy"),
configurations = nrow(param_grid),
cv_folds = 10, total_fits = configurations * cv_folds
)
knitr::kable(compute_summary,
caption = "Grid search computational workload")
| Model | Konfigurasi | CV folds | Fit total |
|---|---|---|---|
| Regression | 360 | 10 | 3.600 |
| Gini | 360 | 10 | 3.600 |
| Entropy | 360 | 10 | 3.600 |
| Total | 1.080 set konfigurasi | — | 10.800 |
Interpretasi. Grid awal 480 kombinasi disaring menjadi 360 kombinasi per model. Konfigurasi baseline (cp = 0,01; minsplit = 20; minbucket = 7; maxdepth = 30) tercakup sebagai konfigurasi 240. Jumlah fit besar, sehingga digunakan benchmark dan checkpoint pada eksekusi penuh.
stopifnot(nrow(reg_train) == nrow(cls_train))
set.seed(2026)
cv_folds <- caret::createFolds(
cls_train$quality_class, k = 10,
list = TRUE, returnTrain = FALSE
)
fold_summary <- tibble(
fold = names(cv_folds),
validation_size = lengths(cv_folds)
)
knitr::kable(fold_summary,
caption = "Fixed 10-fold cross-validation allocation")
stopifnot(identical(
sort(unlist(cv_folds, use.names = FALSE)),
seq_len(nrow(cls_train))
))
| Fold | Ukuran validasi |
|---|---|
| Fold01 | 426 |
| Fold02 | 425 |
| Fold03 | 426 |
| Fold04 | 425 |
| Fold05 | 426 |
| Fold06 | 426 |
| Fold07 | 425 |
| Fold08 | 425 |
| Fold09 | 426 |
| Fold10 | 425 |
Interpretasi. Lima fold berisi 426 observasi dan lima fold berisi 425 observasi. Semua 4.255 training observations menjadi data validasi tepat satu kali. Indeks fold yang sama digunakan untuk Regression, Gini, dan Entropy agar perbandingan konfigurasi dilakukan pada partisi yang sepadan.
pilot_grid <- tibble(
configuration = c("Complex", "Medium", "Simple"),
cp = c(0, 0.005, 0.05),
minsplit = c(10L, 20L, 80L),
minbucket = c(5L, 7L, 15L),
maxdepth = c(30L, 8L, 3L)
)
pilot_train_ids <- setdiff(
seq_len(nrow(cls_train)), cv_folds[[1]]
)
benchmark_tree <- function(spec, model_name) {
is_regression <- model_name == "Regression"
train_data <- if (is_regression) {
reg_train[pilot_train_ids, , drop = FALSE]
} else {
cls_train[pilot_train_ids, , drop = FALSE]
}
control_params <- rpart.control(
cp = spec$cp, minsplit = spec$minsplit,
minbucket = spec$minbucket, maxdepth = spec$maxdepth,
xval = 0
)
start_time <- proc.time()[["elapsed"]]
if (is_regression) {
fit <- rpart(quality ~ ., data = train_data,
method = "anova", control = control_params)
} else {
split_method <- if (model_name == "Gini") "gini" else "information"
fit <- rpart(quality_class ~ ., data = train_data,
method = "class", parms = list(split = split_method),
control = control_params)
}
elapsed <- proc.time()[["elapsed"]] - start_time
tibble(configuration = spec$configuration,
model = model_name, elapsed_seconds = elapsed,
terminal_nodes = sum(fit$frame$var == "<leaf>"))
}
benchmark_results <- bind_rows(lapply(
seq_len(nrow(pilot_grid)), function(i) {
spec <- pilot_grid[i, ]
bind_rows(lapply(c("Regression", "Gini", "Entropy"),
function(m) benchmark_tree(spec, m)))
}
))
knitr::kable(benchmark_results, digits = 4,
caption = "Computational benchmark for CART configurations")
| Konfigurasi | Regresi: node (detik) | Gini: node (detik) | Entropy: node (detik) |
|---|---|---|---|
| Complex | 573 (0,37) | 261 (0,22) | 305 (0,19) |
| Medium | 14 (0,12) | 7 (0,44) | 9 (0,17) |
| Simple | 2 (0,15) | 3 (0,22) | 3 (0,14) |
Interpretasi. Pengaturan kompleks menghasilkan ratusan terminal node, sedangkan pengaturan sederhana hanya dua atau tiga. Hasil ini membuktikan rentang grid cukup luas untuk menampilkan variasi struktur pohon; waktu benchmark tidak boleh diperlakukan sebagai estimasi pasti total runtime.
Kode lengkap ini menunjukkan urutan komputasi tahap tersebut. Jalankan tahapan mulai dari Data Preparation agar objek yang diperlukan telah tersedia.
# PARAMETER EXPLORATION — GRID AND BENCHMARK
param_grid <- expand.grid(
cp = c(0, 0.0005, 0.001, 0.003, 0.005, 0.01, 0.02, 0.05),
minsplit = c(10, 20, 40, 80),
minbucket = c(5, 7, 15),
maxdepth = c(3, 5, 8, 15, 30)
) %>% as_tibble() %>%
filter(minsplit >= 2 * minbucket) %>%
arrange(cp, minsplit, minbucket, maxdepth) %>%
mutate(configuration = row_number())
nrow(param_grid)
param_grid %>% filter(
cp == 0.01, minsplit == 20,
minbucket == 7, maxdepth == 30
)
compute_summary <- tibble(
models = c("Regression", "Gini", "Entropy"),
configurations = nrow(param_grid),
cv_folds = 10, total_fits = configurations * cv_folds
)
knitr::kable(compute_summary,
caption = "Grid search computational workload")
stopifnot(nrow(reg_train) == nrow(cls_train))
set.seed(2026)
cv_folds <- caret::createFolds(
cls_train$quality_class, k = 10,
list = TRUE, returnTrain = FALSE
)
fold_summary <- tibble(
fold = names(cv_folds),
validation_size = lengths(cv_folds)
)
knitr::kable(fold_summary,
caption = "Fixed 10-fold cross-validation allocation")
stopifnot(identical(
sort(unlist(cv_folds, use.names = FALSE)),
seq_len(nrow(cls_train))
))
pilot_grid <- tibble(
configuration = c("Complex", "Medium", "Simple"),
cp = c(0, 0.005, 0.05),
minsplit = c(10L, 20L, 80L),
minbucket = c(5L, 7L, 15L),
maxdepth = c(30L, 8L, 3L)
)
pilot_train_ids <- setdiff(
seq_len(nrow(cls_train)), cv_folds[[1]]
)
benchmark_tree <- function(spec, model_name) {
is_regression <- model_name == "Regression"
train_data <- if (is_regression) {
reg_train[pilot_train_ids, , drop = FALSE]
} else {
cls_train[pilot_train_ids, , drop = FALSE]
}
control_params <- rpart.control(
cp = spec$cp, minsplit = spec$minsplit,
minbucket = spec$minbucket, maxdepth = spec$maxdepth,
xval = 0
)
start_time <- proc.time()[["elapsed"]]
if (is_regression) {
fit <- rpart(quality ~ ., data = train_data,
method = "anova", control = control_params)
} else {
split_method <- if (model_name == "Gini") "gini" else "information"
fit <- rpart(quality_class ~ ., data = train_data,
method = "class", parms = list(split = split_method),
control = control_params)
}
elapsed <- proc.time()[["elapsed"]] - start_time
tibble(configuration = spec$configuration,
model = model_name, elapsed_seconds = elapsed,
terminal_nodes = sum(fit$frame$var == "<leaf>"))
}
benchmark_results <- bind_rows(lapply(
seq_len(nrow(pilot_grid)), function(i) {
spec <- pilot_grid[i, ]
bind_rows(lapply(c("Regression", "Gini", "Entropy"),
function(m) benchmark_tree(spec, m)))
}
))
knitr::kable(benchmark_results, digits = 4,
caption = "Computational benchmark for CART configurations")Grid search menyimpan hasil per batch agar komputasi dapat dilanjutkan jika sesi RStudio terputus.
Jalankan seluruh kombinasi pada training fold, simpan hasil per batch, lalu pastikan semua evaluasi yang direncanakan selesai sebelum memilih konfigurasi.
# FULL GRID SEARCH — 360 CONFIGURATIONS x 10 FOLDS x 3
stopifnot(
nrow(param_grid) == 360,
length(cv_folds) == 10,
nrow(reg_train) == nrow(cls_train),
identical(sort(unlist(cv_folds, use.names = FALSE)),
seq_len(nrow(reg_train))),
identical(reg_train$quality >= 6,
cls_train$quality_class == "Good")
)
grid_dir <- "P11_Grid_Search_Results"
dir.create(grid_dir, showWarnings = FALSE, recursive = TRUE)
evaluate_grid_fold <- function(spec, model_name, fold_id) {
is_regression <- model_name == "Regression"
data_model <- if (is_regression) reg_train else cls_train
validation_id <- cv_folds[[fold_id]]
training_id <- setdiff(seq_len(nrow(data_model)), validation_id)
train_fold <- data_model[training_id, , drop = FALSE]
valid_fold <- data_model[validation_id, , drop = FALSE]
control_params <- rpart.control(
cp = spec$cp, minsplit = spec$minsplit,
minbucket = spec$minbucket, maxdepth = spec$maxdepth,
xval = 0
)
start_time <- proc.time()[["elapsed"]]
if (is_regression) {
fit <- rpart(quality ~ ., data = train_fold,
method = "anova", control = control_params)
} else {
split_method <- if (model_name == "Gini") "gini" else "information"
fit <- rpart(quality_class ~ ., data = train_fold,
method = "class", parms = list(split = split_method),
control = control_params)
}
fit_seconds <- proc.time()[["elapsed"]] - start_time
frame <- fit$frame
is_leaf <- frame$var == "<leaf>"
node_ids <- as.integer(rownames(frame))
result <- tibble(
model = model_name, configuration = spec$configuration,
fold = fold_id, cp = spec$cp,
minsplit = spec$minsplit, minbucket = spec$minbucket,
maxdepth = spec$maxdepth, terminal_nodes = sum(is_leaf),
tree_depth = max(floor(log2(node_ids))),
fit_seconds = fit_seconds,
rmse = NA_real_, mae = NA_real_,
balanced_accuracy = NA_real_, accuracy = NA_real_,
precision = NA_real_, recall = NA_real_,
f1_score = NA_real_, specificity = NA_real_
)
if (is_regression) {
predicted <- as.numeric(
predict(fit, newdata = valid_fold, type = "vector"))
actual <- valid_fold$quality
result$rmse <- sqrt(mean((actual - predicted)^2))
result$mae <- mean(abs(actual - predicted))
} else {
predicted <- as.character(
predict(fit, newdata = valid_fold, type = "class"))
actual <- as.character(valid_fold$quality_class)
tp <- sum(predicted == "Good" & actual == "Good")
tn <- sum(predicted == "Not Good" & actual == "Not Good")
fp <- sum(predicted == "Good" & actual == "Not Good")
fn <- sum(predicted == "Not Good" & actual == "Good")
recall <- tp / (tp + fn)
specificity <- tn / (tn + fp)
precision <- if ((tp + fp) > 0) tp / (tp + fp) else 0
f1 <- if ((precision + recall) > 0) {
2 * precision * recall / (precision + recall)
} else 0
result$balanced_accuracy <- (recall + specificity) / 2
result$accuracy <- (tp + tn) / length(actual)
result$precision <- precision
result$recall <- recall
result$f1_score <- f1
result$specificity <- specificity
}
return(result)
}
run_grid_model <- function(model_name, batch_size = 20) {
stopifnot(model_name %in% c("Regression", "Gini", "Entropy"))
checkpoint_file <- file.path(
grid_dir, paste0("cv_", tolower(model_name), ".rds"))
if (file.exists(checkpoint_file)) {
checkpoint <- readRDS(checkpoint_file)
stopifnot(
identical(checkpoint$grid, param_grid),
identical(checkpoint$folds, cv_folds),
identical(checkpoint$model, model_name)
)
results <- checkpoint$results
message("Melanjutkan ", model_name, " dari checkpoint.")
} else {
results <- tibble()
}
completed_ids <- unique(results$configuration)
remaining_ids <- setdiff(param_grid$configuration, completed_ids)
if (length(remaining_ids) == 0) {
message(model_name, ": seluruh konfigurasi sudah selesai.")
return(results)
}
batches <- split(
remaining_ids,
ceiling(seq_along(remaining_ids) / batch_size)
)
for (b in seq_along(batches)) {
batch_results <- bind_rows(lapply(batches[[b]], function(config_id) {
spec <- param_grid %>% filter(configuration == config_id)
bind_rows(lapply(seq_along(cv_folds), function(k) {
evaluate_grid_fold(spec = spec,
model_name = model_name, fold_id = k)
}))
}))
results <- bind_rows(results, batch_results)
saveRDS(list(model = model_name, grid = param_grid,
folds = cv_folds, results = results),
checkpoint_file)
completed_count <- length(unique(results$configuration))
message(model_name, ": ", completed_count, " / ",
nrow(param_grid), " konfigurasi selesai.")
}
return(results)
}
reg_grid_raw <- run_grid_model("Regression", batch_size = 20)
gini_grid_raw <- run_grid_model("Gini", batch_size = 20)
entropy_grid_raw <- run_grid_model("Entropy", batch_size = 20)
grid_completion <- tibble(
model = c("Regression", "Gini", "Entropy"),
records = c(nrow(reg_grid_raw), nrow(gini_grid_raw),
nrow(entropy_grid_raw))
) %>% mutate(expected = nrow(param_grid) * length(cv_folds),
complete = records == expected)
knitr::kable(grid_completion,
caption = "Full grid search completion check")
stopifnot(all(grid_completion$complete))
| Model | Konfigurasi | Fold | Baris hasil CV | Complete |
|---|---|---|---|---|
| Regression | 360 | 10 | 3.600 | TRUE |
| Gini | 360 | 10 | 3.600 | TRUE |
| Entropy | 360 | 10 | 3.600 | TRUE |
Interpretasi. Sebanyak 10.800 evaluasi fold dijalankan melalui 360 konfigurasi pada masing-masing model. Setiap hasil CV tersimpan terpisah dari testing; sehingga konfigurasi terbaik dapat dipilih tanpa menggunakan informasi data uji.
# FULL GRID SEARCH — 360 CONFIGURATIONS x 10 FOLDS x 3
stopifnot(
nrow(param_grid) == 360,
length(cv_folds) == 10,
nrow(reg_train) == nrow(cls_train),
identical(sort(unlist(cv_folds, use.names = FALSE)),
seq_len(nrow(reg_train))),
identical(reg_train$quality >= 6,
cls_train$quality_class == "Good")
)
grid_dir <- "P11_Grid_Search_Results"
dir.create(grid_dir, showWarnings = FALSE, recursive = TRUE)
evaluate_grid_fold <- function(spec, model_name, fold_id) {
is_regression <- model_name == "Regression"
data_model <- if (is_regression) reg_train else cls_train
validation_id <- cv_folds[[fold_id]]
training_id <- setdiff(seq_len(nrow(data_model)), validation_id)
train_fold <- data_model[training_id, , drop = FALSE]
valid_fold <- data_model[validation_id, , drop = FALSE]
control_params <- rpart.control(
cp = spec$cp, minsplit = spec$minsplit,
minbucket = spec$minbucket, maxdepth = spec$maxdepth,
xval = 0
)
start_time <- proc.time()[["elapsed"]]
if (is_regression) {
fit <- rpart(quality ~ ., data = train_fold,
method = "anova", control = control_params)
} else {
split_method <- if (model_name == "Gini") "gini" else "information"
fit <- rpart(quality_class ~ ., data = train_fold,
method = "class", parms = list(split = split_method),
control = control_params)
}
fit_seconds <- proc.time()[["elapsed"]] - start_time
frame <- fit$frame
is_leaf <- frame$var == "<leaf>"
node_ids <- as.integer(rownames(frame))
result <- tibble(
model = model_name, configuration = spec$configuration,
fold = fold_id, cp = spec$cp,
minsplit = spec$minsplit, minbucket = spec$minbucket,
maxdepth = spec$maxdepth, terminal_nodes = sum(is_leaf),
tree_depth = max(floor(log2(node_ids))),
fit_seconds = fit_seconds,
rmse = NA_real_, mae = NA_real_,
balanced_accuracy = NA_real_, accuracy = NA_real_,
precision = NA_real_, recall = NA_real_,
f1_score = NA_real_, specificity = NA_real_
)
if (is_regression) {
predicted <- as.numeric(
predict(fit, newdata = valid_fold, type = "vector"))
actual <- valid_fold$quality
result$rmse <- sqrt(mean((actual - predicted)^2))
result$mae <- mean(abs(actual - predicted))
} else {
predicted <- as.character(
predict(fit, newdata = valid_fold, type = "class"))
actual <- as.character(valid_fold$quality_class)
tp <- sum(predicted == "Good" & actual == "Good")
tn <- sum(predicted == "Not Good" & actual == "Not Good")
fp <- sum(predicted == "Good" & actual == "Not Good")
fn <- sum(predicted == "Not Good" & actual == "Good")
recall <- tp / (tp + fn)
specificity <- tn / (tn + fp)
precision <- if ((tp + fp) > 0) tp / (tp + fp) else 0
f1 <- if ((precision + recall) > 0) {
2 * precision * recall / (precision + recall)
} else 0
result$balanced_accuracy <- (recall + specificity) / 2
result$accuracy <- (tp + tn) / length(actual)
result$precision <- precision
result$recall <- recall
result$f1_score <- f1
result$specificity <- specificity
}
return(result)
}
run_grid_model <- function(model_name, batch_size = 20) {
stopifnot(model_name %in% c("Regression", "Gini", "Entropy"))
checkpoint_file <- file.path(
grid_dir, paste0("cv_", tolower(model_name), ".rds"))
if (file.exists(checkpoint_file)) {
checkpoint <- readRDS(checkpoint_file)
stopifnot(
identical(checkpoint$grid, param_grid),
identical(checkpoint$folds, cv_folds),
identical(checkpoint$model, model_name)
)
results <- checkpoint$results
message("Melanjutkan ", model_name, " dari checkpoint.")
} else {
results <- tibble()
}
completed_ids <- unique(results$configuration)
remaining_ids <- setdiff(param_grid$configuration, completed_ids)
if (length(remaining_ids) == 0) {
message(model_name, ": seluruh konfigurasi sudah selesai.")
return(results)
}
batches <- split(
remaining_ids,
ceiling(seq_along(remaining_ids) / batch_size)
)
for (b in seq_along(batches)) {
batch_results <- bind_rows(lapply(batches[[b]], function(config_id) {
spec <- param_grid %>% filter(configuration == config_id)
bind_rows(lapply(seq_along(cv_folds), function(k) {
evaluate_grid_fold(spec = spec,
model_name = model_name, fold_id = k)
}))
}))
results <- bind_rows(results, batch_results)
saveRDS(list(model = model_name, grid = param_grid,
folds = cv_folds, results = results),
checkpoint_file)
completed_count <- length(unique(results$configuration))
message(model_name, ": ", completed_count, " / ",
nrow(param_grid), " konfigurasi selesai.")
}
return(results)
}
reg_grid_raw <- run_grid_model("Regression", batch_size = 20)
gini_grid_raw <- run_grid_model("Gini", batch_size = 20)
entropy_grid_raw <- run_grid_model("Entropy", batch_size = 20)
grid_completion <- tibble(
model = c("Regression", "Gini", "Entropy"),
records = c(nrow(reg_grid_raw), nrow(gini_grid_raw),
nrow(entropy_grid_raw))
) %>% mutate(expected = nrow(param_grid) * length(cv_folds),
complete = records == expected)
knitr::kable(grid_completion,
caption = "Full grid search completion check")
stopifnot(all(grid_completion$complete))
| Model | Checkpoint file |
|---|---|
| Regression | cv_regression.rds |
| Gini | cv_gini.rds |
| Entropy | cv_entropy.rds |
Interpretasi. Ketiga berkas checkpoint (cv_regression.rds, cv_gini.rds, dan cv_entropy.rds) menyimpan hasil validasi masing-masing model. Penyimpanan bertahap memungkinkan grid search dilanjutkan setelah proses RStudio terhenti tanpa mengulang seluruh konfigurasi. Status berkas hanya menunjukkan tersedianya hasil komputasi tersimpan, bukan ukuran ketepatan prediksi.
Kode lengkap ini menunjukkan urutan komputasi tahap tersebut. Jalankan tahapan mulai dari Data Preparation agar objek yang diperlukan telah tersedia.
# FULL GRID SEARCH — 360 CONFIGURATIONS x 10 FOLDS x 3
stopifnot(
nrow(param_grid) == 360,
length(cv_folds) == 10,
nrow(reg_train) == nrow(cls_train),
identical(sort(unlist(cv_folds, use.names = FALSE)),
seq_len(nrow(reg_train))),
identical(reg_train$quality >= 6,
cls_train$quality_class == "Good")
)
grid_dir <- "P11_Grid_Search_Results"
dir.create(grid_dir, showWarnings = FALSE, recursive = TRUE)
evaluate_grid_fold <- function(spec, model_name, fold_id) {
is_regression <- model_name == "Regression"
data_model <- if (is_regression) reg_train else cls_train
validation_id <- cv_folds[[fold_id]]
training_id <- setdiff(seq_len(nrow(data_model)), validation_id)
train_fold <- data_model[training_id, , drop = FALSE]
valid_fold <- data_model[validation_id, , drop = FALSE]
control_params <- rpart.control(
cp = spec$cp, minsplit = spec$minsplit,
minbucket = spec$minbucket, maxdepth = spec$maxdepth,
xval = 0
)
start_time <- proc.time()[["elapsed"]]
if (is_regression) {
fit <- rpart(quality ~ ., data = train_fold,
method = "anova", control = control_params)
} else {
split_method <- if (model_name == "Gini") "gini" else "information"
fit <- rpart(quality_class ~ ., data = train_fold,
method = "class", parms = list(split = split_method),
control = control_params)
}
fit_seconds <- proc.time()[["elapsed"]] - start_time
frame <- fit$frame
is_leaf <- frame$var == "<leaf>"
node_ids <- as.integer(rownames(frame))
result <- tibble(
model = model_name, configuration = spec$configuration,
fold = fold_id, cp = spec$cp,
minsplit = spec$minsplit, minbucket = spec$minbucket,
maxdepth = spec$maxdepth, terminal_nodes = sum(is_leaf),
tree_depth = max(floor(log2(node_ids))),
fit_seconds = fit_seconds,
rmse = NA_real_, mae = NA_real_,
balanced_accuracy = NA_real_, accuracy = NA_real_,
precision = NA_real_, recall = NA_real_,
f1_score = NA_real_, specificity = NA_real_
)
if (is_regression) {
predicted <- as.numeric(
predict(fit, newdata = valid_fold, type = "vector"))
actual <- valid_fold$quality
result$rmse <- sqrt(mean((actual - predicted)^2))
result$mae <- mean(abs(actual - predicted))
} else {
predicted <- as.character(
predict(fit, newdata = valid_fold, type = "class"))
actual <- as.character(valid_fold$quality_class)
tp <- sum(predicted == "Good" & actual == "Good")
tn <- sum(predicted == "Not Good" & actual == "Not Good")
fp <- sum(predicted == "Good" & actual == "Not Good")
fn <- sum(predicted == "Not Good" & actual == "Good")
recall <- tp / (tp + fn)
specificity <- tn / (tn + fp)
precision <- if ((tp + fp) > 0) tp / (tp + fp) else 0
f1 <- if ((precision + recall) > 0) {
2 * precision * recall / (precision + recall)
} else 0
result$balanced_accuracy <- (recall + specificity) / 2
result$accuracy <- (tp + tn) / length(actual)
result$precision <- precision
result$recall <- recall
result$f1_score <- f1
result$specificity <- specificity
}
return(result)
}
run_grid_model <- function(model_name, batch_size = 20) {
stopifnot(model_name %in% c("Regression", "Gini", "Entropy"))
checkpoint_file <- file.path(
grid_dir, paste0("cv_", tolower(model_name), ".rds"))
if (file.exists(checkpoint_file)) {
checkpoint <- readRDS(checkpoint_file)
stopifnot(
identical(checkpoint$grid, param_grid),
identical(checkpoint$folds, cv_folds),
identical(checkpoint$model, model_name)
)
results <- checkpoint$results
message("Melanjutkan ", model_name, " dari checkpoint.")
} else {
results <- tibble()
}
completed_ids <- unique(results$configuration)
remaining_ids <- setdiff(param_grid$configuration, completed_ids)
if (length(remaining_ids) == 0) {
message(model_name, ": seluruh konfigurasi sudah selesai.")
return(results)
}
batches <- split(
remaining_ids,
ceiling(seq_along(remaining_ids) / batch_size)
)
for (b in seq_along(batches)) {
batch_results <- bind_rows(lapply(batches[[b]], function(config_id) {
spec <- param_grid %>% filter(configuration == config_id)
bind_rows(lapply(seq_along(cv_folds), function(k) {
evaluate_grid_fold(spec = spec,
model_name = model_name, fold_id = k)
}))
}))
results <- bind_rows(results, batch_results)
saveRDS(list(model = model_name, grid = param_grid,
folds = cv_folds, results = results),
checkpoint_file)
completed_count <- length(unique(results$configuration))
message(model_name, ": ", completed_count, " / ",
nrow(param_grid), " konfigurasi selesai.")
}
return(results)
}
reg_grid_raw <- run_grid_model("Regression", batch_size = 20)
gini_grid_raw <- run_grid_model("Gini", batch_size = 20)
entropy_grid_raw <- run_grid_model("Entropy", batch_size = 20)
grid_completion <- tibble(
model = c("Regression", "Gini", "Entropy"),
records = c(nrow(reg_grid_raw), nrow(gini_grid_raw),
nrow(entropy_grid_raw))
) %>% mutate(expected = nrow(param_grid) * length(cv_folds),
complete = records == expected)
knitr::kable(grid_completion,
caption = "Full grid search completion check")
stopifnot(all(grid_completion$complete))Konfigurasi terbaik dipilih hanya berdasarkan hasil cross-validation; seluruh kandidat tetap tercatat.
Pilih RMSE terkecil untuk regresi dan Balanced Accuracy terbesar untuk klasifikasi. Tabel kandidat teratas memperlihatkan bahwa beberapa konfigurasi dapat menghasilkan skor yang sangat mirip.
reg_grid_summary <- reg_grid_raw %>%
group_by(configuration, cp, minsplit, minbucket, maxdepth) %>%
summarise(
cv_RMSE = mean(rmse), sd_RMSE = sd(rmse),
cv_MAE = mean(mae),
mean_terminal_nodes = mean(terminal_nodes),
mean_depth = mean(tree_depth),
mean_fit_seconds = mean(fit_seconds),
.groups = "drop"
)
cls_grid_summary <- bind_rows(gini_grid_raw, entropy_grid_raw) %>%
group_by(model, configuration, cp, minsplit,
minbucket, maxdepth) %>%
summarise(
cv_Balanced_Accuracy = mean(balanced_accuracy),
sd_Balanced_Accuracy = sd(balanced_accuracy),
cv_Accuracy = mean(accuracy),
cv_Precision = mean(precision),
cv_Recall = mean(recall),
cv_F1 = mean(f1_score),
cv_Specificity = mean(specificity),
mean_terminal_nodes = mean(terminal_nodes),
mean_depth = mean(tree_depth),
mean_fit_seconds = mean(fit_seconds),
.groups = "drop"
)
best_reg_config <- reg_grid_summary %>%
arrange(cv_RMSE, mean_terminal_nodes, desc(cp)) %>%
slice_head(n = 1)
best_cls_config <- cls_grid_summary %>%
group_by(model) %>%
arrange(desc(cv_Balanced_Accuracy),
mean_terminal_nodes, desc(cp), .by_group = TRUE) %>%
slice_head(n = 1) %>% ungroup()
knitr::kable(best_reg_config, digits = 5,
caption = "Best Regression configuration")
| Config | CP | minsplit | minbucket | maxdepth | CV RMSE | SD RMSE | CV MAE | Rata-rata daun |
|---|---|---|---|---|---|---|---|---|
| 87 | 0,0005 | 80 | 15 | 5 | 0,75385 | 0,03744 | 0,58709 | 27,8 |
Interpretasi. Konfigurasi 87 meminimalkan CV RMSE sebesar 0,75385 dengan rata-rata 27,8 terminal node antar-fold. Nilai ini berasal dari validasi, bukan hasil testing. Kedalaman maksimum 5 membatasi struktur pohon ketika CP cukup kecil.
cls_grid_summary <- bind_rows(gini_grid_raw, entropy_grid_raw) %>%
group_by(model, configuration, cp, minsplit,
minbucket, maxdepth) %>%
summarise(
cv_Balanced_Accuracy = mean(balanced_accuracy),
sd_Balanced_Accuracy = sd(balanced_accuracy),
cv_Accuracy = mean(accuracy),
cv_Precision = mean(precision),
cv_Recall = mean(recall),
cv_F1 = mean(f1_score),
cv_Specificity = mean(specificity),
mean_terminal_nodes = mean(terminal_nodes),
mean_depth = mean(tree_depth),
mean_fit_seconds = mean(fit_seconds),
.groups = "drop"
)
best_reg_config <- reg_grid_summary %>%
arrange(cv_RMSE, mean_terminal_nodes, desc(cp)) %>%
slice_head(n = 1)
best_cls_config <- cls_grid_summary %>%
group_by(model) %>%
arrange(desc(cv_Balanced_Accuracy),
mean_terminal_nodes, desc(cp), .by_group = TRUE) %>%
slice_head(n = 1) %>% ungroup()
knitr::kable(best_reg_config, digits = 5,
caption = "Best Regression configuration")
knitr::kable(best_cls_config, digits = 5,
caption = "Best Classification configurations")
| Kriteria | Config | CP | minsplit | minbucket | maxdepth | CV Balanced Acc. | SD |
|---|---|---|---|---|---|---|---|
| Gini | 149 | 0,003 | 20 | 7 | 15 | 0,72098 | 0,03286 |
| Entropy | 133 | 0,001 | 80 | 15 | 8 | 0,71749 | 0,02355 |
Interpretasi. Gini dan Entropy memperoleh parameter berbeda karena pemisahan impurity berbeda dan CV Balanced Accuracy yang dioptimalkan tidak selalu sama. CV Gini unggul tipis sebesar 0,00349 dari Entropy pada hasil pemilihan ini, tetapi angka tersebut belum menunjukkan keunggulan pada data uji.
reg_grid_summary <- reg_grid_raw %>%
group_by(configuration, cp, minsplit, minbucket, maxdepth) %>%
summarise(
cv_RMSE = mean(rmse), sd_RMSE = sd(rmse),
cv_MAE = mean(mae),
mean_terminal_nodes = mean(terminal_nodes),
mean_depth = mean(tree_depth),
mean_fit_seconds = mean(fit_seconds),
.groups = "drop"
)
top10_reg <- reg_grid_summary %>%
arrange(cv_RMSE) %>% slice_head(n = 10)
top10_cls <- cls_grid_summary %>%
group_by(model) %>%
arrange(desc(cv_Balanced_Accuracy), .by_group = TRUE) %>%
slice_head(n = 10) %>% ungroup()
knitr::kable(top10_reg, digits = 5,
caption = "Top 10 Regression configurations")
| Regression config | CP | CV RMSE | Mean terminal nodes |
|---|---|---|---|
| 42 | 0 | 0,753850636246 | 27,8 |
| 87 | 0,0005 | 0,753850636246 | 27,8 |
| 132 | 0,001 | 0,75388 | 27,7 |
| 27 | 0 | 0,75503 | 30,1 |
| 72 | 0,0005 | 0,75503 | 30,1 |
Interpretasi. Konfigurasi 42 (cp = 0) dan 87 (cp = 0,0005) menghasilkan CV RMSE identik hingga 12 desimal, yaitu 0,753850636246. Ketika skor dan rata-rata terminal node sama, aturan pemilihan yang ditetapkan mempertahankan konfigurasi 87 karena cp lebih besar. Kesamaan skor agregat bukan bukti bahwa setiap pohon antar-fold identik.
cls_grid_summary <- bind_rows(gini_grid_raw, entropy_grid_raw) %>%
group_by(model, configuration, cp, minsplit,
minbucket, maxdepth) %>%
summarise(
cv_Balanced_Accuracy = mean(balanced_accuracy),
sd_Balanced_Accuracy = sd(balanced_accuracy),
cv_Accuracy = mean(accuracy),
cv_Precision = mean(precision),
cv_Recall = mean(recall),
cv_F1 = mean(f1_score),
cv_Specificity = mean(specificity),
mean_terminal_nodes = mean(terminal_nodes),
mean_depth = mean(tree_depth),
mean_fit_seconds = mean(fit_seconds),
.groups = "drop"
top10_cls <- cls_grid_summary %>%
group_by(model) %>%
arrange(desc(cv_Balanced_Accuracy), .by_group = TRUE) %>%
slice_head(n = 10) %>% ungroup()
knitr::kable(top10_reg, digits = 5,
caption = "Top 10 Regression configurations")
knitr::kable(top10_cls, digits = 5,
caption = "Top 10 configurations Gini and Entropy")
| Model | Config | CV BA | CV Accuracy | CV F1 |
|---|---|---|---|---|
| Gini | 149 | 0.72098 | 0.73915 | 0.79174 |
| Entropy | 133 | 0.71749 | 0.73891 | 0.79357 |
Interpretasi. Gini memilih konfigurasi 149 (Balanced Accuracy CV 0,72098), sedangkan entropy memilih konfigurasi 133 (0,71749). Daftar ini memperlihatkan beberapa konfigurasi dengan skor berdekatan; pemilihan tetap didasarkan pada kriteria CV yang telah ditetapkan, bukan hasil data uji.
Kode lengkap ini menunjukkan urutan komputasi tahap tersebut. Jalankan tahapan mulai dari Data Preparation agar objek yang diperlukan telah tersedia.
# CV SUMMARY AND CONFIGURATION SELECTION
reg_grid_summary <- reg_grid_raw %>%
group_by(configuration, cp, minsplit, minbucket, maxdepth) %>%
summarise(
cv_RMSE = mean(rmse), sd_RMSE = sd(rmse),
cv_MAE = mean(mae),
mean_terminal_nodes = mean(terminal_nodes),
mean_depth = mean(tree_depth),
mean_fit_seconds = mean(fit_seconds),
.groups = "drop"
)
cls_grid_summary <- bind_rows(gini_grid_raw, entropy_grid_raw) %>%
group_by(model, configuration, cp, minsplit,
minbucket, maxdepth) %>%
summarise(
cv_Balanced_Accuracy = mean(balanced_accuracy),
sd_Balanced_Accuracy = sd(balanced_accuracy),
cv_Accuracy = mean(accuracy),
cv_Precision = mean(precision),
cv_Recall = mean(recall),
cv_F1 = mean(f1_score),
cv_Specificity = mean(specificity),
mean_terminal_nodes = mean(terminal_nodes),
mean_depth = mean(tree_depth),
mean_fit_seconds = mean(fit_seconds),
.groups = "drop"
)
best_reg_config <- reg_grid_summary %>%
arrange(cv_RMSE, mean_terminal_nodes, desc(cp)) %>%
slice_head(n = 1)
best_cls_config <- cls_grid_summary %>%
group_by(model) %>%
arrange(desc(cv_Balanced_Accuracy),
mean_terminal_nodes, desc(cp), .by_group = TRUE) %>%
slice_head(n = 1) %>% ungroup()
knitr::kable(best_reg_config, digits = 5,
caption = "Best Regression configuration")
knitr::kable(best_cls_config, digits = 5,
caption = "Best Classification configurations")
top10_reg <- reg_grid_summary %>%
arrange(cv_RMSE) %>% slice_head(n = 10)
top10_cls <- cls_grid_summary %>%
group_by(model) %>%
arrange(desc(cv_Balanced_Accuracy), .by_group = TRUE) %>%
slice_head(n = 10) %>% ungroup()
knitr::kable(top10_reg, digits = 5,
caption = "Top 10 Regression configurations")
knitr::kable(top10_cls, digits = 5,
caption = "Top 10 configurations Gini and Entropy")
saveRDS(list(regression = reg_grid_summary,
classification = cls_grid_summary,
best_regression = best_reg_config,
best_classification = best_cls_config),
file.path(grid_dir, "grid_search_summary.rds"))
cat("\nGRID SEARCH SUMMARY COMPLETED\n")CV baseline dan tuned dibandingkan sebelum model terbaik dilatih ulang pada seluruh training.
Bandingkan baseline dan tuned pada fold yang sama. Setelah memilih parameter, latih ulang model pada seluruh training set dan amati perubahan struktur setiap pohon.
baseline_id <- param_grid %>% filter(
cp == 0.01, minsplit == 20,
minbucket == 7, maxdepth == 30
) %>% pull(configuration)
stopifnot(length(baseline_id) == 1)
cv_reg_comparison <- bind_rows(
reg_grid_summary %>% filter(configuration == baseline_id) %>%
mutate(version = "Baseline"),
best_reg_config %>% mutate(version = "Grid Search")
) %>% select(version, configuration, cp, minsplit,
minbucket, maxdepth, cv_RMSE, sd_RMSE,
cv_MAE, mean_terminal_nodes)
knitr::kable(cv_reg_comparison, digits = 5,
caption = "Baseline vs Tuned Regression — 10-fold CV")
| Version | CP | minsplit | minbucket | maxdepth | CV RMSE | CV MAE | Rata-rata daun |
|---|---|---|---|---|---|---|---|
| Baseline | 0,01 | 20 | 7 | 30 | 0,77240 | 0,61186 | 5,8 |
| Grid Search | 0,0005 | 80 | 15 | 5 | 0,75385 | 0,58709 | 27,8 |
Interpretasi. Pada sepuluh fold yang sama, RMSE CV turun dari 0,77240 (baseline) menjadi 0,75385 (tuned). Selisih ini merupakan hasil validasi selama pemilihan parameter, bukan jaminan bahwa seluruh kesalahan uji akan turun. Pemeriksaan data uji dilakukan setelah model dipilih.
cv_cls_comparison <- bind_rows(
cls_grid_summary %>% filter(configuration == baseline_id) %>%
mutate(version = "Baseline"),
best_cls_config %>% mutate(version = "Grid Search")
) %>% arrange(model, version) %>%
select(model, version, configuration, cp, minsplit,
minbucket, maxdepth, cv_Balanced_Accuracy,
sd_Balanced_Accuracy, cv_Accuracy,
cv_F1, cv_Specificity, mean_terminal_nodes)
knitr::kable(cv_cls_comparison, digits = 5,
caption = "Baseline vs Tuned Classification — 10-fold CV")
| Model | Versi | Balanced Acc. CV | Accuracy CV | F1 CV | Specificity CV |
|---|---|---|---|---|---|
| Gini | Baseline | 0,68585 | 0,72693 | 0,79554 | 0,52327 |
| Gini | Grid Search | 0,72098 | 0,73915 | 0,79174 | 0,64906 |
| Entropy | Baseline | 0,69090 | 0,72881 | 0,79529 | 0,54088 |
| Entropy | Grid Search | 0,71749 | 0,73891 | 0,79357 | 0,63270 |
Interpretasi. Rata-rata Balanced Accuracy CV naik dari 0,68585 menjadi 0,72098 pada Gini dan dari 0,69090 menjadi 0,71749 pada entropy. Kenaikan masing-masing sekitar 3,51 dan 2,66 poin persentase. Metrik lain, termasuk F1, tidak harus naik karena seleksi konfigurasi memang mengutamakan Balanced Accuracy.
reg_tie_check <- reg_grid_summary %>%
filter(configuration %in% c(42, 87)) %>%
mutate(RMSE_12_digits = sprintf("%.12f", cv_RMSE)) %>%
select(configuration, cp, cv_RMSE, RMSE_12_digits,
cv_MAE, mean_terminal_nodes)
knitr::kable(reg_tie_check,
caption = "Detailed comparison of regression ties")
| Config | cp | CV RMSE | Mean leaves |
|---|---|---|---|
| 42 | 0 | 0.753850636246 | 27.8 |
| 87 | 0.0005 | 0.753850636246 | 27.8 |
Interpretasi. Kedua konfigurasi menghasilkan CV RMSE 0,753850636246 hingga dua belas angka desimal. Konfigurasi 87 dipilih berdasarkan aturan tie-break (cp lebih besar), bukan karena diketahui memiliki kinerja testing lebih baik.
# REFIT SELECTED MODELS ON FULL TRAINING DATA
fit_selected_tree <- function(spec, data, task, split = NULL) {
stopifnot(nrow(spec) == 1)
tree_control <- rpart.control(
cp = spec$cp, minsplit = spec$minsplit,
minbucket = spec$minbucket, maxdepth = spec$maxdepth,
xval = 0
)
if (task == "regression") {
fit <- rpart(quality ~ ., data = data,
method = "anova", control = tree_control)
} else {
fit <- rpart(quality_class ~ ., data = data,
method = "class", parms = list(split = split),
control = tree_control)
}
return(fit)
}
reg_tree_tuned <- fit_selected_tree(
best_reg_config, reg_train, task = "regression")
gini_spec <- best_cls_config %>% filter(model == "Gini")
cls_tree_gini_tuned <- fit_selected_tree(
gini_spec, cls_train, task = "classification", split = "gini")
entropy_spec <- best_cls_config %>% filter(model == "Entropy")
cls_tree_entropy_tuned <- fit_selected_tree(
entropy_spec, cls_train, task = "classification",
split = "information")
get_tree_structure <- function(fit, model, version) {
frame <- fit$frame
node_ids <- as.integer(rownames(frame))
tibble(model = model, version = version,
internal_nodes = sum(frame$var != "<leaf>"),
terminal_nodes = sum(frame$var == "<leaf>"),
total_nodes = nrow(frame),
tree_depth = max(floor(log2(node_ids))),
root_split = frame$var[1])
}
tuned_structure <- bind_rows(
get_tree_structure(reg_tree, "Regression", "Baseline"),
get_tree_structure(reg_tree_tuned, "Regression", "Grid Search"),
get_tree_structure(cls_tree_gini, "Gini", "Baseline"),
get_tree_structure(cls_tree_gini_tuned, "Gini", "Grid Search"),
get_tree_structure(cls_tree_entropy, "Entropy", "Baseline"),
get_tree_structure(cls_tree_entropy_tuned, "Entropy", "Grid Search")
)
knitr::kable(tuned_structure,
caption = "Baseline and tuned tree structures")
| Model | Versi | Internal | Terminal | Total | Depth | Root split |
|---|---|---|---|---|---|---|
| Regression | Baseline | 4 | 5 | 9 | 3 | alcohol |
| Regression | Grid Search | 28 | 29 | 57 | 5 | alcohol |
| Gini | Baseline | 2 | 3 | 5 | 2 | alcohol |
| Gini | Grid Search | 25 | 26 | 51 | 9 | alcohol |
| Entropy | Baseline | 5 | 6 | 11 | 4 | alcohol |
| Entropy | Grid Search | 29 | 30 | 59 | 8 | alcohol |
Interpretasi. Seluruh model tuned memiliki lebih banyak terminal node, tetapi tetap menggunakan alcohol sebagai root split. Nilai maxdepth adalah batas atas yang diperbolehkan, bukan jaminan kedalaman pohon aktual. Pada Gini tuned, batas maxdepth 15 menghasilkan kedalaman aktual 9.
# SAVE FULL TUNED TREE VISUALIZATIONS
plot_dir <- file.path(grid_dir, "Tuned_Tree_Plots")
dir.create(plot_dir, recursive = TRUE, showWarnings = FALSE)
save_tree_plot <- function(fit, filename, title, extra) {
png(filename = file.path(plot_dir, filename),
width = 3200, height = 2000, res = 180)
tryCatch({
rpart.plot(fit, type = 2, extra = extra,
under = FALSE, fallen.leaves = TRUE,
faclen = 0, digits = 3, tweak = 0.8,
main = title)
}, finally = dev.off())
}
save_tree_plot(reg_tree_tuned, "Regression_Tree_Tuned.png",
"Tuned Regression Tree — Wine Quality", 101)
Interpretasi. Hasil refitting menghasilkan 29 terminal node, jauh lebih banyak daripada baseline (5). Pada gambar, cabang-cabang baru membagi kelompok anggur menjadi wilayah prediksi lebih rinci, tetapi tiap daun masih menghasilkan nilai skor konstan. Perbedaan struktur ini baru bernilai praktis apabila kesalahannya pada data uji turun, seperti yang akan diperiksa pada evaluasi berikutnya.
# SAVE FULL TUNED TREE VISUALIZATIONS
plot_dir <- file.path(grid_dir, "Tuned_Tree_Plots")
dir.create(plot_dir, recursive = TRUE, showWarnings = FALSE)
save_tree_plot <- function(fit, filename, title, extra) {
png(filename = file.path(plot_dir, filename),
width = 3200, height = 2000, res = 180)
tryCatch({
rpart.plot(fit, type = 2, extra = extra,
under = FALSE, fallen.leaves = TRUE,
faclen = 0, digits = 3, tweak = 0.8,
main = title)
}, finally = dev.off())
}
save_tree_plot(reg_tree_tuned, "Regression_Tree_Tuned.png",
"Tuned Regression Tree — Wine Quality", 101)
save_tree_plot(cls_tree_gini_tuned, "Classification_Gini_Tuned.png",
"Tuned Classification Tree — Gini", 104)
Interpretasi. Gini tuned menghasilkan 26 terminal node dengan kedalaman aktual 9, walaupun maxdepth yang diizinkan adalah 15. Diagram menunjukkan bahwa beberapa cabang mengalami pemisahan tambahan, tetapi perhatikan perbedaan antara bertambahnya rincian keputusan dan perubahan kemampuan mengenali kelas Good maupun Not Good pada data uji.
# SAVE FULL TUNED TREE VISUALIZATIONS
plot_dir <- file.path(grid_dir, "Tuned_Tree_Plots")
dir.create(plot_dir, recursive = TRUE, showWarnings = FALSE)
save_tree_plot <- function(fit, filename, title, extra) {
png(filename = file.path(plot_dir, filename),
width = 3200, height = 2000, res = 180)
tryCatch({
rpart.plot(fit, type = 2, extra = extra,
under = FALSE, fallen.leaves = TRUE,
faclen = 0, digits = 3, tweak = 0.8,
main = title)
}, finally = dev.off())
}
save_tree_plot(reg_tree_tuned, "Regression_Tree_Tuned.png",
"Tuned Regression Tree — Wine Quality", 101)
save_tree_plot(cls_tree_gini_tuned, "Classification_Gini_Tuned.png",
"Tuned Classification Tree — Gini", 104)
save_tree_plot(cls_tree_entropy_tuned,
"Classification_Entropy_Tuned.png",
"Tuned Classification Tree — Entropy", 104)
cat("Three tuned tree plots saved to:", plot_dir, "\n")
Interpretasi. Entropy tuned menghasilkan 30 terminal node dan kedalaman aktual 8. Dibandingkan enam terminal node pada baseline, model ini membentuk lebih banyak wilayah klasifikasi. Namun jumlah daun bukan ukuran keberhasilan: confusion matrix data uji memperlihatkan tambahan pengenalan Not Good sekaligus penurunan pengenalan Good.
Kode lengkap ini menunjukkan urutan komputasi tahap tersebut. Jalankan tahapan mulai dari Data Preparation agar objek yang diperlukan telah tersedia.
# BASELINE VS TUNED (COMMON 10-FOLD CV)
baseline_id <- param_grid %>% filter(
cp == 0.01, minsplit == 20,
minbucket == 7, maxdepth == 30
) %>% pull(configuration)
stopifnot(length(baseline_id) == 1)
cv_reg_comparison <- bind_rows(
reg_grid_summary %>% filter(configuration == baseline_id) %>%
mutate(version = "Baseline"),
best_reg_config %>% mutate(version = "Grid Search")
) %>% select(version, configuration, cp, minsplit,
minbucket, maxdepth, cv_RMSE, sd_RMSE,
cv_MAE, mean_terminal_nodes)
knitr::kable(cv_reg_comparison, digits = 5,
caption = "Baseline vs Tuned Regression — 10-fold CV")
cv_cls_comparison <- bind_rows(
cls_grid_summary %>% filter(configuration == baseline_id) %>%
mutate(version = "Baseline"),
best_cls_config %>% mutate(version = "Grid Search")
) %>% arrange(model, version) %>%
select(model, version, configuration, cp, minsplit,
minbucket, maxdepth, cv_Balanced_Accuracy,
sd_Balanced_Accuracy, cv_Accuracy,
cv_F1, cv_Specificity, mean_terminal_nodes)
knitr::kable(cv_cls_comparison, digits = 5,
caption = "Baseline vs Tuned Classification — 10-fold CV")
reg_tie_check <- reg_grid_summary %>%
filter(configuration %in% c(42, 87)) %>%
mutate(RMSE_12_digits = sprintf("%.12f", cv_RMSE)) %>%
select(configuration, cp, cv_RMSE, RMSE_12_digits,
cv_MAE, mean_terminal_nodes)
knitr::kable(reg_tie_check,
caption = "Detailed comparison of regression ties")
# REFIT SELECTED MODELS ON FULL TRAINING DATA
fit_selected_tree <- function(spec, data, task, split = NULL) {
stopifnot(nrow(spec) == 1)
tree_control <- rpart.control(
cp = spec$cp, minsplit = spec$minsplit,
minbucket = spec$minbucket, maxdepth = spec$maxdepth,
xval = 0
)
if (task == "regression") {
fit <- rpart(quality ~ ., data = data,
method = "anova", control = tree_control)
} else {
fit <- rpart(quality_class ~ ., data = data,
method = "class", parms = list(split = split),
control = tree_control)
}
return(fit)
}
reg_tree_tuned <- fit_selected_tree(
best_reg_config, reg_train, task = "regression")
gini_spec <- best_cls_config %>% filter(model == "Gini")
cls_tree_gini_tuned <- fit_selected_tree(
gini_spec, cls_train, task = "classification", split = "gini")
entropy_spec <- best_cls_config %>% filter(model == "Entropy")
cls_tree_entropy_tuned <- fit_selected_tree(
entropy_spec, cls_train, task = "classification",
split = "information")
get_tree_structure <- function(fit, model, version) {
frame <- fit$frame
node_ids <- as.integer(rownames(frame))
tibble(model = model, version = version,
internal_nodes = sum(frame$var != "<leaf>"),
terminal_nodes = sum(frame$var == "<leaf>"),
total_nodes = nrow(frame),
tree_depth = max(floor(log2(node_ids))),
root_split = frame$var[1])
}
tuned_structure <- bind_rows(
get_tree_structure(reg_tree, "Regression", "Baseline"),
get_tree_structure(reg_tree_tuned, "Regression", "Grid Search"),
get_tree_structure(cls_tree_gini, "Gini", "Baseline"),
get_tree_structure(cls_tree_gini_tuned, "Gini", "Grid Search"),
get_tree_structure(cls_tree_entropy, "Entropy", "Baseline"),
get_tree_structure(cls_tree_entropy_tuned, "Entropy", "Grid Search")
)
knitr::kable(tuned_structure,
caption = "Baseline and tuned tree structures")
# SAVE FULL TUNED TREE VISUALIZATIONS
plot_dir <- file.path(grid_dir, "Tuned_Tree_Plots")
dir.create(plot_dir, recursive = TRUE, showWarnings = FALSE)
save_tree_plot <- function(fit, filename, title, extra) {
png(filename = file.path(plot_dir, filename),
width = 3200, height = 2000, res = 180)
tryCatch({
rpart.plot(fit, type = 2, extra = extra,
under = FALSE, fallen.leaves = TRUE,
faclen = 0, digits = 3, tweak = 0.8,
main = title)
}, finally = dev.off())
}
save_tree_plot(reg_tree_tuned, "Regression_Tree_Tuned.png",
"Tuned Regression Tree — Wine Quality", 101)
save_tree_plot(cls_tree_gini_tuned, "Classification_Gini_Tuned.png",
"Tuned Classification Tree — Gini", 104)
save_tree_plot(cls_tree_entropy_tuned,
"Classification_Entropy_Tuned.png",
"Tuned Classification Tree — Entropy", 104)
cat("Three tuned tree plots saved to:", plot_dir, "\n")Perbandingan akhir pada data testing dilakukan setelah parameter dikunci oleh proses CV.
Gunakan testing set hanya setelah pemilihan parameter selesai. Baca metrik regresi, grafik prediksi, confusion matrix, dan hasil klasifikasi tanpa memilih ulang konfigurasi.
evaluate_regression <- function(fit, label) {
actual <- reg_test$quality
predicted <- as.numeric(
predict(fit, newdata = reg_test, type = "vector"))
tibble(
version = label,
RMSE = sqrt(mean((actual - predicted)^2)),
MAE = mean(abs(actual - predicted)),
R2 = 1 - sum((actual - predicted)^2) /
sum((actual - mean(actual))^2)
)
}
reg_test_comparison <- bind_rows(
evaluate_regression(reg_tree_pruned, "Baseline"),
evaluate_regression(reg_tree_tuned, "Grid Search")
)
knitr::kable(reg_test_comparison, digits = 5,
caption = "Regression Tree baseline vs tuned on test data")
| Versi | RMSE ↓ | MAE ↓ | R² ↑ |
|---|---|---|---|
| Baseline | 0,77330 | 0,60672 | 0,23380 |
| Grid Search | 0,75444 | 0,58748 | 0,27070 |
Interpretasi. Pada 1.065 observasi uji yang sama, RMSE turun dari 0,77330 menjadi 0,75444 dan MAE turun dari 0,60672 menjadi 0,58748; R² naik dari 0,2338 menjadi 0,2707. Jadi, peningkatan regresi tidak berhenti pada CV: ketiga metrik yang digunakan juga membaik pada test set.
reg_plot_comparison <- bind_rows(
tibble(actual = reg_test$quality,
predicted = as.numeric(predict(reg_tree_pruned,
newdata = reg_test, type = "vector")),
version = "Baseline"),
tibble(actual = reg_test$quality,
predicted = as.numeric(predict(reg_tree_tuned,
newdata = reg_test, type = "vector")),
version = "Grid Search")
)
ggplot(reg_plot_comparison, aes(x = actual, y = predicted)) +
geom_abline(intercept = 0, slope = 1, linetype = "dashed") +
geom_count(alpha = 0.65) +
facet_wrap(~ version, ncol = 2) +
labs(title = "Regression Tree: Baseline vs Grid Search",
subtitle = "Predictions on Test Data",
x = "Actual Quality", y = "Predicted Quality",
size = "Observations") +
theme_minimal(base_size = 12)
Interpretasi. Grafik tuned memperlihatkan lebih banyak tingkat prediksi daripada baseline. Gelembung yang lebih besar menyatakan lebih banyak observasi dengan pasangan aktual–prediksi yang sama.
evaluate_classification <- function(fit, model, version) {
predicted <- predict(fit, newdata = cls_test, type = "class")
predicted <- factor(as.character(predicted),
levels = levels(cls_test$quality_class))
cm <- caret::confusionMatrix(
data = predicted, reference = cls_test$quality_class,
positive = "Good", mode = "everything")
metrics <- tibble(
model = model, version = version,
Accuracy = unname(cm$overall["Accuracy"]),
Precision = unname(cm$byClass["Precision"]),
Recall = unname(cm$byClass["Recall"]),
F1_score = unname(cm$byClass["F1"]),
Specificity = unname(cm$byClass["Specificity"]),
Balanced_Accuracy = unname(cm$byClass["Balanced Accuracy"])
)
list(metrics = metrics, confusion_matrix = cm,
predicted = predicted)
}
gini_base_eval <- evaluate_classification(
cls_tree_gini, "Gini", "Baseline")
gini_tuned_eval <- evaluate_classification(
cls_tree_gini_tuned, "Gini", "Grid Search")
entropy_base_eval <- evaluate_classification(
cls_tree_entropy, "Entropy", "Baseline")
entropy_tuned_eval <- evaluate_classification(
cls_tree_entropy_tuned, "Entropy", "Grid Search")
cat("\nTUNED GINI — TEST DATA\n")
print(gini_tuned_eval$confusion_matrix)
| Prediksi \ Aktual | Not Good | Good |
|---|---|---|
| Not Good | 242 (TN) | 137 (FN) |
| Good | 156 (FP) | 530 (TP) |
Interpretasi. Setelah tuning, observasi Not Good yang dikenali benar meningkat dari 231 menjadi 242, sedangkan Good yang dikenali benar menurun dari 545 menjadi 530. Hal ini menjelaskan mengapa specificity meningkat tetapi recall Good menurun. Perubahan keseimbangan dua kelas perlu dibaca bersama Balanced Accuracy.
evaluate_classification <- function(fit, model, version) {
predicted <- predict(fit, newdata = cls_test, type = "class")
predicted <- factor(as.character(predicted),
levels = levels(cls_test$quality_class))
cm <- caret::confusionMatrix(
data = predicted, reference = cls_test$quality_class,
positive = "Good", mode = "everything")
metrics <- tibble(
model = model, version = version,
Accuracy = unname(cm$overall["Accuracy"]),
Precision = unname(cm$byClass["Precision"]),
Recall = unname(cm$byClass["Recall"]),
F1_score = unname(cm$byClass["F1"]),
Specificity = unname(cm$byClass["Specificity"]),
Balanced_Accuracy = unname(cm$byClass["Balanced Accuracy"])
)
list(metrics = metrics, confusion_matrix = cm,
predicted = predicted)
}
gini_base_eval <- evaluate_classification(
cls_tree_gini, "Gini", "Baseline")
gini_tuned_eval <- evaluate_classification(
cls_tree_gini_tuned, "Gini", "Grid Search")
entropy_base_eval <- evaluate_classification(
cls_tree_entropy, "Entropy", "Baseline")
entropy_tuned_eval <- evaluate_classification(
cls_tree_entropy_tuned, "Entropy", "Grid Search")
cat("\nTUNED ENTROPY — TEST DATA\n")
print(entropy_tuned_eval$confusion_matrix)
| Prediksi \ Aktual | Not Good | Good |
|---|---|---|
| Not Good | 250 (TN) | 142 (FN) |
| Good | 148 (FP) | 525 (TP) |
Interpretasi. Setelah tuning, observasi Not Good yang dikenali benar bertambah dari 246 menjadi 250, sementara Good yang dikenali benar menurun dari 533 menjadi 525. Model lebih baik mengenali kelas negatif, tetapi mengorbankan sebagian pengenalan Good; akibatnya Balanced Accuracy hampir tidak berubah dan sedikit turun.
evaluate_classification <- function(fit, model, version) {
predicted <- predict(fit, newdata = cls_test, type = "class")
predicted <- factor(as.character(predicted),
levels = levels(cls_test$quality_class))
cm <- caret::confusionMatrix(
data = predicted, reference = cls_test$quality_class,
positive = "Good", mode = "everything")
metrics <- tibble(
model = model, version = version,
Accuracy = unname(cm$overall["Accuracy"]),
Precision = unname(cm$byClass["Precision"]),
Recall = unname(cm$byClass["Recall"]),
F1_score = unname(cm$byClass["F1"]),
Specificity = unname(cm$byClass["Specificity"]),
Balanced_Accuracy = unname(cm$byClass["Balanced Accuracy"])
)
list(metrics = metrics, confusion_matrix = cm,
predicted = predicted)
}
gini_base_eval <- evaluate_classification(
cls_tree_gini, "Gini", "Baseline")
gini_tuned_eval <- evaluate_classification(
cls_tree_gini_tuned, "Gini", "Grid Search")
entropy_base_eval <- evaluate_classification(
cls_tree_entropy, "Entropy", "Baseline")
entropy_tuned_eval <- evaluate_classification(
cls_tree_entropy_tuned, "Entropy", "Grid Search")
cls_test_comparison <- bind_rows(
gini_base_eval$metrics, gini_tuned_eval$metrics,
entropy_base_eval$metrics, entropy_tuned_eval$metrics
)
knitr::kable(cls_test_comparison, digits = 5,
caption = "Classification Trees baseline vs tuned on test data")
| Model | Versi | Accuracy | Precision | Recall | F1 | Specificity | Balanced Acc. |
|---|---|---|---|---|---|---|---|
| Gini | Baseline | 0,72864 | 0,76545 | 0,81709 | 0,79043 | 0,58040 | 0,69875 |
| Gini | Tuned | 0,72488 | 0,77259 | 0,79460 | 0,78344 | 0,60804 | 0,70132 |
| Entropy | Baseline | 0,73146 | 0,77810 | 0,79910 | 0,78846 | 0,61809 | 0,70860 |
| Entropy | Tuned | 0,72770 | 0,78009 | 0,78711 | 0,78358 | 0,62814 | 0,70762 |
Interpretasi. Tuning Gini menaikkan Balanced Accuracy secara tipis dari 0,69875 menjadi 0,70132, tetapi accuracy dan F1 turun. Pada entropy, Balanced Accuracy turun tipis dari 0,70860 menjadi 0,70762 meski specificity membaik. Inilah alasan hasil model harus dibaca per metrik, bukan diberi kesimpulan tunggal bahwa tuning selalu lebih baik.
Kode lengkap ini menunjukkan urutan komputasi tahap tersebut. Jalankan tahapan mulai dari Data Preparation agar objek yang diperlukan telah tersedia.
# FINAL TEST EVALUATION — BASELINE VS GRID SEARCH
evaluate_regression <- function(fit, label) {
actual <- reg_test$quality
predicted <- as.numeric(
predict(fit, newdata = reg_test, type = "vector"))
tibble(
version = label,
RMSE = sqrt(mean((actual - predicted)^2)),
MAE = mean(abs(actual - predicted)),
R2 = 1 - sum((actual - predicted)^2) /
sum((actual - mean(actual))^2)
)
}
reg_test_comparison <- bind_rows(
evaluate_regression(reg_tree_pruned, "Baseline"),
evaluate_regression(reg_tree_tuned, "Grid Search")
)
knitr::kable(reg_test_comparison, digits = 5,
caption = "Regression Tree baseline vs tuned on test data")
evaluate_classification <- function(fit, model, version) {
predicted <- predict(fit, newdata = cls_test, type = "class")
predicted <- factor(as.character(predicted),
levels = levels(cls_test$quality_class))
cm <- caret::confusionMatrix(
data = predicted, reference = cls_test$quality_class,
positive = "Good", mode = "everything")
metrics <- tibble(
model = model, version = version,
Accuracy = unname(cm$overall["Accuracy"]),
Precision = unname(cm$byClass["Precision"]),
Recall = unname(cm$byClass["Recall"]),
F1_score = unname(cm$byClass["F1"]),
Specificity = unname(cm$byClass["Specificity"]),
Balanced_Accuracy = unname(cm$byClass["Balanced Accuracy"])
)
list(metrics = metrics, confusion_matrix = cm,
predicted = predicted)
}
gini_base_eval <- evaluate_classification(
cls_tree_gini, "Gini", "Baseline")
gini_tuned_eval <- evaluate_classification(
cls_tree_gini_tuned, "Gini", "Grid Search")
entropy_base_eval <- evaluate_classification(
cls_tree_entropy, "Entropy", "Baseline")
entropy_tuned_eval <- evaluate_classification(
cls_tree_entropy_tuned, "Entropy", "Grid Search")
cls_test_comparison <- bind_rows(
gini_base_eval$metrics, gini_tuned_eval$metrics,
entropy_base_eval$metrics, entropy_tuned_eval$metrics
)
knitr::kable(cls_test_comparison, digits = 5,
caption = "Classification Trees baseline vs tuned on test data")
cat("\nTUNED GINI — TEST DATA\n")
print(gini_tuned_eval$confusion_matrix)
cat("\nTUNED ENTROPY — TEST DATA\n")
print(entropy_tuned_eval$confusion_matrix)
saveRDS(list(regression = reg_test_comparison,
classification = cls_test_comparison,
gini_cm = gini_tuned_eval$confusion_matrix,
entropy_cm = entropy_tuned_eval$confusion_matrix),
file.path(grid_dir, "final_test_comparison.rds"))
cat("\nFINAL TEST EVALUATION COMPLETED\n")
reg_plot_comparison <- bind_rows(
tibble(actual = reg_test$quality,
predicted = as.numeric(predict(reg_tree_pruned,
newdata = reg_test, type = "vector")),
version = "Baseline"),
tibble(actual = reg_test$quality,
predicted = as.numeric(predict(reg_tree_tuned,
newdata = reg_test, type = "vector")),
version = "Grid Search")
)
ggplot(reg_plot_comparison, aes(x = actual, y = predicted)) +
geom_abline(intercept = 0, slope = 1, linetype = "dashed") +
geom_count(alpha = 0.65) +
facet_wrap(~ version, ncol = 2) +
labs(title = "Regression Tree: Baseline vs Grid Search",
subtitle = "Predictions on Test Data",
x = "Actual Quality", y = "Predicted Quality",
size = "Observations") +
theme_minimal(base_size = 12)Grafik marginal dan heatmap merangkum seluruh konfigurasi untuk membantu memahami pola kompleksitas dan kinerja validasi.
Periksa jumlah konfigurasi yang menyumbang setiap ringkasan, lalu baca grafik marginal dan heatmap. Grafik ini menggambarkan pola dalam grid, bukan efek kausal satu parameter.
stopifnot(nrow(reg_grid_summary) == 360,
nrow(cls_grid_summary) == 720)
parameter_scores <- bind_rows(
reg_grid_summary %>% transmute(
model = "Regression", cp, minsplit, minbucket,
maxdepth, cv_score = cv_RMSE),
cls_grid_summary %>% transmute(
model = model, cp, minsplit, minbucket,
maxdepth, cv_score = cv_Balanced_Accuracy)
)
parameter_long <- parameter_scores %>%
pivot_longer(cols = c(cp, minsplit, minbucket, maxdepth),
names_to = "parameter", values_to = "value")
parameter_effect <- parameter_long %>%
group_by(model, parameter, value) %>%
summarise(mean_cv = mean(cv_score),
min_cv = min(cv_score), max_cv = max(cv_score),
configurations = n(), .groups = "drop")
parameter_coverage <- parameter_effect %>%
filter(model == "Regression") %>%
select(parameter, value, configurations) %>%
arrange(parameter, value)
knitr::kable(parameter_coverage,
caption = "Grid configurations represented per parameter")
| Parameter | Nilai diuji | Jumlah kombinasi per nilai |
|---|---|---|
| cp | 8 nilai: 0 s.d. 0,05 | 45 |
| maxdepth | 3; 5; 8; 15; 30 | 72 |
| minbucket | 5; 7; 15 | 160; 120; 80 |
| minsplit | 10; 20; 40; 80 | 40; 80; 120; 120 |
Interpretasi. Jumlah kombinasi untuk minsplit dan minbucket tidak sama karena penyaringan minsplit ≥ 2 × minbucket. Oleh sebab itu, rata-rata marginal adalah ringkasan deskriptif lintas konfigurasi, bukan eksperimen yang menahan seluruh parameter lain pada nilai tetap.
stopifnot(nrow(reg_grid_summary) == 360,
nrow(cls_grid_summary) == 720)
parameter_scores <- bind_rows(
reg_grid_summary %>% transmute(
model = "Regression", cp, minsplit, minbucket,
maxdepth, cv_score = cv_RMSE),
cls_grid_summary %>% transmute(
model = model, cp, minsplit, minbucket,
maxdepth, cv_score = cv_Balanced_Accuracy)
)
parameter_long <- parameter_scores %>%
pivot_longer(cols = c(cp, minsplit, minbucket, maxdepth),
names_to = "parameter", values_to = "value")
parameter_effect <- parameter_long %>%
group_by(model, parameter, value) %>%
summarise(mean_cv = mean(cv_score),
min_cv = min(cv_score), max_cv = max(cv_score),
configurations = n(), .groups = "drop")
parameter_coverage <- parameter_effect %>%
filter(model == "Regression") %>%
select(parameter, value, configurations) %>%
arrange(parameter, value)
knitr::kable(parameter_coverage,
caption = "Grid configurations represented per parameter")
reg_parameter_plot <- parameter_effect %>%
filter(model == "Regression") %>%
ggplot(aes(x = factor(value), y = mean_cv, group = 1)) +
geom_line(linewidth = 0.7) + geom_point(size = 2) +
facet_wrap(~ parameter, scales = "free_x", ncol = 2) +
labs(title = "Regression Tree — Hyperparameter Exploration",
subtitle = "Average 10-fold CV RMSE across grid configurations",
x = "Parameter Value", y = "Mean CV RMSE") +
theme_minimal(base_size = 12)
print(reg_parameter_plot)
Interpretasi. Rata-rata CV RMSE regresi relatif rendah pada cp sekitar 0,003–0,005 dan maxdepth = 5. Ini adalah ringkasan marginal; kombinasi terbaik tersendiri tetap dipilih berdasarkan nilai CV RMSE per konfigurasi.
stopifnot(nrow(reg_grid_summary) == 360,
nrow(cls_grid_summary) == 720)
parameter_scores <- bind_rows(
reg_grid_summary %>% transmute(
model = "Regression", cp, minsplit, minbucket,
maxdepth, cv_score = cv_RMSE),
cls_grid_summary %>% transmute(
model = model, cp, minsplit, minbucket,
maxdepth, cv_score = cv_Balanced_Accuracy)
)
parameter_long <- parameter_scores %>%
pivot_longer(cols = c(cp, minsplit, minbucket, maxdepth),
names_to = "parameter", values_to = "value")
parameter_effect <- parameter_long %>%
group_by(model, parameter, value) %>%
summarise(mean_cv = mean(cv_score),
min_cv = min(cv_score), max_cv = max(cv_score),
configurations = n(), .groups = "drop")
parameter_coverage <- parameter_effect %>%
filter(model == "Regression") %>%
select(parameter, value, configurations) %>%
arrange(parameter, value)
knitr::kable(parameter_coverage,
caption = "Grid configurations represented per parameter")
cls_parameter_plot <- parameter_effect %>%
filter(model %in% c("Gini", "Entropy")) %>%
ggplot(aes(x = factor(value), y = mean_cv,
group = model, color = model)) +
geom_line(linewidth = 0.7) + geom_point(size = 2) +
facet_wrap(~ parameter, scales = "free_x", ncol = 2) +
labs(title = "Classification Tree — Hyperparameter Exploration",
subtitle = "Average 10-fold CV Balanced Accuracy",
x = "Parameter Value", y = "Mean CV Balanced Accuracy",
color = "Splitting Criterion") +
theme_minimal(base_size = 12)
print(cls_parameter_plot)
Interpretasi. Rata-rata Balanced Accuracy Gini dan entropy relatif tinggi di sekitar cp = 0,003, tetapi pola keduanya berbeda ketika kedalaman dan batas jumlah observasi berubah.
reg_heatmap_data <- reg_grid_summary %>%
group_by(cp, maxdepth) %>%
summarise(mean_cv_rmse = mean(cv_RMSE), .groups = "drop")
reg_heatmap <- ggplot(reg_heatmap_data,
aes(x = factor(maxdepth),
y = factor(cp), fill = mean_cv_rmse)) +
geom_tile(color = "white", linewidth = 0.5) +
scale_fill_viridis_c(direction = -1, name = "CV RMSE") +
labs(title = "Regression Tree — CP × Maxdepth",
subtitle = "Average CV RMSE across minsplit and minbucket",
x = "Maxdepth", y = "CP") +
theme_minimal(base_size = 12)
print(reg_heatmap)
Interpretasi. Warna RMSE lebih rendah cenderung muncul untuk cp yang tidak terlalu besar dengan kedalaman moderat, khususnya sekitar 5–8. Kombinasi cp = 0 atau 0,0005 dengan maxdepth 15–30 justru mempunyai rata-rata RMSE lebih tinggi. Pohon yang diizinkan tumbuh sangat dalam tidak otomatis menggeneralisasi lebih baik.
cls_heatmap_data <- cls_grid_summary %>%
group_by(model, cp, maxdepth) %>%
summarise(mean_cv_balanced_accuracy = mean(cv_Balanced_Accuracy),
.groups = "drop")
cls_heatmap <- ggplot(cls_heatmap_data,
aes(x = factor(maxdepth), y = factor(cp),
fill = mean_cv_balanced_accuracy)) +
geom_tile(color = "white", linewidth = 0.5) +
facet_wrap(~ model) +
scale_fill_viridis_c(name = "Balanced Accuracy") +
labs(title = "Classification Tree — CP × Maxdepth",
subtitle = "Average CV Balanced Accuracy across other parameters",
x = "Maxdepth", y = "CP") +
theme_minimal(base_size = 12)
print(cls_heatmap)
Interpretasi. Pada Gini, rata-rata Balanced Accuracy relatif tinggi terlihat saat cp = 0,003 dengan maxdepth 15–30; entropy juga menunjukkan wilayah kinerja tinggi di sekitar cp = 0,003, dengan pola kedalaman yang berbeda. Setiap sel merupakan rerata kombinasi minsplit dan minbucket yang valid, bukan skor satu pohon tertentu.
Kode lengkap ini menunjukkan urutan komputasi tahap tersebut. Jalankan tahapan mulai dari Data Preparation agar objek yang diperlukan telah tersedia.
# HYPERPARAMETER EXPLORATION PLOTS — ALL 360 CONFIGURATIONS
stopifnot(nrow(reg_grid_summary) == 360,
nrow(cls_grid_summary) == 720)
parameter_scores <- bind_rows(
reg_grid_summary %>% transmute(
model = "Regression", cp, minsplit, minbucket,
maxdepth, cv_score = cv_RMSE),
cls_grid_summary %>% transmute(
model = model, cp, minsplit, minbucket,
maxdepth, cv_score = cv_Balanced_Accuracy)
)
parameter_long <- parameter_scores %>%
pivot_longer(cols = c(cp, minsplit, minbucket, maxdepth),
names_to = "parameter", values_to = "value")
parameter_effect <- parameter_long %>%
group_by(model, parameter, value) %>%
summarise(mean_cv = mean(cv_score),
min_cv = min(cv_score), max_cv = max(cv_score),
configurations = n(), .groups = "drop")
parameter_coverage <- parameter_effect %>%
filter(model == "Regression") %>%
select(parameter, value, configurations) %>%
arrange(parameter, value)
knitr::kable(parameter_coverage,
caption = "Grid configurations represented per parameter")
reg_parameter_plot <- parameter_effect %>%
filter(model == "Regression") %>%
ggplot(aes(x = factor(value), y = mean_cv, group = 1)) +
geom_line(linewidth = 0.7) + geom_point(size = 2) +
facet_wrap(~ parameter, scales = "free_x", ncol = 2) +
labs(title = "Regression Tree — Hyperparameter Exploration",
subtitle = "Average 10-fold CV RMSE across grid configurations",
x = "Parameter Value", y = "Mean CV RMSE") +
theme_minimal(base_size = 12)
print(reg_parameter_plot)
cls_parameter_plot <- parameter_effect %>%
filter(model %in% c("Gini", "Entropy")) %>%
ggplot(aes(x = factor(value), y = mean_cv,
group = model, color = model)) +
geom_line(linewidth = 0.7) + geom_point(size = 2) +
facet_wrap(~ parameter, scales = "free_x", ncol = 2) +
labs(title = "Classification Tree — Hyperparameter Exploration",
subtitle = "Average 10-fold CV Balanced Accuracy",
x = "Parameter Value", y = "Mean CV Balanced Accuracy",
color = "Splitting Criterion") +
theme_minimal(base_size = 12)
print(cls_parameter_plot)
reg_heatmap_data <- reg_grid_summary %>%
group_by(cp, maxdepth) %>%
summarise(mean_cv_rmse = mean(cv_RMSE), .groups = "drop")
reg_heatmap <- ggplot(reg_heatmap_data,
aes(x = factor(maxdepth),
y = factor(cp), fill = mean_cv_rmse)) +
geom_tile(color = "white", linewidth = 0.5) +
scale_fill_viridis_c(direction = -1, name = "CV RMSE") +
labs(title = "Regression Tree — CP × Maxdepth",
subtitle = "Average CV RMSE across minsplit and minbucket",
x = "Maxdepth", y = "CP") +
theme_minimal(base_size = 12)
print(reg_heatmap)
cls_heatmap_data <- cls_grid_summary %>%
group_by(model, cp, maxdepth) %>%
summarise(mean_cv_balanced_accuracy = mean(cv_Balanced_Accuracy),
.groups = "drop")
cls_heatmap <- ggplot(cls_heatmap_data,
aes(x = factor(maxdepth), y = factor(cp),
fill = mean_cv_balanced_accuracy)) +
geom_tile(color = "white", linewidth = 0.5) +
facet_wrap(~ model) +
scale_fill_viridis_c(name = "Balanced Accuracy") +
labs(title = "Classification Tree — CP × Maxdepth",
subtitle = "Average CV Balanced Accuracy across other parameters",
x = "Maxdepth", y = "CP") +
theme_minimal(base_size = 12)
print(cls_heatmap)Pada step function, batas interval ditentukan terlebih dahulu. CART menggunakan prinsip prediksi per wilayah yang serupa, tetapi batas dan variabel pemisahannya dipelajari dari data. Karena itu, aturan pada setiap cabang dan nilai pada terminal node perlu dibaca sebagai satu kesatuan: aturan menentukan kelompok observasi, sedangkan terminal node menentukan hasil prediksinya.
Untuk respons numerik, regression tree memilih split dengan menurunkan residual sum of squares (RSS) dan memberikan rata-rata respons pada setiap terminal node. Untuk respons kategorik, classification tree menggunakan komposisi kelas: Gini atau entropy membantu memilih split, sementara kelas dominan dan proporsi kelas pada terminal node menentukan hasil klasifikasi. Contoh perhitungan manual dan ilustrasi interaktif memperlihatkan bagaimana perubahan cutpoint dapat mengubah kelompok, nilai galat, atau impurity.
Pohon yang lebih besar dapat menurunkan kesalahan pelatihan, tetapi tidak otomatis lebih baik untuk data baru. Cost-complexity pruning membatasi banyaknya cabang, sedangkan cross-validation membandingkan kemampuan prediksi pada data yang tidak digunakan untuk melatih masing-masing fold. Pada analisis Wine Quality, model baseline regresi mempunyai lima terminal node; pemilihan CP melalui tabel CV internal tidak mengubah pohon tersebut. Eksplorasi berikutnya membandingkan 360 konfigurasi untuk masing-masing model regresi, Gini, dan entropy menggunakan 10-fold cross-validation pada data training.
Perbandingan berikut menggunakan 1.065 observasi data uji yang tidak dipakai untuk memilih hyperparameter. RMSE lebih kecil berarti kesalahan prediksi regresi lebih rendah, sedangkan Balanced Accuracy lebih besar berarti rata-rata kemampuan mengenali kedua kelas lebih baik.
| Model | Metrik data uji | Baseline | Grid search |
|---|---|---|---|
| Regression Tree | RMSE ↓ | 0,77330 | 0,75444 |
| Gini | Balanced Accuracy ↑ | 0,69875 | 0,70132 |
| Entropy | Balanced Accuracy ↑ | 0,70860 | 0,70762 |
Hasil regresi menunjukkan perbaikan pada data uji: RMSE turun dari 0,77330 menjadi 0,75444, MAE dari 0,60672 menjadi 0,58748, dan R² naik dari 0,2338 menjadi 0,2707. Pada klasifikasi, peningkatan Balanced Accuracy Gini hanya kecil, sedangkan entropy sedikit menurun. Sebagian metrik lain juga bergerak berlawanan arah, misalnya specificity dapat meningkat saat recall menurun. Karena itu, model tuned tidak boleh otomatis dianggap unggul pada semua aspek.
Inti pembelajaran CART adalah membaca aturan pemisahan, isi terminal node, kompleksitas pohon, dan kinerja data uji secara bersamaan. Konfigurasi dipilih berdasarkan cross-validation pada data training; data uji digunakan untuk menilai hasil akhir, bukan untuk mengganti pilihan parameter setelah skor diketahui.
Bacallado, S., & Taylor, J. (2022). Regression trees. STATS 202, Stanford University (based on James et al., 2021). Course notes.
James, G., Witten, D., Hastie, T., & Tibshirani, R. (2021). An Introduction to Statistical Learning: With Applications in R (2nd ed.), Chapter 8. Springer. https://www.statlearning.com/resources-second-edition
Breiman, L., Friedman, J. H., Olshen, R. A., & Stone, C. J. (1984). Classification and Regression Trees. Wadsworth.
Cortez, P., Cerdeira, A., Almeida, F., Matos, T., & Reis, J. (2009). Modeling wine preferences by data mining from physicochemical properties. Decision Support Systems, 47, 547–553. https://doi.org/10.1016/j.dss.2009.05.016
UCI Machine Learning Repository. Wine Quality [Dataset]. https://archive.ics.uci.edu/dataset/186/wine+quality
Dokumentasi R: rpart, rpart.plot, caret, dan rsample.
Classification and Regression Trees (CART) · RStudio Implementation
In the previous practicum, we studied step functions, which partition a predictor range into intervals and assign a constant prediction to each interval. This represents the predictor–response relationship without requiring a single curve to describe the entire range.
But what if the interval boundaries are not known? What if splitting on just one predictor is insufficient, and several characteristics must be considered together?
Classification and Regression Trees (CART) offer one approach. Rather than fixing the split points in advance, CART learns which predictor and threshold to use from the data. Each split creates two groups that may be split again, forming a decision tree whose terminal nodes provide predictions.
The practicum uses five main R packages to prepare data, fit and visualize CART models, and evaluate predictions. rsample is called using its namespace for the same stratified training–test split used in Practicum 10.
| Package | Role in the practicum | Main functions |
|---|---|---|
tidyverse |
Data manipulation, summaries and visualization | read_csv(), select(), mutate(), ggplot() |
rpart |
Tree fitting and complexity control | rpart(), rpart.control(), printcp(), prune() |
rpart.plot |
Tree structure and splitting-rule visualization | rpart.plot() |
caret |
Fold allocation and classification evaluation | createFolds(), confusionMatrix() |
knitr |
Tables and document output | kable() |
Install packages once when they are not already available:
install.packages(c("tidyverse", "rpart", "rpart.plot", "caret", "knitr"))
# Dependency for the Practicum 10 train–test split
install.packages("rsample")library(tidyverse)
library(rpart)
library(rpart.plot)
library(caret)
library(knitr)A regression tree predicts a numerical response by the mean response within each terminal region, whereas a classification tree predicts the majority class and summarizes its class proportions. Both construct a stepwise prediction function, but their splitting criteria are different.
Both CART variants use recursive binary splitting, but differ in how they select splits and produce terminal-node predictions. The next sections develop regression trees and RSS first, followed by pruning, then classification trees with Gini and entropy.
Read the relationship among predictor-space regions, decision rules, and predictions in the following figure.
The upper-left partition contains intersecting boundaries that cannot be produced by the recursive splitting procedure shown here. The upper-right panel has five rectangular regions that can be created by successive splits. The lower-left tree encodes the same sequence, while the lower-right surface gives a constant predicted height in each region. The partition, the decision tree, and the stepwise prediction surface are three views of the same model.
A regression tree is used for numerical outcomes. Each terminal node predicts the mean training response of observations assigned to that node. The baseball example below shows how an observation follows a sequence of rules from root to prediction.
The following STATS 202 figure presents a baseball regression tree alongside a Years–Hits partition for log-salary predictions. Both panels describe the same rules in different forms.
In the left-hand tree, Years < 4.5 leads directly to prediction 5.11 (region R1). For players with Years ≥ 4.5, Hits < 117.5 distinguishes R2 (prediction 6.00) from R3 (6.74). The vertical and horizontal lines in the right-hand plot represent those same rules. Leaf values are the training-region averages of log salary, not an exact salary for every individual.
Values are calculated from the published teaching example; they are not Wine Quality model predictions.
Exercise in matching predictor regions to decision-tree branches.
At each node, the method searches a predictor Xj and threshold s to form two disjoint regions. The interactive illustration below illustrates the relation among predictor-space partitions, the binary tree, and constant regional predictions.
Values are calculated from the published teaching example; they are not Wine Quality model predictions.
Exercise in matching predictor regions to decision-tree branches.
For regression tree region Rm, the terminal prediction is the average response of its Nm training observations:
The split is selected to reduce residual squared error, while classification uses class impurity.
The split is selected to minimize the squared difference between the observed responses and the mean in each child node:
The RSS improvement is Δ RSS=RSSparent-RSSsplit. The decision is greedy: the best immediate split is chosen within the current node rather than searching every possible complete tree.
Six hypothetical students have study hours X=(1,2,3,4,5,6) and exam scores Y=(40,42,44,70,72,74). This small example is separate from the Wine Quality dataset.
| Student | Hours | Score |
|---|---|---|
| A | 1 | 40 |
| B | 2 | 42 |
| C | 3 | 44 |
| D | 4 | 70 |
| E | 5 | 72 |
| F | 6 | 74 |
At the root, the predicted mean is ȳ=(40+42+44+70+72+74)/6=57. Thus,
Candidate thresholds are the midpoints between consecutive study-hour values. For example, at s=2.5, the left group scores (40,42) and has mean 41, yielding RSS 2. The right group scores (44,70,72,74) and has mean 65, yielding RSS 596. Therefore the total is 2+596=598.
| Cutpoint | Left size | Right size | RSS after split |
|---|---|---|---|
| 1.5 | 1 | 5 | 1019.2 |
| 2.5 | 2 | 4 | 598 |
| 3.5 | 3 | 3 | 16 |
| 4.5 | 4 | 2 | 598 |
| 5.5 | 5 | 1 | 1019.2 |
At the optimal s=3.5, the left mean is (40+42+44)/3=42 and its RSS is 8. The right mean is (70+72+74)/3=72 and its RSS is also 8. The combined RSS is 16, a reduction of 1366-16=1350.
After working through the candidate splits, adjust the cutpoint to compare subgroup means, RSS, and the reduction in RSS. The interactive example uses the same six observations.
Values are calculated from the published teaching example; they are not Wine Quality model predictions.
Students with less than 3.5 hours are assigned a prediction of 42; the other group is assigned 72. These are regional sample means, not the observed scores of every student. If no further splits are made, the two groups become terminal nodes.
A tree can keep partitioning observations into increasingly small regions. The STATS 202 example below moves beyond Years and Hits to features such as RBI, Walks, and Putouts. More branches yield a finer fit, but training error alone does not establish predictive quality.
Growing a tree with more terminal nodes can reduce training RSS, but overly complex trees may fit sample-specific variation and generalize poorly. Pruning removes branches to balance model fit against complexity.
Here |T| is the number of terminal nodes and α≥0 is the complexity penalty. Larger values of α can favour smaller trees even if their training RSS is higher.
Return to the six study-hour observations. A fully grown tree with one student per leaf has six leaves and RSS 0. Combining adjacent terminal nodes in successive steps produces candidate trees of sizes 6, 5, 4, 3, 2 and 1 with RSS of 0, 2, 4, 10, 16 and 1366, respectively. The sequence illustrates successive branch removal; tied increments may occur.
With α=7, compute C7(T)=RSS(T)+7|T|:
| Leaves | RSS | Penalty | Total cost |
|---|---|---|---|
| 6 | 0 | 42 | 42 |
| 5 | 2 | 35 | 37 |
| 4 | 4 | 28 | 32 |
| 3 | 10 | 21 | 31 |
| 2 | 16 | 14 | 30 |
| 1 | 1366 | 7 | 1373 |
The two-leaf tree minimizes cost at 30 in this illustration. The illustrative penalty α=7 was not chosen by cross-validation.
Vary the penalty below to compare candidate subtrees by RSS and leaf count. The selected tree minimizes cost complexity among the shown candidates.
Values are calculated from the published teaching example; they are not Wine Quality model predictions.
The black training-error curve keeps decreasing with tree size. The green cross-validation curve reaches a low point at a relatively small tree, then levels off or rises. The orange test curve need not follow the training curve either. Selecting complexity solely by training error can therefore retain branches that do not improve generalization; cross-validation supplies the selection criterion.
The selected tree below returns to three terminal regions with split thresholds at Years = 4.5 and Hits = 117.5. It illustrates how a simpler tree can be retained after comparing complexity; test error is not used to tune the tree.
A relatively large tree is grown and candidate subtrees are obtained through pruning. For each penalty, predictive MSE is estimated from K validation folds:
The test set remains untouched until final evaluation. The interactive illustration below summarizes how training, cross-validation and test error can differ as the tree grows.
Values are calculated from the published teaching example; they are not Wine Quality model predictions.
Conceptual illustration of complexity and validation error. The original STATS 202 plot is shown in the model-selection section.
In rpart, cp is a relative complexity parameter rather than the same numeric scale as α in this manual illustration.
A classification tree recursively seeks groups with increasingly homogeneous class composition. Whereas regression chooses splits using RSS, classification uses node-impurity criteria and predicts the most frequent class within each leaf.
For node m, the class-k proportion is \hat pmk=nmk/Nm, where nmk is the count in class k and Nm the node size. The class error, Gini index and entropy are
Gini or entropy is zero for a pure node; by convention 0log0=0. Each candidate split is assessed with a size-weighted impurity, for example
The preferred split minimizes this weighted value.
After defining Gini impurity, use the following small example to see how changing the cutpoint alters class composition, child-node impurity, and the resulting decrease in Gini. Only thresholds that produce two non-empty groups are eligible for comparison.
The two terminal nodes from the Heart example below both predict Yes, but their class compositions are different.
Node A contains 7 Yes and 4 No observations, giving a 63.6% Yes proportion and Gini = 0.463. Node B contains 9 Yes observations and no No cases (Gini = 0). Although both nodes predict Yes, Node B is more homogeneous. Gini measures within-node class purity; it does not by itself establish how accurately the tree will predict test data.
Values are calculated from the published teaching example; they are not Wine Quality model predictions.
Comparison of two Heart-example nodes: both predict Yes, but their class proportions differ.
Consider eight students with study hours 1–8 and outcomes Not Pass, Not Pass, Pass, Not Pass, Pass, Pass, Pass, Pass. These hypothetical observations are distinct from Wine Quality.
| Student | Study hours | Outcome |
|---|---|---|
| A | 1 | Not Pass |
| B | 2 | Not Pass |
| C | 3 | Pass |
| D | 4 | Not Pass |
| E | 5 | Pass |
| F | 6 | Pass |
| G | 7 | Pass |
| H | 8 | Pass |
At the root, five students Pass and three do not, yielding
At cutpoint s=4.5, the left group has one Pass and three Not Pass (G1=0.375), while the right group consists entirely of Pass observations (G2=0). Their equal sizes give
Across all candidate thresholds, the lowest weighted Gini occurs at 4.5.
| Cutpoint | Left (Pass/Not Pass) | Right (Pass/Not Pass) | Weighted Gini |
|---|---|---|---|
| 1.5 | 0 / 1 | 5 / 2 | 0.3571 |
| 2.5 | 0 / 2 | 5 / 1 | 0.2083 |
| 3.5 | 1 / 2 | 4 / 1 | 0.3667 |
| 4.5 | 1 / 3 | 4 / 0 | 0.1875 |
| 5.5 | 2 / 3 | 3 / 0 | 0.3000 |
| 6.5 | 3 / 3 | 2 / 0 | 0.3750 |
| 7.5 | 4 / 3 | 1 / 0 | 0.4286 |
Using natural-log entropy, the root value is approximately 0.6616 and the weighted split entropy at 4.5 is approximately 0.2812, so information gain is about 0.3804. For this example, entropy also chooses cutpoint 4.5.
Values are calculated from the published teaching example; they are not Wine Quality model predictions.
Teaching illustration. Reconstructed manual classification split for eight hypothetical students.
For less than 4.5 study hours, Not Pass is the majority class (3/4 = 75%). For at least 4.5 hours, all four training observations Pass (100%). The latter is the within-node training proportion, not a guarantee of perfect prediction on new data.
After calculating Gini for the eight students in the classification example above, explore how changing the cutpoint affects class proportions and weighted Gini for 16 synthetic observations.
Move the alcohol threshold for 16 synthetic observations. Watch the points, class composition and weighted Gini change.
CART on Wine Quality covers six baseline stages followed by parameter exploration with ten-fold cross-validation. The outputs below are computed when this Quarto document is rendered in RStudio.
The Wine Quality dataset is available from the UCI Machine Learning Repository and contains 6,497 Portuguese vinho verde observations: 1,599 red wines and 4,898 white wines. The version used here has 13 columns: type (wine type), eleven physicochemical measurements—fixed acidity, volatile acidity, citric acid, residual sugar, chlorides, free sulfur dioxide, total sulfur dioxide, density, pH, sulphates, and alcohol—and the sensory quality score quality. The source study is Cortez et al. (2009).
Both CART tasks use the same twelve predictors. Regression trees predict the numerical quality score; classification trees predict quality_class, defined as Not Good when quality < 6 and Good when quality ≥ 6. The alternative response is excluded from each predictor set to prevent target leakage.
As in Practicum 10, identical records are removed before the stratified 80% training / 20% testing split. Numerical predictors remain on their original scales, and type is treated as a factor. The results of each preparation step are available in separate tabs below the main code block.
Start with the class distribution, confirm that missing values are absent, and remove identical rows. Then perform the data split and define two different prediction targets.
wine_data <- wine_data %>%
mutate(quality_class = factor(
if_else(quality >= 6, "Good", "Not Good"),
levels = c("Not Good", "Good")
))
class_distribution <- wine_data %>%
count(quality_class, name = "frequency") %>%
mutate(percentage = round(100 * frequency / sum(frequency), 2))
knitr::kable(class_distribution,
caption = "Initial distribution of wine quality categories")
| Class | Count | Percent |
|---|---|---|
| Not Good | 2,384 | 36.69% |
| Good | 4,113 | 63.31% |
Interpretation. Before deduplication, 2,384 observations (36.69%) are Not Good and 4,113 (63.31%) are Good. This is the original class composition.
wine_data <- wine_data %>%
mutate(quality_class = factor(
if_else(quality >= 6, "Good", "Not Good"),
levels = c("Not Good", "Good")
))
class_distribution <- wine_data %>%
count(quality_class, name = "frequency") %>%
mutate(percentage = round(100 * frequency / sum(frequency), 2))
knitr::kable(class_distribution,
caption = "Initial distribution of wine quality categories")
missing_wine <- wine_data %>%
summarise(across(everything(), ~ sum(is.na(.x)))) %>%
pivot_longer(cols = everything(), names_to = "variable",
values_to = "missing_count")
knitr::kable(missing_wine, caption = "Missing values by variable")
| Variable | Missing |
|---|---|
| type | 0 |
| fixed acidity | 0 |
| volatile acidity | 0 |
| citric acid | 0 |
| residual sugar | 0 |
| chlorides | 0 |
| free sulfur dioxide | 0 |
| total sulfur dioxide | 0 |
| density | 0 |
| pH | 0 |
| sulphates | 0 |
| alcohol | 0 |
| quality | 0 |
| quality_class | 0 |
Interpretation. All fourteen variables, including the derived quality_class, contain no missing values. No imputation is required before fitting CART models.
wine_clean <- wine_data %>% distinct()
stopifnot(nrow(wine_clean) == 5320L)
duplicate_summary <- tibble(
stage = c("Before removal", "After removal"),
observations = c(nrow(wine_data), nrow(wine_clean))
)
knitr::kable(duplicate_summary,
caption = "Observations before and after duplicate removal")
| Stage | Observations |
|---|---|
| Before duplicate removal | 6.497 |
| After duplicate removal | 5.320 |
Interpretation. Removing 1,177 identical rows reduces the dataset from 6,497 to 5,320 observations. This occurs before train–test splitting so identical records cannot appear in both subsets.
wine_clean <- wine_data %>% distinct()
stopifnot(nrow(wine_clean) == 5320L)
duplicate_summary <- tibble(
stage = c("Before removal", "After removal"),
observations = c(nrow(wine_data), nrow(wine_clean))
)
knitr::kable(duplicate_summary,
caption = "Observations before and after duplicate removal")
wine_clean %>% count(quality_class, name = "frequency") %>%
mutate(percentage = round(100 * frequency / sum(frequency), 2)) %>%
knitr::kable(caption = "Class distribution after duplicate removal")
| Class | Count | Percent |
|---|---|---|
| Not Good | 1,988 | 37.37% |
| Good | 3,332 | 62.63% |
Interpretation. After cleaning, 1,988 observations (37.37%) are Not Good and 3,332 (62.63%) are Good. Because Good remains the majority class, accuracy alone is insufficient to describe classification performance.
set.seed(123)
split_wine <- rsample::initial_split(
wine_clean, prop = 0.80, strata = quality_class)
wine_train <- rsample::training(split_wine)
wine_test <- rsample::testing(split_wine)
dim(wine_train)
dim(wine_test)
split_summary <- bind_rows(
wine_train %>% mutate(dataset = "Training"),
wine_test %>% mutate(dataset = "Testing")
) %>% count(dataset, quality_class, name = "frequency") %>%
group_by(dataset) %>%
mutate(percentage = round(100 * frequency / sum(frequency), 2)) %>%
ungroup()
knitr::kable(split_summary,
caption = "Class distribution in training and testing data")
| Subset | Not Good | Good | Total |
|---|---|---|---|
| Training | 1.590 (37,37%) | 2.665 (62,63%) | 4.255 |
| Testing | 398 (37,37%) | 667 (62,63%) | 1.065 |
Interpretation. Stratified splitting preserves the distribution of Good and Not Good across the training and test sets. All parameter selection uses training data; the test set is reserved for final evaluation.
reg_train <- wine_train %>% select(-quality_class) %>%
mutate(type = factor(type, levels = c("red", "white")))
reg_test <- wine_test %>% select(-quality_class) %>%
mutate(type = factor(type, levels = c("red", "white")))
cls_train <- wine_train %>% select(-quality) %>%
mutate(type = factor(type, levels = c("red", "white")),
quality_class = factor(quality_class,
levels = c("Not Good", "Good")))
cls_test <- wine_test %>% select(-quality) %>%
mutate(type = factor(type, levels = c("red", "white")),
quality_class = factor(quality_class,
levels = c("Not Good", "Good")))
stopifnot(
identical(names(reg_train), names(reg_test)),
identical(names(cls_train), names(cls_test)),
is.numeric(reg_train$quality),
is.factor(cls_train$quality_class),
!anyNA(reg_train), !anyNA(reg_test),
!anyNA(cls_train), !anyNA(cls_test)
)
data_summary <- tibble(
method = c("Regression", "Regression",
"Classification", "Classification"),
dataset = c("Training", "Testing", "Training", "Testing"),
observations = c(nrow(reg_train), nrow(reg_test),
nrow(cls_train), nrow(cls_test)),
predictors = c(ncol(reg_train)-1, ncol(reg_test)-1,
ncol(cls_train)-1, ncol(cls_test)-1)
)
knitr::kable(data_summary,
caption = "Final data preparation summary for CART")
| Method | Subset | Observations | Predictors | Response |
|---|---|---|---|---|
| Regression | Training | 4.255 | 12 | quality (numeric) |
| Regression | Testing | 1.065 | 12 | quality (numeric) |
| Classification | Training | 4.255 | 12 | quality_class (factor) |
| Classification | Testing | 1.065 | 12 | quality_class (factor) |
Interpretation. The regression dataset excludes quality_class, whereas the classification dataset excludes quality, preventing target leakage. The predictor type is a factor; numeric predictors retain their original units.
This complete block shows the computational order for the stage. Run the stages from Data Preparation so dependencies are already available.
# PRACTICUM 11 — DATA PREPARATION (continuation of P10)
library(tidyverse)
library(rpart)
library(rpart.plot)
library(caret)
library(knitr)
if (!requireNamespace("rsample", quietly = TRUE)) {
stop("Install package rsample terlebih dahulu.")
}
# Temukan CSV Praktikum 10 secara otomatis dalam project RStudio yang sama.
# Pencarian dimulai dari lokasi dokumen dan dilanjutkan di project Sains Data 2026.
find_p10_wine_csv <- function(filename = "wine-quality-white-and-red.csv") {
wd <- normalizePath(getwd(), winslash = "/", mustWork = TRUE)
# Urutkan folder dari working directory hingga induknya.
ancestors <- wd
current <- wd
repeat {
parent <- dirname(current)
if (identical(parent, current)) break
ancestors <- c(ancestors, parent)
current <- parent
}
# Utamakan project Sains Data 2026 yang sudah digunakan sejak P10.
named_project <- ancestors[
tolower(basename(ancestors)) == "sains data 2026"
]
if (length(named_project) > 0) {
project_root <- named_project[1]
} else {
has_rproj <- vapply(ancestors, function(d) {
length(list.files(d, pattern = "[.]Rproj$")) > 0
}, logical(1))
project_candidates <- ancestors[has_rproj]
project_root <- if (length(project_candidates) > 0) {
tail(project_candidates, 1)
} else {
wd
}
}
# Cari CSV di dalam project aktif, bukan di luar direktori project.
project_idx <- match(project_root, ancestors)
search_dirs <- if (is.na(project_idx)) wd else ancestors[seq_len(project_idx)]
direct <- file.path(search_dirs, filename)
direct <- direct[file.exists(direct)]
matches <- list.files(
project_root,
pattern = "^wine-quality-white-and-red[.]csv$",
recursive = TRUE,
full.names = TRUE,
ignore.case = TRUE
)
candidates <- unique(normalizePath(
c(direct, matches), winslash = "/", mustWork = FALSE
))
candidates <- candidates[file.exists(candidates)]
if (length(candidates) == 0) {
stop("CSV P10 tidak ditemukan di project: ", project_root,
". Simpan wine-quality-white-and-red.csv dalam folder project Sains Data 2026.")
}
# Dua berkas bernama sama tidak boleh diam-diam dianggap dataset identik.
if (length(candidates) > 1) {
signatures <- unname(tools::md5sum(candidates))
if (length(unique(signatures)) != 1) {
stop("Beberapa CSV P10 dengan isi berbeda ditemukan: ",
paste(candidates, collapse = " | "),
". Tentukan satu versi CSV P10 yang benar sebelum render.")
}
}
in_p10 <- grepl("praktikum[ _-]*10|p10", candidates, ignore.case = TRUE)
candidates <- candidates[order(!in_p10, nchar(candidates), candidates)]
normalizePath(candidates[1], winslash = "/", mustWork = TRUE)
}
file_path <- find_p10_wine_csv()
wine_data <- read_csv(file_path, show_col_types = FALSE)
# Menjaga kesesuaian dengan dataset P10 yang digunakan dalam modul.
stopifnot(
nrow(wine_data) == 6497L,
ncol(wine_data) == 13L,
identical(names(wine_data), c(
"type", "fixed acidity", "volatile acidity", "citric acid",
"residual sugar", "chlorides", "free sulfur dioxide",
"total sulfur dioxide", "density", "pH", "sulphates", "alcohol",
"quality"
)),
sum(wine_data$type == "red") == 1599L,
sum(wine_data$type == "white") == 4898L,
sum(wine_data$quality >= 6) == 4113L
)
head(wine_data)
dim(wine_data)
names(wine_data)
glimpse(wine_data)
wine_data <- wine_data %>%
mutate(quality_class = factor(
if_else(quality >= 6, "Good", "Not Good"),
levels = c("Not Good", "Good")
))
class_distribution <- wine_data %>%
count(quality_class, name = "frequency") %>%
mutate(percentage = round(100 * frequency / sum(frequency), 2))
knitr::kable(class_distribution,
caption = "Initial distribution of wine quality categories")
missing_wine <- wine_data %>%
summarise(across(everything(), ~ sum(is.na(.x)))) %>%
pivot_longer(cols = everything(), names_to = "variable",
values_to = "missing_count")
knitr::kable(missing_wine, caption = "Missing values by variable")
stopifnot(!anyNA(wine_data))
wine_clean <- wine_data %>% distinct()
stopifnot(nrow(wine_clean) == 5320L)
duplicate_summary <- tibble(
stage = c("Before removal", "After removal"),
observations = c(nrow(wine_data), nrow(wine_clean))
)
knitr::kable(duplicate_summary,
caption = "Observations before and after duplicate removal")
wine_clean %>% count(quality_class, name = "frequency") %>%
mutate(percentage = round(100 * frequency / sum(frequency), 2)) %>%
knitr::kable(caption = "Class distribution after duplicate removal")
set.seed(123)
split_wine <- rsample::initial_split(
wine_clean, prop = 0.80, strata = quality_class)
wine_train <- rsample::training(split_wine)
wine_test <- rsample::testing(split_wine)
dim(wine_train)
dim(wine_test)
split_summary <- bind_rows(
wine_train %>% mutate(dataset = "Training"),
wine_test %>% mutate(dataset = "Testing")
) %>% count(dataset, quality_class, name = "frequency") %>%
group_by(dataset) %>%
mutate(percentage = round(100 * frequency / sum(frequency), 2)) %>%
ungroup()
knitr::kable(split_summary,
caption = "Class distribution in training and testing data")
reg_train <- wine_train %>% select(-quality_class) %>%
mutate(type = factor(type, levels = c("red", "white")))
reg_test <- wine_test %>% select(-quality_class) %>%
mutate(type = factor(type, levels = c("red", "white")))
cls_train <- wine_train %>% select(-quality) %>%
mutate(type = factor(type, levels = c("red", "white")),
quality_class = factor(quality_class,
levels = c("Not Good", "Good")))
cls_test <- wine_test %>% select(-quality) %>%
mutate(type = factor(type, levels = c("red", "white")),
quality_class = factor(quality_class,
levels = c("Not Good", "Good")))
stopifnot(
identical(names(reg_train), names(reg_test)),
identical(names(cls_train), names(cls_test)),
is.numeric(reg_train$quality),
is.factor(cls_train$quality_class),
!anyNA(reg_train), !anyNA(reg_test),
!anyNA(cls_train), !anyNA(cls_test)
)
data_summary <- tibble(
method = c("Regression", "Regression",
"Classification", "Classification"),
dataset = c("Training", "Testing", "Training", "Testing"),
observations = c(nrow(reg_train), nrow(reg_test),
nrow(cls_train), nrow(cls_test)),
predictors = c(ncol(reg_train)-1, ncol(reg_test)-1,
ncol(cls_train)-1, ncol(cls_test)-1)
)
knitr::kable(data_summary,
caption = "Final data preparation summary for CART")
class(reg_train$quality)
class(cls_train$quality_class)
levels(cls_train$quality_class)
glimpse(reg_train)
glimpse(cls_train)
cat("\nDATA PREPARATION COMPLETED\n")The baseline regression tree uses the ANOVA split criterion, cp = 0.01, minsplit = 20, minbucket = 7, and internal ten-fold validation. The model output provides all splitting rules and terminal predictions.
The same fitted tree produces structural summaries, split rules, a tree diagram, and node-level RSS.
Fit the baseline model first, inspect its nodes and splitting rules, then connect the tree diagram with its residual sum of squares.
set.seed(123)
reg_tree <- rpart(
quality ~ ., data = reg_train, method = "anova",
control = rpart.control(
minsplit = 20, minbucket = 7, cp = 0.01, xval = 10
)
)
tree_frame <- reg_tree$frame
tree_structure <- tibble(
internal_nodes = sum(tree_frame$var != "<leaf>"),
terminal_nodes = sum(tree_frame$var == "<leaf>"),
total_nodes = nrow(tree_frame)
)
knitr::kable(tree_structure,
caption = "Initial regression tree structure")
| Internal nodes | Terminal nodes | Total nodes | Training rows |
|---|---|---|---|
| 4 | 5 | 9 | 4.255 |
Interpretation. The baseline tree divides 4,255 training observations using four internal nodes and five terminal nodes. Consequently, it assigns one of five distinct predictions to each observation. The root mean of 5.798 is the starting estimate before any split.
set.seed(123)
reg_tree <- rpart(
quality ~ ., data = reg_train, method = "anova",
control = rpart.control(
minsplit = 20, minbucket = 7, cp = 0.01, xval = 10
)
)
print(reg_tree)
| Terminal node | Split path (full precision) | Observations | Predicted quality |
|---|---|---|---|
| 4 | alcohol < 11,05833; volatile acidity ≥ 0,2825 | 1.520 | 5,338816 |
| 10 | alcohol < 10,11667; volatile acidity < 0,2825 | 807 | 5,629492 |
| 11 | 10,11667 ≤ alcohol < 11,05833; volatile acidity < 0,2825 | 590 | 6,011864 |
| 6 | 11,05833 ≤ alcohol < 11,92 | 660 | 6,124242 |
| 7 | alcohol ≥ 11,92 | 678 | 6,525074 |
Interpretation. The root splits at alcohol < 11.05833. The left branch has mean quality around 5.555 and the right around 6.327. Later splits reuse alcohol and volatile acidity; terminal predictions range roughly from 5.339 to 6.525. These are predictive patterns, not evidence of causation.
set.seed(123)
reg_tree <- rpart(
quality ~ ., data = reg_train, method = "anova",
control = rpart.control(
minsplit = 20, minbucket = 7, cp = 0.01, xval = 10
)
)
rpart.plot(
reg_tree, type = 2, extra = 101, under = TRUE,
fallen.leaves = TRUE, faclen = 0, digits = 3,
main = "Initial Regression Tree — Wine Quality"
)
Interpretation. The diagram contains five terminal nodes, so baseline predictions take only five values. Alcohol forms the first split, while alcohol and volatile acidity divide subsequent branches. The compact structure provides a useful baseline for comparison with the more complex tuned tree.
set.seed(123)
reg_tree <- rpart(
quality ~ ., data = reg_train, method = "anova",
control = rpart.control(
minsplit = 20, minbucket = 7, cp = 0.01, xval = 10
)
)
tree_frame <- reg_tree$frame
node_summary <- tibble(
node = as.integer(rownames(tree_frame)),
split_variable = tree_frame$var,
observations = tree_frame$n,
predicted_quality = round(tree_frame$yval, 3),
RSS = round(tree_frame$dev, 3)
)
knitr::kable(node_summary,
caption = "Regression tree node summary")
| Node | Type | n | RSS |
|---|---|---|---|
| 1 | Root | 4.255 | 3.285,585 |
| 4 | Leaf | 1.520 | 724,510 |
| 10 | Leaf | 807 | 428,218 |
| 11 | Leaf | 590 | 398,917 |
| 6 | Leaf | 660 | 489,812 |
| 7 | Leaf | 678 | 445,074 |
Interpretation. The root RSS of 3,285.585 is the squared-error total for one overall prediction. After the tree forms five regions, the combined terminal RSS is 2,486.531, a reduction of about 799.054 on training data. Improvement on new data must still be assessed separately.
This complete block shows the computational order for the stage. Run the stages from Data Preparation so dependencies are already available.
# REGRESSION TREE — BASELINE
set.seed(123)
reg_tree <- rpart(
quality ~ ., data = reg_train, method = "anova",
control = rpart.control(
minsplit = 20, minbucket = 7, cp = 0.01, xval = 10
)
)
print(reg_tree)
reg_tree$control
tree_frame <- reg_tree$frame
tree_structure <- tibble(
internal_nodes = sum(tree_frame$var != "<leaf>"),
terminal_nodes = sum(tree_frame$var == "<leaf>"),
total_nodes = nrow(tree_frame)
)
knitr::kable(tree_structure,
caption = "Initial regression tree structure")
node_summary <- tibble(
node = as.integer(rownames(tree_frame)),
split_variable = tree_frame$var,
observations = tree_frame$n,
predicted_quality = round(tree_frame$yval, 3),
RSS = round(tree_frame$dev, 3)
)
knitr::kable(node_summary,
caption = "Regression tree node summary")
rpart.plot(
reg_tree, type = 2, extra = 101, under = TRUE,
fallen.leaves = TRUE, faclen = 0, digits = 3,
main = "Initial Regression Tree — Wine Quality"
)The complexity table and internal cross-validation identify the subtree with minimum xerror. Pruning is based entirely on the training data.
CP selection and pruning use the fixed baseline tree; each result appears with its own explanation.
Inspect the CP table and cross-validation error before choosing a complexity parameter. Finally compare the tree before and after pruning.
printcp(reg_tree)
reg_cp_table <- reg_tree$cptable
knitr::kable(round(reg_cp_table, 5),
caption = "Complexity parameter table — Regression Tree")
| CP | nsplit | rel error | xerror | xstd |
|---|---|---|---|---|
| 0,16638 | 0 | 1,00000 | 1,00046 | 0,02309 |
| 0,04530 | 1 | 0,83362 | 0,85649 | 0,02216 |
| 0,01635 | 2 | 0,78832 | 0,80259 | 0,02145 |
| 0,01517 | 3 | 0,77197 | 0,79260 | 0,02117 |
| 0,01000 | 4 | 0,75680 | 0,77728 | 0,02076 |
Interpretation. As the number of splits rises from zero to four, cross-validation relative error tends to decrease. The smallest reported xerror is 0.77728 at cp = 0.01 and five terminal nodes. This relative measure is not the test-set RMSE.
plotcp(reg_tree, minline = TRUE)
title(main = "Regression Tree — Cross-Validation Error")
Interpretation. The curve illustrates the CP table: cross-validation relative error falls as available subtrees grow, reaching its lowest point with five terminal nodes. It does not imply that unconstrained growth will always improve predictive accuracy.
best_cp_index <- which.min(reg_cp_table[, "xerror"])
best_cp <- reg_cp_table[best_cp_index, "CP"]
cp_selection <- tibble(
selected_cp = best_cp,
nsplit = reg_cp_table[best_cp_index, "nsplit"],
terminal_nodes = nsplit + 1,
relative_error = reg_cp_table[best_cp_index, "rel error"],
cv_error = reg_cp_table[best_cp_index, "xerror"],
cv_std = reg_cp_table[best_cp_index, "xstd"]
)
knitr::kable(cp_selection, digits = 5,
caption = "Selected CP based on minimum CV error")
| Selected CP | Splits | Terminal nodes | Relative error | CV error | xstd |
|---|---|---|---|---|---|
| 0,01000 | 4 | 5 | 0,75680 | 0,77728 | 0,02076 |
Interpretation. The selected cp is 0.01, with the smallest observed xerror of 0.77728. This selection only compares subtrees that exist within the baseline tree; it is not a claim about every possible hyperparameter configuration.
best_cp_index <- which.min(reg_cp_table[, "xerror"])
best_cp <- reg_cp_table[best_cp_index, "CP"]
cp_selection <- tibble(
selected_cp = best_cp,
nsplit = reg_cp_table[best_cp_index, "nsplit"],
terminal_nodes = nsplit + 1,
relative_error = reg_cp_table[best_cp_index, "rel error"],
cv_error = reg_cp_table[best_cp_index, "xerror"],
cv_std = reg_cp_table[best_cp_index, "xstd"]
)
knitr::kable(cp_selection, digits = 5,
caption = "Selected CP based on minimum CV error")
reg_tree_pruned <- prune(reg_tree, cp = best_cp)
print(reg_tree_pruned)
rpart.plot(
reg_tree_pruned, type = 2, extra = 101,
under = TRUE, fallen.leaves = TRUE,
faclen = 0, digits = 3,
main = "Pruned Regression Tree — Wine Quality"
)
Interpretation. The pruned plot is unchanged from baseline and still has five leaves. At the selected cp = 0.01, there are no additional branches to discard on the available cost-complexity path. An unchanged tree is a valid pruning outcome.
best_cp_index <- which.min(reg_cp_table[, "xerror"])
best_cp <- reg_cp_table[best_cp_index, "CP"]
cp_selection <- tibble(
selected_cp = best_cp,
nsplit = reg_cp_table[best_cp_index, "nsplit"],
terminal_nodes = nsplit + 1,
relative_error = reg_cp_table[best_cp_index, "rel error"],
cv_error = reg_cp_table[best_cp_index, "xerror"],
cv_std = reg_cp_table[best_cp_index, "xstd"]
)
knitr::kable(cp_selection, digits = 5,
caption = "Selected CP based on minimum CV error")
reg_tree_pruned <- prune(reg_tree, cp = best_cp)
print(reg_tree_pruned)
rpart.plot(
reg_tree_pruned, type = 2, extra = 101,
under = TRUE, fallen.leaves = TRUE,
faclen = 0, digits = 3,
main = "Pruned Regression Tree — Wine Quality"
)
tree_info <- function(model, label) {
frame <- model$frame
is_leaf <- frame$var == "<leaf>"
tibble(
model = label,
internal_nodes = sum(!is_leaf),
terminal_nodes = sum(is_leaf),
total_nodes = nrow(frame),
training_RSS = sum(frame$dev[is_leaf])
)
}
tree_comparison <- bind_rows(
tree_info(reg_tree, "Initial Tree"),
tree_info(reg_tree_pruned, "Pruned Tree")
)
| Model | Internal nodes | Terminal nodes | Total nodes | Training RSS |
|---|---|---|---|---|
| Initial Tree | 4 | 5 | 9 | 2.486,531 |
| Pruned Tree | 4 | 5 | 9 | 2.486,531 |
Interpretation. Both trees have five terminal nodes and training RSS of 2,486.531. Neither the pruning decision nor cp selection uses the test observations.
This complete block shows the computational order for the stage. Run the stages from Data Preparation so dependencies are already available.
# TREE COMPLEXITY AND PRUNING
printcp(reg_tree)
reg_cp_table <- reg_tree$cptable
knitr::kable(round(reg_cp_table, 5),
caption = "Complexity parameter table — Regression Tree")
plotcp(reg_tree, minline = TRUE)
title(main = "Regression Tree — Cross-Validation Error")
best_cp_index <- which.min(reg_cp_table[, "xerror"])
best_cp <- reg_cp_table[best_cp_index, "CP"]
cp_selection <- tibble(
selected_cp = best_cp,
nsplit = reg_cp_table[best_cp_index, "nsplit"],
terminal_nodes = nsplit + 1,
relative_error = reg_cp_table[best_cp_index, "rel error"],
cv_error = reg_cp_table[best_cp_index, "xerror"],
cv_std = reg_cp_table[best_cp_index, "xstd"]
)
knitr::kable(cp_selection, digits = 5,
caption = "Selected CP based on minimum CV error")
reg_tree_pruned <- prune(reg_tree, cp = best_cp)
print(reg_tree_pruned)
rpart.plot(
reg_tree_pruned, type = 2, extra = 101,
under = TRUE, fallen.leaves = TRUE,
faclen = 0, digits = 3,
main = "Pruned Regression Tree — Wine Quality"
)
tree_info <- function(model, label) {
frame <- model$frame
is_leaf <- frame$var == "<leaf>"
tibble(
model = label,
internal_nodes = sum(!is_leaf),
terminal_nodes = sum(is_leaf),
total_nodes = nrow(frame),
training_RSS = sum(frame$dev[is_leaf])
)
}
tree_comparison <- bind_rows(
tree_info(reg_tree, "Initial Tree"),
tree_info(reg_tree_pruned, "Pruned Tree")
)
knitr::kable(tree_comparison, digits = 3,
caption = "Regression Tree complexity before/after pruning")
if (tree_comparison$terminal_nodes[1] ==
tree_comparison$terminal_nodes[2]) {
cat("Pruning mempertahankan ukuran pohon baseline.\n")
} else {
cat("Pruning menghasilkan pohon yang lebih sederhana.\n")
}The selected regression tree is evaluated on 1,065 held-out observations using RMSE, MAE, predictive R², and an observed-versus-predicted plot.
Test evaluation is performed only after model complexity has been selected on training data.
Start with individual predictions, continue with test-set metrics, and use the figure to examine error patterns that a single score cannot reveal.
reg_pred <- predict(reg_tree_pruned, newdata = reg_test, type = "vector")
reg_results <- tibble(
actual = reg_test$quality,
predicted = as.numeric(reg_pred)
) %>% mutate(residual = actual - predicted)
stopifnot(nrow(reg_results) == nrow(reg_test),
all(is.finite(reg_results$predicted)))
knitr::kable(head(reg_results, 10), digits = 3,
caption = "First 10 regression predictions on test data")
| Actual | Predicted | Residual |
|---|---|---|
| 6 | 5,629 | 0,371 |
| 5 | 5,339 | −0,339 |
| 6 | 5,629 | 0,371 |
| 6 | 6,012 | −0,012 |
| 4 | 5,339 | −1,339 |
| 7 | 6,525 | 0,475 |
| 7 | 6,525 | 0,475 |
| 5 | 5,339 | −0,339 |
| 6 | 5,339 | 0,661 |
| 5 | 5,629 | −0,629 |
Interpretation. Compare actual quality, the tree prediction and the residual for each displayed test observation. Positive residuals mean the actual quality exceeds the prediction; negative values mean overprediction. Repeated predicted values arise naturally from the five leaves.
reg_pred <- predict(reg_tree_pruned, newdata = reg_test, type = "vector")
reg_results <- tibble(
actual = reg_test$quality,
predicted = as.numeric(reg_pred)
) %>% mutate(residual = actual - predicted)
stopifnot(nrow(reg_results) == nrow(reg_test),
all(is.finite(reg_results$predicted)))
knitr::kable(head(reg_results, 10), digits = 3,
caption = "First 10 regression predictions on test data")
actual <- reg_results$actual
predicted <- reg_results$predicted
rmse <- sqrt(mean((actual - predicted)^2))
mae <- mean(abs(actual - predicted))
r2 <- 1 - sum((actual - predicted)^2) /
sum((actual - mean(actual))^2)
reg_metrics <- tibble(
model = "Regression Tree (Baseline + Pruning)",
RMSE = rmse, MAE = mae, R2 = r2
)
knitr::kable(reg_metrics, digits = 4,
caption = "Regression Tree performance on test data")
| Model | RMSE | MAE | R² |
|---|---|---|---|
| Regression Tree Baseline + Pruning | 0,7733 | 0,6067 | 0,2338 |
Interpretation. On held-out data, RMSE is 0.7733 and MAE is 0.6067 quality points. RMSE penalizes larger errors more heavily, explaining its larger value. R² = 0.2338 indicates only a modest reduction in squared error relative to a constant test-set benchmark.
reg_pred <- predict(reg_tree_pruned, newdata = reg_test, type = "vector")
reg_results <- tibble(
actual = reg_test$quality,
predicted = as.numeric(reg_pred)
) %>% mutate(residual = actual - predicted)
stopifnot(nrow(reg_results) == nrow(reg_test),
all(is.finite(reg_results$predicted)))
knitr::kable(head(reg_results, 10), digits = 3,
caption = "First 10 regression predictions on test data")
actual <- reg_results$actual
predicted <- reg_results$predicted
rmse <- sqrt(mean((actual - predicted)^2))
mae <- mean(abs(actual - predicted))
r2 <- 1 - sum((actual - predicted)^2) /
sum((actual - mean(actual))^2)
reg_metrics <- tibble(
model = "Regression Tree (Baseline + Pruning)",
RMSE = rmse, MAE = mae, R2 = r2
)
knitr::kable(reg_metrics, digits = 4,
caption = "Regression Tree performance on test data")
reg_plot <- ggplot(reg_results,
aes(x = actual, y = predicted)) +
geom_point(alpha = 0.25, size = 1.6) +
geom_abline(intercept = 0, slope = 1, linetype = "dashed") +
labs(title = "Actual vs Predicted Wine Quality",
subtitle = "Baseline Regression Tree — Test Data",
x = "Actual Quality", y = "Predicted Quality") +
theme_minimal(base_size = 12)
print(reg_plot)
Interpretation. Five horizontal prediction bands appear because the baseline tree has five leaves. Actual scores are more dispersed than predicted scores, especially near the extremes, so the model tends to pull the lowest and highest values toward the middle.
This complete block shows the computational order for the stage. Run the stages from Data Preparation so dependencies are already available.
# REGRESSION TREE — TEST EVALUATION
reg_pred <- predict(reg_tree_pruned, newdata = reg_test, type = "vector")
reg_results <- tibble(
actual = reg_test$quality,
predicted = as.numeric(reg_pred)
) %>% mutate(residual = actual - predicted)
stopifnot(nrow(reg_results) == nrow(reg_test),
all(is.finite(reg_results$predicted)))
knitr::kable(head(reg_results, 10), digits = 3,
caption = "First 10 regression predictions on test data")
actual <- reg_results$actual
predicted <- reg_results$predicted
rmse <- sqrt(mean((actual - predicted)^2))
mae <- mean(abs(actual - predicted))
r2 <- 1 - sum((actual - predicted)^2) /
sum((actual - mean(actual))^2)
reg_metrics <- tibble(
model = "Regression Tree (Baseline + Pruning)",
RMSE = rmse, MAE = mae, R2 = r2
)
knitr::kable(reg_metrics, digits = 4,
caption = "Regression Tree performance on test data")
reg_plot <- ggplot(reg_results,
aes(x = actual, y = predicted)) +
geom_point(alpha = 0.25, size = 1.6) +
geom_abline(intercept = 0, slope = 1, linetype = "dashed") +
labs(title = "Actual vs Predicted Wine Quality",
subtitle = "Baseline Regression Tree — Test Data",
x = "Actual Quality", y = "Predicted Quality") +
theme_minimal(base_size = 12)
print(reg_plot)
reg_pred_initial <- predict(reg_tree, newdata = reg_test,
type = "vector")
identical(as.numeric(reg_pred_initial), as.numeric(reg_pred))Two baseline classification trees use Gini and entropy on identical training data and growth settings. Only the impurity criterion differs.
Gini and entropy use binary tree splitting with different impurity criteria and may produce different class compositions.
Examine both tree structures, inspect their diagrams, and then read class probabilities at terminal nodes. A more complex tree is not necessarily more accurate.
set.seed(123)
cls_tree_gini <- rpart(
quality_class ~ ., data = cls_train, method = "class",
parms = list(split = "gini"),
control = rpart.control(
minsplit = 20, minbucket = 7, cp = 0.01, xval = 10
)
)
set.seed(123)
cls_tree_entropy <- rpart(
quality_class ~ ., data = cls_train, method = "class",
parms = list(split = "information"),
control = rpart.control(
minsplit = 20, minbucket = 7, cp = 0.01, xval = 10
)
)
class_tree_info <- function(model, label) {
frame <- model$frame
is_leaf <- frame$var == "<leaf>"
tibble(model = label, internal_nodes = sum(!is_leaf),
terminal_nodes = sum(is_leaf), total_nodes = nrow(frame))
}
cls_structure <- bind_rows(
class_tree_info(cls_tree_gini, "Gini"),
class_tree_info(cls_tree_entropy, "Entropy")
)
knitr::kable(cls_structure,
caption = "Baseline classification tree structures")
| Model | Internal nodes | Terminal nodes | Total nodes | Root split |
|---|---|---|---|---|
| Gini | 2 | 3 | 5 | alcohol |
| Entropy | 5 | 6 | 11 | alcohol |
Interpretation. Both classifiers split first at alcohol < 10.01667, but Gini forms three leaves and entropy forms six. The shared root shows a similar dominant initial partition, while different branches show how split criteria can favor different subsequent partitions.
set.seed(123)
cls_tree_gini <- rpart(
quality_class ~ ., data = cls_train, method = "class",
parms = list(split = "gini"),
control = rpart.control(
minsplit = 20, minbucket = 7, cp = 0.01, xval = 10
)
)
set.seed(123)
cls_tree_entropy <- rpart(
quality_class ~ ., data = cls_train, method = "class",
parms = list(split = "information"),
control = rpart.control(
minsplit = 20, minbucket = 7, cp = 0.01, xval = 10
)
)
rpart.plot(cls_tree_gini, type = 2, extra = 104,
under = TRUE, fallen.leaves = TRUE,
faclen = 0, digits = 3,
main = "Classification Tree — Gini Index")
Interpretation. Below the initial alcohol threshold, volatile acidity separates two regions with different class composition. The Gini tree has three leaves, each predicting the class most common in its training observations; a leaf label is not a guarantee that every observation belongs to that class.
set.seed(123)
cls_tree_gini <- rpart(
quality_class ~ ., data = cls_train, method = "class",
parms = list(split = "gini"),
control = rpart.control(
minsplit = 20, minbucket = 7, cp = 0.01, xval = 10
)
)
set.seed(123)
cls_tree_entropy <- rpart(
quality_class ~ ., data = cls_train, method = "class",
parms = list(split = "information"),
control = rpart.control(
minsplit = 20, minbucket = 7, cp = 0.01, xval = 10
)
)
rpart.plot(cls_tree_entropy, type = 2, extra = 104,
under = TRUE, fallen.leaves = TRUE,
faclen = 0, digits = 3,
main = "Classification Tree — Entropy")
Interpretation. The entropy tree begins with the same alcohol threshold but grows to six terminal nodes, also splitting on volatile acidity, free sulfur dioxide and sulphates. Greater structural detail is not itself proof of better test accuracy.
set.seed(123)
cls_tree_gini <- rpart(
quality_class ~ ., data = cls_train, method = "class",
parms = list(split = "gini"),
control = rpart.control(
minsplit = 20, minbucket = 7, cp = 0.01, xval = 10
)
)
set.seed(123)
cls_tree_entropy <- rpart(
quality_class ~ ., data = cls_train, method = "class",
parms = list(split = "information"),
control = rpart.control(
minsplit = 20, minbucket = 7, cp = 0.01, xval = 10
)
)
class_leaf_summary <- function(model, label) {
frame <- model$frame
is_leaf <- frame$var == "<leaf>"
node_values <- frame$yval2
tibble(
model = label,
node = as.integer(rownames(frame)[is_leaf]),
observations = frame$n[is_leaf],
predicted_class = levels(cls_train$quality_class)[
frame$yval[is_leaf]
],
prob_not_good = round(node_values[is_leaf, 4], 4),
prob_good = round(node_values[is_leaf, 5], 4)
)
}
cls_leaf_summary <- bind_rows(
class_leaf_summary(cls_tree_gini, "Gini"),
class_leaf_summary(cls_tree_entropy, "Entropy")
)
knitr::kable(cls_leaf_summary,
caption = "Predicted class and probabilities at terminal nodes")
| Model | Node | n | Class | P(Not Good) | P(Good) |
|---|---|---|---|---|---|
| Gini | 4 | 1.361 | Not Good | 0,6694 | 0,3306 |
| Gini | 5 | 407 | Good | 0,3366 | 0,6634 |
| Gini | 3 | 2.487 | Good | 0,2179 | 0,7821 |
| Entropy | 4 | 1.230 | Not Good | 0,6854 | 0,3146 |
| Entropy | 5 | 538 | Good | 0,3810 | 0,6190 |
| Entropy | 24 | 209 | Not Good | 0,6220 | 0,3780 |
| Entropy | 25 | 204 | Good | 0,2843 | 0,7157 |
| Entropy | 13 | 1.277 | Good | 0,2349 | 0,7651 |
| Entropy | 7 | 797 | Good | 0,0678 | 0,9322 |
Interpretation. The predicted class is the majority class at each terminal node. Class probabilities are proportions of training observations within that node, not necessarily calibrated predictive probabilities. The classification-tree loss column counts minority observations; it is not Gini or entropy itself.
This complete block shows the computational order for the stage. Run the stages from Data Preparation so dependencies are already available.
# CLASSIFICATION TREE — GINI AND ENTROPY
set.seed(123)
cls_tree_gini <- rpart(
quality_class ~ ., data = cls_train, method = "class",
parms = list(split = "gini"),
control = rpart.control(
minsplit = 20, minbucket = 7, cp = 0.01, xval = 10
)
)
set.seed(123)
cls_tree_entropy <- rpart(
quality_class ~ ., data = cls_train, method = "class",
parms = list(split = "information"),
control = rpart.control(
minsplit = 20, minbucket = 7, cp = 0.01, xval = 10
)
)
print(cls_tree_gini)
print(cls_tree_entropy)
cls_tree_gini$parms
cls_tree_entropy$parms
class_tree_info <- function(model, label) {
frame <- model$frame
is_leaf <- frame$var == "<leaf>"
tibble(model = label, internal_nodes = sum(!is_leaf),
terminal_nodes = sum(is_leaf), total_nodes = nrow(frame))
}
cls_structure <- bind_rows(
class_tree_info(cls_tree_gini, "Gini"),
class_tree_info(cls_tree_entropy, "Entropy")
)
knitr::kable(cls_structure,
caption = "Baseline classification tree structures")
rpart.plot(cls_tree_gini, type = 2, extra = 104,
under = TRUE, fallen.leaves = TRUE,
faclen = 0, digits = 3,
main = "Classification Tree — Gini Index")
rpart.plot(cls_tree_entropy, type = 2, extra = 104,
under = TRUE, fallen.leaves = TRUE,
faclen = 0, digits = 3,
main = "Classification Tree — Entropy")
class_leaf_summary <- function(model, label) {
frame <- model$frame
is_leaf <- frame$var == "<leaf>"
node_values <- frame$yval2
tibble(
model = label,
node = as.integer(rownames(frame)[is_leaf]),
observations = frame$n[is_leaf],
predicted_class = levels(cls_train$quality_class)[
frame$yval[is_leaf]
],
prob_not_good = round(node_values[is_leaf, 4], 4),
prob_good = round(node_values[is_leaf, 5], 4)
)
}
cls_leaf_summary <- bind_rows(
class_leaf_summary(cls_tree_gini, "Gini"),
class_leaf_summary(cls_tree_entropy, "Entropy")
)
knitr::kable(cls_leaf_summary,
caption = "Predicted class and probabilities at terminal nodes")The test-set confusion matrices provide accuracy, precision, recall, F1, and specificity. Good is the positive class.
Both confusion matrices use Good as the positive class; metrics are interpreted per output.
Inspect predicted classes and probabilities, read both confusion matrices, and compare metrics for recognizing Good and Not Good observations.
cls_pred_gini <- predict(cls_tree_gini, newdata = cls_test,
type = "class")
cls_prob_gini <- predict(cls_tree_gini, newdata = cls_test,
type = "prob")
cls_pred_entropy <- predict(cls_tree_entropy, newdata = cls_test,
type = "class")
cls_prob_entropy <- predict(cls_tree_entropy,
newdata = cls_test, type = "prob")
stopifnot(
length(cls_pred_gini) == nrow(cls_test),
length(cls_pred_entropy) == nrow(cls_test),
identical(levels(cls_pred_gini), levels(cls_test$quality_class)),
identical(levels(cls_pred_entropy), levels(cls_test$quality_class)),
all(is.finite(cls_prob_gini)),
all(is.finite(cls_prob_entropy))
)
cls_results <- tibble(
actual = cls_test$quality_class,
predicted_gini = cls_pred_gini,
prob_good_gini = cls_prob_gini[, "Good"],
predicted_entropy = cls_pred_entropy,
prob_good_entropy = cls_prob_entropy[, "Good"]
)
knitr::kable(head(cls_results, 10), digits = 4,
caption = "First 10 classification predictions on test data")
| Actual | Pred. Gini | P(Good) Gini | Pred. Entropy | P(Good) Entropy |
|---|---|---|---|---|
| Good | Good | 0,7821 | Good | 0,7651 |
| Not Good | Not Good | 0,3306 | Not Good | 0,3146 |
| Good | Not Good | 0,3306 | Not Good | 0,3146 |
| Good | Good | 0,7821 | Good | 0,7651 |
| Not Good | Not Good | 0,3306 | Not Good | 0,3146 |
| Good | Good | 0,7821 | Good | 0,9322 |
| Good | Good | 0,7821 | Good | 0,9322 |
| Not Good | Not Good | 0,3306 | Not Good | 0,3146 |
| Good | Not Good | 0,3306 | Not Good | 0,3146 |
| Not Good | Not Good | 0,3306 | Not Good | 0,3146 |
Interpretation. The same observations can receive the same class but different Good probabilities from the two trees. For example, the sixth row is Good for both, with proportions 0.7821 (Gini) and 0.9322 (entropy).
cls_pred_gini <- predict(cls_tree_gini, newdata = cls_test,
type = "class")
cls_prob_gini <- predict(cls_tree_gini, newdata = cls_test,
type = "prob")
cm_gini <- caret::confusionMatrix(
data = cls_pred_gini,
reference = cls_test$quality_class,
positive = "Good", mode = "everything"
)
cat("\nCLASSIFICATION TREE — GINI\n")
print(cm_gini)
| Prediction \ Reference | Not Good | Good |
|---|---|---|
| Not Good | 231 (TN) | 122 (FN) |
| Good | 167 (FP) | 545 (TP) |
Interpretation. Gini correctly identifies 545 of 667 Good wines but misses 122; it correctly identifies 231 of 398 Not Good wines. Thus recall for Good (81.71%) exceeds specificity for Not Good (58.04%).
cls_pred_entropy <- predict(cls_tree_entropy, newdata = cls_test,
type = "class")
cls_prob_entropy <- predict(cls_tree_entropy,
newdata = cls_test, type = "prob")
cm_entropy <- caret::confusionMatrix(
data = cls_pred_entropy,
reference = cls_test$quality_class,
positive = "Good", mode = "everything"
cat("\nCLASSIFICATION TREE — ENTROPY\n")
print(cm_entropy)
| Prediction \ Reference | Not Good | Good |
|---|---|---|
| Not Good | 246 (TN) | 134 (FN) |
| Good | 152 (FP) | 533 (TP) |
Interpretation. Entropy correctly identifies 533 Good observations, fewer than Gini (545), but recognizes 246 Not Good observations, more than Gini (231). The confusion matrix reveals a class-recognition trade-off hidden by overall accuracy.
cls_pred_gini <- predict(cls_tree_gini, newdata = cls_test,
type = "class")
cls_prob_gini <- predict(cls_tree_gini, newdata = cls_test,
type = "prob")
cls_pred_entropy <- predict(cls_tree_entropy, newdata = cls_test,
type = "class")
cls_prob_entropy <- predict(cls_tree_entropy,
newdata = cls_test, type = "prob")
stopifnot(
length(cls_pred_gini) == nrow(cls_test),
length(cls_pred_entropy) == nrow(cls_test),
identical(levels(cls_pred_gini), levels(cls_test$quality_class)),
identical(levels(cls_pred_entropy), levels(cls_test$quality_class)),
all(is.finite(cls_prob_gini)),
all(is.finite(cls_prob_entropy))
)
cls_results <- tibble(
actual = cls_test$quality_class,
predicted_gini = cls_pred_gini,
prob_good_gini = cls_prob_gini[, "Good"],
predicted_entropy = cls_pred_entropy,
prob_good_entropy = cls_prob_entropy[, "Good"]
)
knitr::kable(head(cls_results, 10), digits = 4,
caption = "First 10 classification predictions on test data")
cm_gini <- caret::confusionMatrix(
data = cls_pred_gini,
reference = cls_test$quality_class,
positive = "Good", mode = "everything"
)
cm_entropy <- caret::confusionMatrix(
data = cls_pred_entropy,
reference = cls_test$quality_class,
positive = "Good", mode = "everything"
)
cat("\nCLASSIFICATION TREE — GINI\n")
print(cm_gini)
cat("\nCLASSIFICATION TREE — ENTROPY\n")
print(cm_entropy)
get_class_metrics <- function(cm, model_name) {
tibble(
model = model_name,
Accuracy = unname(cm$overall["Accuracy"]),
Precision = unname(cm$byClass["Precision"]),
Recall = unname(cm$byClass["Recall"]),
F1_score = unname(cm$byClass["F1"]),
Specificity = unname(cm$byClass["Specificity"])
)
}
cls_metrics <- bind_rows(
get_class_metrics(cm_gini, "Gini"),
get_class_metrics(cm_entropy, "Entropy")
)
knitr::kable(cls_metrics, digits = 4,
| Metrik | Gini | Entropy |
|---|---|---|
| Accuracy | 0,7286 | 0,7315 |
| Precision | 0,7654 | 0,7781 |
| Recall | 0,8171 | 0,7991 |
| F1-score | 0,7904 | 0,7885 |
| Specificity | 0,5804 | 0,6181 |
| Balanced Accuracy | 0,6987 | 0,7086 |
Interpretation. Entropy has slightly higher accuracy (0.7315 versus 0.7286), precision and specificity (0.6181 versus 0.5804). Gini has higher recall for Good (0.8171 versus 0.7991) and slightly higher F1. Neither dominates every metric.
This complete block shows the computational order for the stage. Run the stages from Data Preparation so dependencies are already available.
# CLASSIFICATION TREE — TEST EVALUATION
cls_pred_gini <- predict(cls_tree_gini, newdata = cls_test,
type = "class")
cls_prob_gini <- predict(cls_tree_gini, newdata = cls_test,
type = "prob")
cls_pred_entropy <- predict(cls_tree_entropy, newdata = cls_test,
type = "class")
cls_prob_entropy <- predict(cls_tree_entropy,
newdata = cls_test, type = "prob")
stopifnot(
length(cls_pred_gini) == nrow(cls_test),
length(cls_pred_entropy) == nrow(cls_test),
identical(levels(cls_pred_gini), levels(cls_test$quality_class)),
identical(levels(cls_pred_entropy), levels(cls_test$quality_class)),
all(is.finite(cls_prob_gini)),
all(is.finite(cls_prob_entropy))
)
cls_results <- tibble(
actual = cls_test$quality_class,
predicted_gini = cls_pred_gini,
prob_good_gini = cls_prob_gini[, "Good"],
predicted_entropy = cls_pred_entropy,
prob_good_entropy = cls_prob_entropy[, "Good"]
)
knitr::kable(head(cls_results, 10), digits = 4,
caption = "First 10 classification predictions on test data")
cm_gini <- caret::confusionMatrix(
data = cls_pred_gini,
reference = cls_test$quality_class,
positive = "Good", mode = "everything"
)
cm_entropy <- caret::confusionMatrix(
data = cls_pred_entropy,
reference = cls_test$quality_class,
positive = "Good", mode = "everything"
)
cat("\nCLASSIFICATION TREE — GINI\n")
print(cm_gini)
cat("\nCLASSIFICATION TREE — ENTROPY\n")
print(cm_entropy)
get_class_metrics <- function(cm, model_name) {
tibble(
model = model_name,
Accuracy = unname(cm$overall["Accuracy"]),
Precision = unname(cm$byClass["Precision"]),
Recall = unname(cm$byClass["Recall"]),
F1_score = unname(cm$byClass["F1"]),
Specificity = unname(cm$byClass["Specificity"])
)
}
cls_metrics <- bind_rows(
get_class_metrics(cm_gini, "Gini"),
get_class_metrics(cm_entropy, "Entropy")
)
knitr::kable(cls_metrics, digits = 4,
caption = "Baseline Classification Tree performance on test data")The full grid varies cp, minsplit, minbucket, and maxdepth. The same ten validation folds support all three models. Selected configurations are refitted on full training data and only then evaluated on the test set.
The parameter grid and shared CV folds are defined once for fair comparison.
Specify the hyperparameter combinations and reuse the same ten folds for all models. The computational benchmark illustrates why model complexity must be managed.
param_grid <- expand.grid(
cp = c(0, 0.0005, 0.001, 0.003, 0.005, 0.01, 0.02, 0.05),
minsplit = c(10, 20, 40, 80),
minbucket = c(5, 7, 15),
maxdepth = c(3, 5, 8, 15, 30)
) %>% as_tibble() %>%
filter(minsplit >= 2 * minbucket) %>%
arrange(cp, minsplit, minbucket, maxdepth) %>%
mutate(configuration = row_number())
nrow(param_grid)
param_grid %>% filter(
cp == 0.01, minsplit == 20,
minbucket == 7, maxdepth == 30
)
compute_summary <- tibble(
models = c("Regression", "Gini", "Entropy"),
configurations = nrow(param_grid),
cv_folds = 10, total_fits = configurations * cv_folds
)
knitr::kable(compute_summary,
caption = "Grid search computational workload")
| Model | Configuration | CV folds | Total fits |
|---|---|---|---|
| Regression | 360 | 10 | 3.600 |
| Gini | 360 | 10 | 3.600 |
| Entropy | 360 | 10 | 3.600 |
| Total | 1.080 set konfigurasi | — | 10.800 |
Interpretation. Filtering 480 initial combinations with minsplit ≥ 2 × minbucket leaves 360 configurations per model. The baseline configuration is present in the grid (configuration 240).
stopifnot(nrow(reg_train) == nrow(cls_train))
set.seed(2026)
cv_folds <- caret::createFolds(
cls_train$quality_class, k = 10,
list = TRUE, returnTrain = FALSE
)
fold_summary <- tibble(
fold = names(cv_folds),
validation_size = lengths(cv_folds)
)
knitr::kable(fold_summary,
caption = "Fixed 10-fold cross-validation allocation")
stopifnot(identical(
sort(unlist(cv_folds, use.names = FALSE)),
seq_len(nrow(cls_train))
))
| Fold | Validation size |
|---|---|
| Fold01 | 426 |
| Fold02 | 425 |
| Fold03 | 426 |
| Fold04 | 425 |
| Fold05 | 426 |
| Fold06 | 426 |
| Fold07 | 425 |
| Fold08 | 425 |
| Fold09 | 426 |
| Fold10 | 425 |
Interpretation. Five validation folds contain 426 observations and five contain 425. Each of the 4,255 training rows appears exactly once in validation. The same fold indices are reused for regression, Gini, and entropy.
pilot_grid <- tibble(
configuration = c("Complex", "Medium", "Simple"),
cp = c(0, 0.005, 0.05),
minsplit = c(10L, 20L, 80L),
minbucket = c(5L, 7L, 15L),
maxdepth = c(30L, 8L, 3L)
)
pilot_train_ids <- setdiff(
seq_len(nrow(cls_train)), cv_folds[[1]]
)
benchmark_tree <- function(spec, model_name) {
is_regression <- model_name == "Regression"
train_data <- if (is_regression) {
reg_train[pilot_train_ids, , drop = FALSE]
} else {
cls_train[pilot_train_ids, , drop = FALSE]
}
control_params <- rpart.control(
cp = spec$cp, minsplit = spec$minsplit,
minbucket = spec$minbucket, maxdepth = spec$maxdepth,
xval = 0
)
start_time <- proc.time()[["elapsed"]]
if (is_regression) {
fit <- rpart(quality ~ ., data = train_data,
method = "anova", control = control_params)
} else {
split_method <- if (model_name == "Gini") "gini" else "information"
fit <- rpart(quality_class ~ ., data = train_data,
method = "class", parms = list(split = split_method),
control = control_params)
}
elapsed <- proc.time()[["elapsed"]] - start_time
tibble(configuration = spec$configuration,
model = model_name, elapsed_seconds = elapsed,
terminal_nodes = sum(fit$frame$var == "<leaf>"))
}
benchmark_results <- bind_rows(lapply(
seq_len(nrow(pilot_grid)), function(i) {
spec <- pilot_grid[i, ]
bind_rows(lapply(c("Regression", "Gini", "Entropy"),
function(m) benchmark_tree(spec, m)))
}
))
knitr::kable(benchmark_results, digits = 4,
caption = "Computational benchmark for CART configurations")
| Configuration | Regression: nodes (sec) | Gini: nodes (sec) | Entropy: nodes (sec) |
|---|---|---|---|
| Complex | 573 (0,37) | 261 (0,22) | 305 (0,19) |
| Medium | 14 (0,12) | 7 (0,44) | 9 (0,17) |
| Simple | 2 (0,15) | 3 (0,22) | 3 (0,14) |
Interpretation. Large-growth settings generate hundreds of leaves, while simpler settings produce only a few. Runtime measurements are machine dependent and are used to plan checkpointed computation.
This complete block shows the computational order for the stage. Run the stages from Data Preparation so dependencies are already available.
# PARAMETER EXPLORATION — GRID AND BENCHMARK
param_grid <- expand.grid(
cp = c(0, 0.0005, 0.001, 0.003, 0.005, 0.01, 0.02, 0.05),
minsplit = c(10, 20, 40, 80),
minbucket = c(5, 7, 15),
maxdepth = c(3, 5, 8, 15, 30)
) %>% as_tibble() %>%
filter(minsplit >= 2 * minbucket) %>%
arrange(cp, minsplit, minbucket, maxdepth) %>%
mutate(configuration = row_number())
nrow(param_grid)
param_grid %>% filter(
cp == 0.01, minsplit == 20,
minbucket == 7, maxdepth == 30
)
compute_summary <- tibble(
models = c("Regression", "Gini", "Entropy"),
configurations = nrow(param_grid),
cv_folds = 10, total_fits = configurations * cv_folds
)
knitr::kable(compute_summary,
caption = "Grid search computational workload")
stopifnot(nrow(reg_train) == nrow(cls_train))
set.seed(2026)
cv_folds <- caret::createFolds(
cls_train$quality_class, k = 10,
list = TRUE, returnTrain = FALSE
)
fold_summary <- tibble(
fold = names(cv_folds),
validation_size = lengths(cv_folds)
)
knitr::kable(fold_summary,
caption = "Fixed 10-fold cross-validation allocation")
stopifnot(identical(
sort(unlist(cv_folds, use.names = FALSE)),
seq_len(nrow(cls_train))
))
pilot_grid <- tibble(
configuration = c("Complex", "Medium", "Simple"),
cp = c(0, 0.005, 0.05),
minsplit = c(10L, 20L, 80L),
minbucket = c(5L, 7L, 15L),
maxdepth = c(30L, 8L, 3L)
)
pilot_train_ids <- setdiff(
seq_len(nrow(cls_train)), cv_folds[[1]]
)
benchmark_tree <- function(spec, model_name) {
is_regression <- model_name == "Regression"
train_data <- if (is_regression) {
reg_train[pilot_train_ids, , drop = FALSE]
} else {
cls_train[pilot_train_ids, , drop = FALSE]
}
control_params <- rpart.control(
cp = spec$cp, minsplit = spec$minsplit,
minbucket = spec$minbucket, maxdepth = spec$maxdepth,
xval = 0
)
start_time <- proc.time()[["elapsed"]]
if (is_regression) {
fit <- rpart(quality ~ ., data = train_data,
method = "anova", control = control_params)
} else {
split_method <- if (model_name == "Gini") "gini" else "information"
fit <- rpart(quality_class ~ ., data = train_data,
method = "class", parms = list(split = split_method),
control = control_params)
}
elapsed <- proc.time()[["elapsed"]] - start_time
tibble(configuration = spec$configuration,
model = model_name, elapsed_seconds = elapsed,
terminal_nodes = sum(fit$frame$var == "<leaf>"))
}
benchmark_results <- bind_rows(lapply(
seq_len(nrow(pilot_grid)), function(i) {
spec <- pilot_grid[i, ]
bind_rows(lapply(c("Regression", "Gini", "Entropy"),
function(m) benchmark_tree(spec, m)))
}
))
knitr::kable(benchmark_results, digits = 4,
caption = "Computational benchmark for CART configurations")Checkpoint files allow the full CV search to resume after interrupted RStudio sessions.
Evaluate all combinations within the training folds, save batch checkpoints, and confirm completion before selecting a configuration.
# FULL GRID SEARCH — 360 CONFIGURATIONS x 10 FOLDS x 3
stopifnot(
nrow(param_grid) == 360,
length(cv_folds) == 10,
nrow(reg_train) == nrow(cls_train),
identical(sort(unlist(cv_folds, use.names = FALSE)),
seq_len(nrow(reg_train))),
identical(reg_train$quality >= 6,
cls_train$quality_class == "Good")
)
grid_dir <- "P11_Grid_Search_Results"
dir.create(grid_dir, showWarnings = FALSE, recursive = TRUE)
evaluate_grid_fold <- function(spec, model_name, fold_id) {
is_regression <- model_name == "Regression"
data_model <- if (is_regression) reg_train else cls_train
validation_id <- cv_folds[[fold_id]]
training_id <- setdiff(seq_len(nrow(data_model)), validation_id)
train_fold <- data_model[training_id, , drop = FALSE]
valid_fold <- data_model[validation_id, , drop = FALSE]
control_params <- rpart.control(
cp = spec$cp, minsplit = spec$minsplit,
minbucket = spec$minbucket, maxdepth = spec$maxdepth,
xval = 0
)
start_time <- proc.time()[["elapsed"]]
if (is_regression) {
fit <- rpart(quality ~ ., data = train_fold,
method = "anova", control = control_params)
} else {
split_method <- if (model_name == "Gini") "gini" else "information"
fit <- rpart(quality_class ~ ., data = train_fold,
method = "class", parms = list(split = split_method),
control = control_params)
}
fit_seconds <- proc.time()[["elapsed"]] - start_time
frame <- fit$frame
is_leaf <- frame$var == "<leaf>"
node_ids <- as.integer(rownames(frame))
result <- tibble(
model = model_name, configuration = spec$configuration,
fold = fold_id, cp = spec$cp,
minsplit = spec$minsplit, minbucket = spec$minbucket,
maxdepth = spec$maxdepth, terminal_nodes = sum(is_leaf),
tree_depth = max(floor(log2(node_ids))),
fit_seconds = fit_seconds,
rmse = NA_real_, mae = NA_real_,
balanced_accuracy = NA_real_, accuracy = NA_real_,
precision = NA_real_, recall = NA_real_,
f1_score = NA_real_, specificity = NA_real_
)
if (is_regression) {
predicted <- as.numeric(
predict(fit, newdata = valid_fold, type = "vector"))
actual <- valid_fold$quality
result$rmse <- sqrt(mean((actual - predicted)^2))
result$mae <- mean(abs(actual - predicted))
} else {
predicted <- as.character(
predict(fit, newdata = valid_fold, type = "class"))
actual <- as.character(valid_fold$quality_class)
tp <- sum(predicted == "Good" & actual == "Good")
tn <- sum(predicted == "Not Good" & actual == "Not Good")
fp <- sum(predicted == "Good" & actual == "Not Good")
fn <- sum(predicted == "Not Good" & actual == "Good")
recall <- tp / (tp + fn)
specificity <- tn / (tn + fp)
precision <- if ((tp + fp) > 0) tp / (tp + fp) else 0
f1 <- if ((precision + recall) > 0) {
2 * precision * recall / (precision + recall)
} else 0
result$balanced_accuracy <- (recall + specificity) / 2
result$accuracy <- (tp + tn) / length(actual)
result$precision <- precision
result$recall <- recall
result$f1_score <- f1
result$specificity <- specificity
}
return(result)
}
run_grid_model <- function(model_name, batch_size = 20) {
stopifnot(model_name %in% c("Regression", "Gini", "Entropy"))
checkpoint_file <- file.path(
grid_dir, paste0("cv_", tolower(model_name), ".rds"))
if (file.exists(checkpoint_file)) {
checkpoint <- readRDS(checkpoint_file)
stopifnot(
identical(checkpoint$grid, param_grid),
identical(checkpoint$folds, cv_folds),
identical(checkpoint$model, model_name)
)
results <- checkpoint$results
message("Melanjutkan ", model_name, " dari checkpoint.")
} else {
results <- tibble()
}
completed_ids <- unique(results$configuration)
remaining_ids <- setdiff(param_grid$configuration, completed_ids)
if (length(remaining_ids) == 0) {
message(model_name, ": seluruh konfigurasi sudah selesai.")
return(results)
}
batches <- split(
remaining_ids,
ceiling(seq_along(remaining_ids) / batch_size)
)
for (b in seq_along(batches)) {
batch_results <- bind_rows(lapply(batches[[b]], function(config_id) {
spec <- param_grid %>% filter(configuration == config_id)
bind_rows(lapply(seq_along(cv_folds), function(k) {
evaluate_grid_fold(spec = spec,
model_name = model_name, fold_id = k)
}))
}))
results <- bind_rows(results, batch_results)
saveRDS(list(model = model_name, grid = param_grid,
folds = cv_folds, results = results),
checkpoint_file)
completed_count <- length(unique(results$configuration))
message(model_name, ": ", completed_count, " / ",
nrow(param_grid), " konfigurasi selesai.")
}
return(results)
}
reg_grid_raw <- run_grid_model("Regression", batch_size = 20)
gini_grid_raw <- run_grid_model("Gini", batch_size = 20)
entropy_grid_raw <- run_grid_model("Entropy", batch_size = 20)
grid_completion <- tibble(
model = c("Regression", "Gini", "Entropy"),
records = c(nrow(reg_grid_raw), nrow(gini_grid_raw),
nrow(entropy_grid_raw))
) %>% mutate(expected = nrow(param_grid) * length(cv_folds),
complete = records == expected)
knitr::kable(grid_completion,
caption = "Full grid search completion check")
stopifnot(all(grid_completion$complete))
| Model | Configuration | Fold | CV rows | Complete |
|---|---|---|---|---|
| Regression | 360 | 10 | 3.600 | TRUE |
| Gini | 360 | 10 | 3.600 | TRUE |
| Entropy | 360 | 10 | 3.600 | TRUE |
Interpretation. The completed grid contains 3,600 validation results per model, or 10,800 individual fold evaluations. Model selection does not use the test data.
# FULL GRID SEARCH — 360 CONFIGURATIONS x 10 FOLDS x 3
stopifnot(
nrow(param_grid) == 360,
length(cv_folds) == 10,
nrow(reg_train) == nrow(cls_train),
identical(sort(unlist(cv_folds, use.names = FALSE)),
seq_len(nrow(reg_train))),
identical(reg_train$quality >= 6,
cls_train$quality_class == "Good")
)
grid_dir <- "P11_Grid_Search_Results"
dir.create(grid_dir, showWarnings = FALSE, recursive = TRUE)
evaluate_grid_fold <- function(spec, model_name, fold_id) {
is_regression <- model_name == "Regression"
data_model <- if (is_regression) reg_train else cls_train
validation_id <- cv_folds[[fold_id]]
training_id <- setdiff(seq_len(nrow(data_model)), validation_id)
train_fold <- data_model[training_id, , drop = FALSE]
valid_fold <- data_model[validation_id, , drop = FALSE]
control_params <- rpart.control(
cp = spec$cp, minsplit = spec$minsplit,
minbucket = spec$minbucket, maxdepth = spec$maxdepth,
xval = 0
)
start_time <- proc.time()[["elapsed"]]
if (is_regression) {
fit <- rpart(quality ~ ., data = train_fold,
method = "anova", control = control_params)
} else {
split_method <- if (model_name == "Gini") "gini" else "information"
fit <- rpart(quality_class ~ ., data = train_fold,
method = "class", parms = list(split = split_method),
control = control_params)
}
fit_seconds <- proc.time()[["elapsed"]] - start_time
frame <- fit$frame
is_leaf <- frame$var == "<leaf>"
node_ids <- as.integer(rownames(frame))
result <- tibble(
model = model_name, configuration = spec$configuration,
fold = fold_id, cp = spec$cp,
minsplit = spec$minsplit, minbucket = spec$minbucket,
maxdepth = spec$maxdepth, terminal_nodes = sum(is_leaf),
tree_depth = max(floor(log2(node_ids))),
fit_seconds = fit_seconds,
rmse = NA_real_, mae = NA_real_,
balanced_accuracy = NA_real_, accuracy = NA_real_,
precision = NA_real_, recall = NA_real_,
f1_score = NA_real_, specificity = NA_real_
)
if (is_regression) {
predicted <- as.numeric(
predict(fit, newdata = valid_fold, type = "vector"))
actual <- valid_fold$quality
result$rmse <- sqrt(mean((actual - predicted)^2))
result$mae <- mean(abs(actual - predicted))
} else {
predicted <- as.character(
predict(fit, newdata = valid_fold, type = "class"))
actual <- as.character(valid_fold$quality_class)
tp <- sum(predicted == "Good" & actual == "Good")
tn <- sum(predicted == "Not Good" & actual == "Not Good")
fp <- sum(predicted == "Good" & actual == "Not Good")
fn <- sum(predicted == "Not Good" & actual == "Good")
recall <- tp / (tp + fn)
specificity <- tn / (tn + fp)
precision <- if ((tp + fp) > 0) tp / (tp + fp) else 0
f1 <- if ((precision + recall) > 0) {
2 * precision * recall / (precision + recall)
} else 0
result$balanced_accuracy <- (recall + specificity) / 2
result$accuracy <- (tp + tn) / length(actual)
result$precision <- precision
result$recall <- recall
result$f1_score <- f1
result$specificity <- specificity
}
return(result)
}
run_grid_model <- function(model_name, batch_size = 20) {
stopifnot(model_name %in% c("Regression", "Gini", "Entropy"))
checkpoint_file <- file.path(
grid_dir, paste0("cv_", tolower(model_name), ".rds"))
if (file.exists(checkpoint_file)) {
checkpoint <- readRDS(checkpoint_file)
stopifnot(
identical(checkpoint$grid, param_grid),
identical(checkpoint$folds, cv_folds),
identical(checkpoint$model, model_name)
)
results <- checkpoint$results
message("Melanjutkan ", model_name, " dari checkpoint.")
} else {
results <- tibble()
}
completed_ids <- unique(results$configuration)
remaining_ids <- setdiff(param_grid$configuration, completed_ids)
if (length(remaining_ids) == 0) {
message(model_name, ": seluruh konfigurasi sudah selesai.")
return(results)
}
batches <- split(
remaining_ids,
ceiling(seq_along(remaining_ids) / batch_size)
)
for (b in seq_along(batches)) {
batch_results <- bind_rows(lapply(batches[[b]], function(config_id) {
spec <- param_grid %>% filter(configuration == config_id)
bind_rows(lapply(seq_along(cv_folds), function(k) {
evaluate_grid_fold(spec = spec,
model_name = model_name, fold_id = k)
}))
}))
results <- bind_rows(results, batch_results)
saveRDS(list(model = model_name, grid = param_grid,
folds = cv_folds, results = results),
checkpoint_file)
completed_count <- length(unique(results$configuration))
message(model_name, ": ", completed_count, " / ",
nrow(param_grid), " konfigurasi selesai.")
}
return(results)
}
reg_grid_raw <- run_grid_model("Regression", batch_size = 20)
gini_grid_raw <- run_grid_model("Gini", batch_size = 20)
entropy_grid_raw <- run_grid_model("Entropy", batch_size = 20)
grid_completion <- tibble(
model = c("Regression", "Gini", "Entropy"),
records = c(nrow(reg_grid_raw), nrow(gini_grid_raw),
nrow(entropy_grid_raw))
) %>% mutate(expected = nrow(param_grid) * length(cv_folds),
complete = records == expected)
knitr::kable(grid_completion,
caption = "Full grid search completion check")
stopifnot(all(grid_completion$complete))
| Model | Checkpoint file |
|---|---|
| Regression | cv_regression.rds |
| Gini | cv_gini.rds |
| Entropy | cv_entropy.rds |
Interpretation. Checkpoint files hold results of the 360-configuration CV runs. Switching a tab on the published page never retrains a model; computation occurs when the document is rendered in RStudio.
This complete block shows the computational order for the stage. Run the stages from Data Preparation so dependencies are already available.
# FULL GRID SEARCH — 360 CONFIGURATIONS x 10 FOLDS x 3
stopifnot(
nrow(param_grid) == 360,
length(cv_folds) == 10,
nrow(reg_train) == nrow(cls_train),
identical(sort(unlist(cv_folds, use.names = FALSE)),
seq_len(nrow(reg_train))),
identical(reg_train$quality >= 6,
cls_train$quality_class == "Good")
)
grid_dir <- "P11_Grid_Search_Results"
dir.create(grid_dir, showWarnings = FALSE, recursive = TRUE)
evaluate_grid_fold <- function(spec, model_name, fold_id) {
is_regression <- model_name == "Regression"
data_model <- if (is_regression) reg_train else cls_train
validation_id <- cv_folds[[fold_id]]
training_id <- setdiff(seq_len(nrow(data_model)), validation_id)
train_fold <- data_model[training_id, , drop = FALSE]
valid_fold <- data_model[validation_id, , drop = FALSE]
control_params <- rpart.control(
cp = spec$cp, minsplit = spec$minsplit,
minbucket = spec$minbucket, maxdepth = spec$maxdepth,
xval = 0
)
start_time <- proc.time()[["elapsed"]]
if (is_regression) {
fit <- rpart(quality ~ ., data = train_fold,
method = "anova", control = control_params)
} else {
split_method <- if (model_name == "Gini") "gini" else "information"
fit <- rpart(quality_class ~ ., data = train_fold,
method = "class", parms = list(split = split_method),
control = control_params)
}
fit_seconds <- proc.time()[["elapsed"]] - start_time
frame <- fit$frame
is_leaf <- frame$var == "<leaf>"
node_ids <- as.integer(rownames(frame))
result <- tibble(
model = model_name, configuration = spec$configuration,
fold = fold_id, cp = spec$cp,
minsplit = spec$minsplit, minbucket = spec$minbucket,
maxdepth = spec$maxdepth, terminal_nodes = sum(is_leaf),
tree_depth = max(floor(log2(node_ids))),
fit_seconds = fit_seconds,
rmse = NA_real_, mae = NA_real_,
balanced_accuracy = NA_real_, accuracy = NA_real_,
precision = NA_real_, recall = NA_real_,
f1_score = NA_real_, specificity = NA_real_
)
if (is_regression) {
predicted <- as.numeric(
predict(fit, newdata = valid_fold, type = "vector"))
actual <- valid_fold$quality
result$rmse <- sqrt(mean((actual - predicted)^2))
result$mae <- mean(abs(actual - predicted))
} else {
predicted <- as.character(
predict(fit, newdata = valid_fold, type = "class"))
actual <- as.character(valid_fold$quality_class)
tp <- sum(predicted == "Good" & actual == "Good")
tn <- sum(predicted == "Not Good" & actual == "Not Good")
fp <- sum(predicted == "Good" & actual == "Not Good")
fn <- sum(predicted == "Not Good" & actual == "Good")
recall <- tp / (tp + fn)
specificity <- tn / (tn + fp)
precision <- if ((tp + fp) > 0) tp / (tp + fp) else 0
f1 <- if ((precision + recall) > 0) {
2 * precision * recall / (precision + recall)
} else 0
result$balanced_accuracy <- (recall + specificity) / 2
result$accuracy <- (tp + tn) / length(actual)
result$precision <- precision
result$recall <- recall
result$f1_score <- f1
result$specificity <- specificity
}
return(result)
}
run_grid_model <- function(model_name, batch_size = 20) {
stopifnot(model_name %in% c("Regression", "Gini", "Entropy"))
checkpoint_file <- file.path(
grid_dir, paste0("cv_", tolower(model_name), ".rds"))
if (file.exists(checkpoint_file)) {
checkpoint <- readRDS(checkpoint_file)
stopifnot(
identical(checkpoint$grid, param_grid),
identical(checkpoint$folds, cv_folds),
identical(checkpoint$model, model_name)
)
results <- checkpoint$results
message("Melanjutkan ", model_name, " dari checkpoint.")
} else {
results <- tibble()
}
completed_ids <- unique(results$configuration)
remaining_ids <- setdiff(param_grid$configuration, completed_ids)
if (length(remaining_ids) == 0) {
message(model_name, ": seluruh konfigurasi sudah selesai.")
return(results)
}
batches <- split(
remaining_ids,
ceiling(seq_along(remaining_ids) / batch_size)
)
for (b in seq_along(batches)) {
batch_results <- bind_rows(lapply(batches[[b]], function(config_id) {
spec <- param_grid %>% filter(configuration == config_id)
bind_rows(lapply(seq_along(cv_folds), function(k) {
evaluate_grid_fold(spec = spec,
model_name = model_name, fold_id = k)
}))
}))
results <- bind_rows(results, batch_results)
saveRDS(list(model = model_name, grid = param_grid,
folds = cv_folds, results = results),
checkpoint_file)
completed_count <- length(unique(results$configuration))
message(model_name, ": ", completed_count, " / ",
nrow(param_grid), " konfigurasi selesai.")
}
return(results)
}
reg_grid_raw <- run_grid_model("Regression", batch_size = 20)
gini_grid_raw <- run_grid_model("Gini", batch_size = 20)
entropy_grid_raw <- run_grid_model("Entropy", batch_size = 20)
grid_completion <- tibble(
model = c("Regression", "Gini", "Entropy"),
records = c(nrow(reg_grid_raw), nrow(gini_grid_raw),
nrow(entropy_grid_raw))
) %>% mutate(expected = nrow(param_grid) * length(cv_folds),
complete = records == expected)
knitr::kable(grid_completion,
caption = "Full grid search completion check")
stopifnot(all(grid_completion$complete))The optimal parameters follow the agreed validation criteria, without inspecting test performance.
Minimize RMSE for regression and maximize Balanced Accuracy for classification. The leading candidates reveal that different settings may produce similar scores.
reg_grid_summary <- reg_grid_raw %>%
group_by(configuration, cp, minsplit, minbucket, maxdepth) %>%
summarise(
cv_RMSE = mean(rmse), sd_RMSE = sd(rmse),
cv_MAE = mean(mae),
mean_terminal_nodes = mean(terminal_nodes),
mean_depth = mean(tree_depth),
mean_fit_seconds = mean(fit_seconds),
.groups = "drop"
)
cls_grid_summary <- bind_rows(gini_grid_raw, entropy_grid_raw) %>%
group_by(model, configuration, cp, minsplit,
minbucket, maxdepth) %>%
summarise(
cv_Balanced_Accuracy = mean(balanced_accuracy),
sd_Balanced_Accuracy = sd(balanced_accuracy),
cv_Accuracy = mean(accuracy),
cv_Precision = mean(precision),
cv_Recall = mean(recall),
cv_F1 = mean(f1_score),
cv_Specificity = mean(specificity),
mean_terminal_nodes = mean(terminal_nodes),
mean_depth = mean(tree_depth),
mean_fit_seconds = mean(fit_seconds),
.groups = "drop"
)
best_reg_config <- reg_grid_summary %>%
arrange(cv_RMSE, mean_terminal_nodes, desc(cp)) %>%
slice_head(n = 1)
best_cls_config <- cls_grid_summary %>%
group_by(model) %>%
arrange(desc(cv_Balanced_Accuracy),
mean_terminal_nodes, desc(cp), .by_group = TRUE) %>%
slice_head(n = 1) %>% ungroup()
knitr::kable(best_reg_config, digits = 5,
caption = "Best Regression configuration")
| Config | CP | minsplit | minbucket | maxdepth | CV RMSE | SD RMSE | CV MAE | Mean leaves |
|---|---|---|---|---|---|---|---|---|
| 87 | 0,0005 | 80 | 15 | 5 | 0,75385 | 0,03744 | 0,58709 | 27,8 |
Interpretation. Configuration 87 minimizes mean CV RMSE at 0.75385, with 27.8 leaves on average across folds. Depth 5 limits growth, while the result remains a validation metric rather than a test score.
cls_grid_summary <- bind_rows(gini_grid_raw, entropy_grid_raw) %>%
group_by(model, configuration, cp, minsplit,
minbucket, maxdepth) %>%
summarise(
cv_Balanced_Accuracy = mean(balanced_accuracy),
sd_Balanced_Accuracy = sd(balanced_accuracy),
cv_Accuracy = mean(accuracy),
cv_Precision = mean(precision),
cv_Recall = mean(recall),
cv_F1 = mean(f1_score),
cv_Specificity = mean(specificity),
mean_terminal_nodes = mean(terminal_nodes),
mean_depth = mean(tree_depth),
mean_fit_seconds = mean(fit_seconds),
.groups = "drop"
)
best_reg_config <- reg_grid_summary %>%
arrange(cv_RMSE, mean_terminal_nodes, desc(cp)) %>%
slice_head(n = 1)
best_cls_config <- cls_grid_summary %>%
group_by(model) %>%
arrange(desc(cv_Balanced_Accuracy),
mean_terminal_nodes, desc(cp), .by_group = TRUE) %>%
slice_head(n = 1) %>% ungroup()
knitr::kable(best_reg_config, digits = 5,
caption = "Best Regression configuration")
knitr::kable(best_cls_config, digits = 5,
caption = "Best Classification configurations")
| Criterion | Config | CP | minsplit | minbucket | maxdepth | CV Balanced Acc. | SD |
|---|---|---|---|---|---|---|---|
| Gini | 149 | 0,003 | 20 | 7 | 15 | 0,72098 | 0,03286 |
| Entropy | 133 | 0,001 | 80 | 15 | 8 | 0,71749 | 0,02355 |
Interpretation. Gini and entropy select different parameter sets because their splitting criteria and validation responses differ. Gini CV Balanced Accuracy exceeds entropy by 0.00349; this alone does not establish test-set superiority.
reg_grid_summary <- reg_grid_raw %>%
group_by(configuration, cp, minsplit, minbucket, maxdepth) %>%
summarise(
cv_RMSE = mean(rmse), sd_RMSE = sd(rmse),
cv_MAE = mean(mae),
mean_terminal_nodes = mean(terminal_nodes),
mean_depth = mean(tree_depth),
mean_fit_seconds = mean(fit_seconds),
.groups = "drop"
)
top10_reg <- reg_grid_summary %>%
arrange(cv_RMSE) %>% slice_head(n = 10)
top10_cls <- cls_grid_summary %>%
group_by(model) %>%
arrange(desc(cv_Balanced_Accuracy), .by_group = TRUE) %>%
slice_head(n = 10) %>% ungroup()
knitr::kable(top10_reg, digits = 5,
caption = "Top 10 Regression configurations")
| Regression config | CP | CV RMSE | Mean terminal nodes |
|---|---|---|---|
| 42 | 0 | 0,753850636246 | 27,8 |
| 87 | 0,0005 | 0,753850636246 | 27,8 |
| 132 | 0,001 | 0,75388 | 27,7 |
| 27 | 0 | 0,75503 | 30,1 |
| 72 | 0,0005 | 0,75503 | 30,1 |
Interpretation. Configurations 42 (cp = 0) and 87 (cp = 0.0005) both achieve a CV RMSE of 0.753850636246 to twelve decimal places. The predefined tie-break selects configuration 87 with the larger cp; identical aggregate scores do not prove that all fold-specific trees are identical.
cls_grid_summary <- bind_rows(gini_grid_raw, entropy_grid_raw) %>%
group_by(model, configuration, cp, minsplit,
minbucket, maxdepth) %>%
summarise(
cv_Balanced_Accuracy = mean(balanced_accuracy),
sd_Balanced_Accuracy = sd(balanced_accuracy),
cv_Accuracy = mean(accuracy),
cv_Precision = mean(precision),
cv_Recall = mean(recall),
cv_F1 = mean(f1_score),
cv_Specificity = mean(specificity),
mean_terminal_nodes = mean(terminal_nodes),
mean_depth = mean(tree_depth),
mean_fit_seconds = mean(fit_seconds),
.groups = "drop"
top10_cls <- cls_grid_summary %>%
group_by(model) %>%
arrange(desc(cv_Balanced_Accuracy), .by_group = TRUE) %>%
slice_head(n = 10) %>% ungroup()
knitr::kable(top10_reg, digits = 5,
caption = "Top 10 Regression configurations")
knitr::kable(top10_cls, digits = 5,
caption = "Top 10 configurations Gini and Entropy")
| Model | Config | CV BA | CV Accuracy | CV F1 |
|---|---|---|---|---|
| Gini | 149 | 0.72098 | 0.73915 | 0.79174 |
| Entropy | 133 | 0.71749 | 0.73891 | 0.79357 |
Interpretation. Gini selects configuration 149 (CV Balanced Accuracy 0.72098), while entropy selects configuration 133 (0.71749). All configurations are ranked using training-fold validation only; test-set results are not used to select parameters.
This complete block shows the computational order for the stage. Run the stages from Data Preparation so dependencies are already available.
# CV SUMMARY AND CONFIGURATION SELECTION
reg_grid_summary <- reg_grid_raw %>%
group_by(configuration, cp, minsplit, minbucket, maxdepth) %>%
summarise(
cv_RMSE = mean(rmse), sd_RMSE = sd(rmse),
cv_MAE = mean(mae),
mean_terminal_nodes = mean(terminal_nodes),
mean_depth = mean(tree_depth),
mean_fit_seconds = mean(fit_seconds),
.groups = "drop"
)
cls_grid_summary <- bind_rows(gini_grid_raw, entropy_grid_raw) %>%
group_by(model, configuration, cp, minsplit,
minbucket, maxdepth) %>%
summarise(
cv_Balanced_Accuracy = mean(balanced_accuracy),
sd_Balanced_Accuracy = sd(balanced_accuracy),
cv_Accuracy = mean(accuracy),
cv_Precision = mean(precision),
cv_Recall = mean(recall),
cv_F1 = mean(f1_score),
cv_Specificity = mean(specificity),
mean_terminal_nodes = mean(terminal_nodes),
mean_depth = mean(tree_depth),
mean_fit_seconds = mean(fit_seconds),
.groups = "drop"
)
best_reg_config <- reg_grid_summary %>%
arrange(cv_RMSE, mean_terminal_nodes, desc(cp)) %>%
slice_head(n = 1)
best_cls_config <- cls_grid_summary %>%
group_by(model) %>%
arrange(desc(cv_Balanced_Accuracy),
mean_terminal_nodes, desc(cp), .by_group = TRUE) %>%
slice_head(n = 1) %>% ungroup()
knitr::kable(best_reg_config, digits = 5,
caption = "Best Regression configuration")
knitr::kable(best_cls_config, digits = 5,
caption = "Best Classification configurations")
top10_reg <- reg_grid_summary %>%
arrange(cv_RMSE) %>% slice_head(n = 10)
top10_cls <- cls_grid_summary %>%
group_by(model) %>%
arrange(desc(cv_Balanced_Accuracy), .by_group = TRUE) %>%
slice_head(n = 10) %>% ungroup()
knitr::kable(top10_reg, digits = 5,
caption = "Top 10 Regression configurations")
knitr::kable(top10_cls, digits = 5,
caption = "Top 10 configurations Gini and Entropy")
saveRDS(list(regression = reg_grid_summary,
classification = cls_grid_summary,
best_regression = best_reg_config,
best_classification = best_cls_config),
file.path(grid_dir, "grid_search_summary.rds"))
cat("\nGRID SEARCH SUMMARY COMPLETED\n")Baseline and tuned models are compared using identical training folds before the final refit.
Compare baseline and tuned models on identical folds. Refit the selected settings using the full training set, then examine the resulting structures.
baseline_id <- param_grid %>% filter(
cp == 0.01, minsplit == 20,
minbucket == 7, maxdepth == 30
) %>% pull(configuration)
stopifnot(length(baseline_id) == 1)
cv_reg_comparison <- bind_rows(
reg_grid_summary %>% filter(configuration == baseline_id) %>%
mutate(version = "Baseline"),
best_reg_config %>% mutate(version = "Grid Search")
) %>% select(version, configuration, cp, minsplit,
minbucket, maxdepth, cv_RMSE, sd_RMSE,
cv_MAE, mean_terminal_nodes)
knitr::kable(cv_reg_comparison, digits = 5,
caption = "Baseline vs Tuned Regression — 10-fold CV")
| Version | CP | minsplit | minbucket | maxdepth | CV RMSE | CV MAE | Mean leaves |
|---|---|---|---|---|---|---|---|
| Baseline | 0,01 | 20 | 7 | 30 | 0,77240 | 0,61186 | 5,8 |
| Grid Search | 0,0005 | 80 | 15 | 5 | 0,75385 | 0,58709 | 27,8 |
Interpretation. On identical validation folds, mean regression RMSE falls from 0.77240 to 0.75385. This CV gain guides parameter selection, but it does not guarantee that all held-out test errors will improve.
cv_cls_comparison <- bind_rows(
cls_grid_summary %>% filter(configuration == baseline_id) %>%
mutate(version = "Baseline"),
best_cls_config %>% mutate(version = "Grid Search")
) %>% arrange(model, version) %>%
select(model, version, configuration, cp, minsplit,
minbucket, maxdepth, cv_Balanced_Accuracy,
sd_Balanced_Accuracy, cv_Accuracy,
cv_F1, cv_Specificity, mean_terminal_nodes)
knitr::kable(cv_cls_comparison, digits = 5,
caption = "Baseline vs Tuned Classification — 10-fold CV")
| Model | Version | Balanced Accuracy CV | Accuracy CV | F1 CV | Specificity CV |
|---|---|---|---|---|---|
| Gini | Baseline | 0,68585 | 0,72693 | 0,79554 | 0,52327 |
| Gini | Grid Search | 0,72098 | 0,73915 | 0,79174 | 0,64906 |
| Entropy | Baseline | 0,69090 | 0,72881 | 0,79529 | 0,54088 |
| Entropy | Grid Search | 0,71749 | 0,73891 | 0,79357 | 0,63270 |
Interpretation. Mean CV Balanced Accuracy rises from 0.68585 to 0.72098 for Gini and from 0.69090 to 0.71749 for entropy—gains of about 3.51 and 2.66 percentage points. F1 need not improve because configurations were selected to maximize Balanced Accuracy.
reg_tie_check <- reg_grid_summary %>%
filter(configuration %in% c(42, 87)) %>%
mutate(RMSE_12_digits = sprintf("%.12f", cv_RMSE)) %>%
select(configuration, cp, cv_RMSE, RMSE_12_digits,
cv_MAE, mean_terminal_nodes)
knitr::kable(reg_tie_check,
caption = "Detailed comparison of regression ties")
| Config | cp | CV RMSE | Mean leaves |
|---|---|---|---|
| 42 | 0 | 0.753850636246 | 27.8 |
| 87 | 0.0005 | 0.753850636246 | 27.8 |
Interpretation. Both settings achieve CV RMSE 0.753850636246 to twelve decimal places. The predefined tie-break chooses configuration 87 with the larger cp, not because test performance has been consulted.
# REFIT SELECTED MODELS ON FULL TRAINING DATA
fit_selected_tree <- function(spec, data, task, split = NULL) {
stopifnot(nrow(spec) == 1)
tree_control <- rpart.control(
cp = spec$cp, minsplit = spec$minsplit,
minbucket = spec$minbucket, maxdepth = spec$maxdepth,
xval = 0
)
if (task == "regression") {
fit <- rpart(quality ~ ., data = data,
method = "anova", control = tree_control)
} else {
fit <- rpart(quality_class ~ ., data = data,
method = "class", parms = list(split = split),
control = tree_control)
}
return(fit)
}
reg_tree_tuned <- fit_selected_tree(
best_reg_config, reg_train, task = "regression")
gini_spec <- best_cls_config %>% filter(model == "Gini")
cls_tree_gini_tuned <- fit_selected_tree(
gini_spec, cls_train, task = "classification", split = "gini")
entropy_spec <- best_cls_config %>% filter(model == "Entropy")
cls_tree_entropy_tuned <- fit_selected_tree(
entropy_spec, cls_train, task = "classification",
split = "information")
get_tree_structure <- function(fit, model, version) {
frame <- fit$frame
node_ids <- as.integer(rownames(frame))
tibble(model = model, version = version,
internal_nodes = sum(frame$var != "<leaf>"),
terminal_nodes = sum(frame$var == "<leaf>"),
total_nodes = nrow(frame),
tree_depth = max(floor(log2(node_ids))),
root_split = frame$var[1])
}
tuned_structure <- bind_rows(
get_tree_structure(reg_tree, "Regression", "Baseline"),
get_tree_structure(reg_tree_tuned, "Regression", "Grid Search"),
get_tree_structure(cls_tree_gini, "Gini", "Baseline"),
get_tree_structure(cls_tree_gini_tuned, "Gini", "Grid Search"),
get_tree_structure(cls_tree_entropy, "Entropy", "Baseline"),
get_tree_structure(cls_tree_entropy_tuned, "Entropy", "Grid Search")
)
knitr::kable(tuned_structure,
caption = "Baseline and tuned tree structures")
| Model | Version | Internal | Terminal | Total | Depth | Root split |
|---|---|---|---|---|---|---|
| Regression | Baseline | 4 | 5 | 9 | 3 | alcohol |
| Regression | Grid Search | 28 | 29 | 57 | 5 | alcohol |
| Gini | Baseline | 2 | 3 | 5 | 2 | alcohol |
| Gini | Grid Search | 25 | 26 | 51 | 9 | alcohol |
| Entropy | Baseline | 5 | 6 | 11 | 4 | alcohol |
| Entropy | Grid Search | 29 | 30 | 59 | 8 | alcohol |
Interpretation. All tuned trees contain more leaves while retaining alcohol as the root split. maxdepth is an upper limit, not the achieved depth: tuned Gini has actual depth 9 despite a maximum of 15.
# SAVE FULL TUNED TREE VISUALIZATIONS
plot_dir <- file.path(grid_dir, "Tuned_Tree_Plots")
dir.create(plot_dir, recursive = TRUE, showWarnings = FALSE)
save_tree_plot <- function(fit, filename, title, extra) {
png(filename = file.path(plot_dir, filename),
width = 3200, height = 2000, res = 180)
tryCatch({
rpart.plot(fit, type = 2, extra = extra,
under = FALSE, fallen.leaves = TRUE,
faclen = 0, digits = 3, tweak = 0.8,
main = title)
}, finally = dev.off())
}
save_tree_plot(reg_tree_tuned, "Regression_Tree_Tuned.png",
"Tuned Regression Tree — Wine Quality", 101)
Interpretation. Refitting produces 29 terminal nodes, compared with five for baseline. New branches divide wine observations into finer prediction regions, but each terminal node still assigns a constant score. Added complexity matters only if held-out prediction error improves, as examined in the next evaluation.
# SAVE FULL TUNED TREE VISUALIZATIONS
plot_dir <- file.path(grid_dir, "Tuned_Tree_Plots")
dir.create(plot_dir, recursive = TRUE, showWarnings = FALSE)
save_tree_plot <- function(fit, filename, title, extra) {
png(filename = file.path(plot_dir, filename),
width = 3200, height = 2000, res = 180)
tryCatch({
rpart.plot(fit, type = 2, extra = extra,
under = FALSE, fallen.leaves = TRUE,
faclen = 0, digits = 3, tweak = 0.8,
main = title)
}, finally = dev.off())
}
save_tree_plot(reg_tree_tuned, "Regression_Tree_Tuned.png",
"Tuned Regression Tree — Wine Quality", 101)
save_tree_plot(cls_tree_gini_tuned, "Classification_Gini_Tuned.png",
"Tuned Classification Tree — Gini", 104)
Interpretation. The tuned Gini model has 26 terminal nodes and actual depth 9, below its allowed maxdepth of 15. The diagram shows additional decision paths, but more detailed rules must be distinguished from better recognition of Good or Not Good cases in the test set.
# SAVE FULL TUNED TREE VISUALIZATIONS
plot_dir <- file.path(grid_dir, "Tuned_Tree_Plots")
dir.create(plot_dir, recursive = TRUE, showWarnings = FALSE)
save_tree_plot <- function(fit, filename, title, extra) {
png(filename = file.path(plot_dir, filename),
width = 3200, height = 2000, res = 180)
tryCatch({
rpart.plot(fit, type = 2, extra = extra,
under = FALSE, fallen.leaves = TRUE,
faclen = 0, digits = 3, tweak = 0.8,
main = title)
}, finally = dev.off())
}
save_tree_plot(reg_tree_tuned, "Regression_Tree_Tuned.png",
"Tuned Regression Tree — Wine Quality", 101)
save_tree_plot(cls_tree_gini_tuned, "Classification_Gini_Tuned.png",
"Tuned Classification Tree — Gini", 104)
save_tree_plot(cls_tree_entropy_tuned,
"Classification_Entropy_Tuned.png",
"Tuned Classification Tree — Entropy", 104)
cat("Three tuned tree plots saved to:", plot_dir, "\n")
Interpretation. Tuned entropy has 30 leaves and actual depth 8, compared with six leaves at baseline. The richer structure partitions more class regions, but leaf count is not itself a success metric: the test confusion matrix shows improved Not Good recognition alongside fewer correctly identified Good observations.
This complete block shows the computational order for the stage. Run the stages from Data Preparation so dependencies are already available.
# BASELINE VS TUNED (COMMON 10-FOLD CV)
baseline_id <- param_grid %>% filter(
cp == 0.01, minsplit == 20,
minbucket == 7, maxdepth == 30
) %>% pull(configuration)
stopifnot(length(baseline_id) == 1)
cv_reg_comparison <- bind_rows(
reg_grid_summary %>% filter(configuration == baseline_id) %>%
mutate(version = "Baseline"),
best_reg_config %>% mutate(version = "Grid Search")
) %>% select(version, configuration, cp, minsplit,
minbucket, maxdepth, cv_RMSE, sd_RMSE,
cv_MAE, mean_terminal_nodes)
knitr::kable(cv_reg_comparison, digits = 5,
caption = "Baseline vs Tuned Regression — 10-fold CV")
cv_cls_comparison <- bind_rows(
cls_grid_summary %>% filter(configuration == baseline_id) %>%
mutate(version = "Baseline"),
best_cls_config %>% mutate(version = "Grid Search")
) %>% arrange(model, version) %>%
select(model, version, configuration, cp, minsplit,
minbucket, maxdepth, cv_Balanced_Accuracy,
sd_Balanced_Accuracy, cv_Accuracy,
cv_F1, cv_Specificity, mean_terminal_nodes)
knitr::kable(cv_cls_comparison, digits = 5,
caption = "Baseline vs Tuned Classification — 10-fold CV")
reg_tie_check <- reg_grid_summary %>%
filter(configuration %in% c(42, 87)) %>%
mutate(RMSE_12_digits = sprintf("%.12f", cv_RMSE)) %>%
select(configuration, cp, cv_RMSE, RMSE_12_digits,
cv_MAE, mean_terminal_nodes)
knitr::kable(reg_tie_check,
caption = "Detailed comparison of regression ties")
# REFIT SELECTED MODELS ON FULL TRAINING DATA
fit_selected_tree <- function(spec, data, task, split = NULL) {
stopifnot(nrow(spec) == 1)
tree_control <- rpart.control(
cp = spec$cp, minsplit = spec$minsplit,
minbucket = spec$minbucket, maxdepth = spec$maxdepth,
xval = 0
)
if (task == "regression") {
fit <- rpart(quality ~ ., data = data,
method = "anova", control = tree_control)
} else {
fit <- rpart(quality_class ~ ., data = data,
method = "class", parms = list(split = split),
control = tree_control)
}
return(fit)
}
reg_tree_tuned <- fit_selected_tree(
best_reg_config, reg_train, task = "regression")
gini_spec <- best_cls_config %>% filter(model == "Gini")
cls_tree_gini_tuned <- fit_selected_tree(
gini_spec, cls_train, task = "classification", split = "gini")
entropy_spec <- best_cls_config %>% filter(model == "Entropy")
cls_tree_entropy_tuned <- fit_selected_tree(
entropy_spec, cls_train, task = "classification",
split = "information")
get_tree_structure <- function(fit, model, version) {
frame <- fit$frame
node_ids <- as.integer(rownames(frame))
tibble(model = model, version = version,
internal_nodes = sum(frame$var != "<leaf>"),
terminal_nodes = sum(frame$var == "<leaf>"),
total_nodes = nrow(frame),
tree_depth = max(floor(log2(node_ids))),
root_split = frame$var[1])
}
tuned_structure <- bind_rows(
get_tree_structure(reg_tree, "Regression", "Baseline"),
get_tree_structure(reg_tree_tuned, "Regression", "Grid Search"),
get_tree_structure(cls_tree_gini, "Gini", "Baseline"),
get_tree_structure(cls_tree_gini_tuned, "Gini", "Grid Search"),
get_tree_structure(cls_tree_entropy, "Entropy", "Baseline"),
get_tree_structure(cls_tree_entropy_tuned, "Entropy", "Grid Search")
)
knitr::kable(tuned_structure,
caption = "Baseline and tuned tree structures")
# SAVE FULL TUNED TREE VISUALIZATIONS
plot_dir <- file.path(grid_dir, "Tuned_Tree_Plots")
dir.create(plot_dir, recursive = TRUE, showWarnings = FALSE)
save_tree_plot <- function(fit, filename, title, extra) {
png(filename = file.path(plot_dir, filename),
width = 3200, height = 2000, res = 180)
tryCatch({
rpart.plot(fit, type = 2, extra = extra,
under = FALSE, fallen.leaves = TRUE,
faclen = 0, digits = 3, tweak = 0.8,
main = title)
}, finally = dev.off())
}
save_tree_plot(reg_tree_tuned, "Regression_Tree_Tuned.png",
"Tuned Regression Tree — Wine Quality", 101)
save_tree_plot(cls_tree_gini_tuned, "Classification_Gini_Tuned.png",
"Tuned Classification Tree — Gini", 104)
save_tree_plot(cls_tree_entropy_tuned,
"Classification_Entropy_Tuned.png",
"Tuned Classification Tree — Entropy", 104)
cat("Three tuned tree plots saved to:", plot_dir, "\n")Held-out test results are compared only after CV-based selection is complete.
Use the test set only after tuning is complete. Interpret regression scores, predicted-versus-actual plots, confusion matrices, and classification metrics without retuning.
evaluate_regression <- function(fit, label) {
actual <- reg_test$quality
predicted <- as.numeric(
predict(fit, newdata = reg_test, type = "vector"))
tibble(
version = label,
RMSE = sqrt(mean((actual - predicted)^2)),
MAE = mean(abs(actual - predicted)),
R2 = 1 - sum((actual - predicted)^2) /
sum((actual - mean(actual))^2)
)
}
reg_test_comparison <- bind_rows(
evaluate_regression(reg_tree_pruned, "Baseline"),
evaluate_regression(reg_tree_tuned, "Grid Search")
)
knitr::kable(reg_test_comparison, digits = 5,
caption = "Regression Tree baseline vs tuned on test data")
| Version | RMSE ↓ | MAE ↓ | R² ↑ |
|---|---|---|---|
| Baseline | 0,77330 | 0,60672 | 0,23380 |
| Grid Search | 0,75444 | 0,58748 | 0,27070 |
Interpretation. On the same 1,065 test cases, RMSE decreases from 0.77330 to 0.75444, MAE from 0.60672 to 0.58748, and R² improves from 0.2338 to 0.2707. The tuned regression tree thus improves all three reported test metrics.
reg_plot_comparison <- bind_rows(
tibble(actual = reg_test$quality,
predicted = as.numeric(predict(reg_tree_pruned,
newdata = reg_test, type = "vector")),
version = "Baseline"),
tibble(actual = reg_test$quality,
predicted = as.numeric(predict(reg_tree_tuned,
newdata = reg_test, type = "vector")),
version = "Grid Search")
)
ggplot(reg_plot_comparison, aes(x = actual, y = predicted)) +
geom_abline(intercept = 0, slope = 1, linetype = "dashed") +
geom_count(alpha = 0.65) +
facet_wrap(~ version, ncol = 2) +
labs(title = "Regression Tree: Baseline vs Grid Search",
subtitle = "Predictions on Test Data",
x = "Actual Quality", y = "Predicted Quality",
size = "Observations") +
theme_minimal(base_size = 12)
Interpretation. The tuned tree produces more distinct prediction levels than baseline, consistent with its increase from 5 to 29 leaves. The wider spread slightly improves predictive fit, although extreme quality scores still deviate from ideal predictions.
evaluate_classification <- function(fit, model, version) {
predicted <- predict(fit, newdata = cls_test, type = "class")
predicted <- factor(as.character(predicted),
levels = levels(cls_test$quality_class))
cm <- caret::confusionMatrix(
data = predicted, reference = cls_test$quality_class,
positive = "Good", mode = "everything")
metrics <- tibble(
model = model, version = version,
Accuracy = unname(cm$overall["Accuracy"]),
Precision = unname(cm$byClass["Precision"]),
Recall = unname(cm$byClass["Recall"]),
F1_score = unname(cm$byClass["F1"]),
Specificity = unname(cm$byClass["Specificity"]),
Balanced_Accuracy = unname(cm$byClass["Balanced Accuracy"])
)
list(metrics = metrics, confusion_matrix = cm,
predicted = predicted)
}
gini_base_eval <- evaluate_classification(
cls_tree_gini, "Gini", "Baseline")
gini_tuned_eval <- evaluate_classification(
cls_tree_gini_tuned, "Gini", "Grid Search")
entropy_base_eval <- evaluate_classification(
cls_tree_entropy, "Entropy", "Baseline")
entropy_tuned_eval <- evaluate_classification(
cls_tree_entropy_tuned, "Entropy", "Grid Search")
cat("\nTUNED GINI — TEST DATA\n")
print(gini_tuned_eval$confusion_matrix)
| Prediction \ Reference | Not Good | Good |
|---|---|---|
| Not Good | 242 (TN) | 137 (FN) |
| Good | 156 (FP) | 530 (TP) |
Interpretation. After tuning, correctly recognized Not Good cases increase from 231 to 242, while correctly recognized Good cases fall from 545 to 530. This explains higher specificity alongside lower Good recall.
evaluate_classification <- function(fit, model, version) {
predicted <- predict(fit, newdata = cls_test, type = "class")
predicted <- factor(as.character(predicted),
levels = levels(cls_test$quality_class))
cm <- caret::confusionMatrix(
data = predicted, reference = cls_test$quality_class,
positive = "Good", mode = "everything")
metrics <- tibble(
model = model, version = version,
Accuracy = unname(cm$overall["Accuracy"]),
Precision = unname(cm$byClass["Precision"]),
Recall = unname(cm$byClass["Recall"]),
F1_score = unname(cm$byClass["F1"]),
Specificity = unname(cm$byClass["Specificity"]),
Balanced_Accuracy = unname(cm$byClass["Balanced Accuracy"])
)
list(metrics = metrics, confusion_matrix = cm,
predicted = predicted)
}
gini_base_eval <- evaluate_classification(
cls_tree_gini, "Gini", "Baseline")
gini_tuned_eval <- evaluate_classification(
cls_tree_gini_tuned, "Gini", "Grid Search")
entropy_base_eval <- evaluate_classification(
cls_tree_entropy, "Entropy", "Baseline")
entropy_tuned_eval <- evaluate_classification(
cls_tree_entropy_tuned, "Entropy", "Grid Search")
cat("\nTUNED ENTROPY — TEST DATA\n")
print(entropy_tuned_eval$confusion_matrix)
| Prediction \ Reference | Not Good | Good |
|---|---|---|
| Not Good | 250 (TN) | 142 (FN) |
| Good | 148 (FP) | 525 (TP) |
Interpretation. After tuning, correctly recognized Not Good cases increase from 246 to 250 while Good cases fall from 533 to 525. Higher specificity comes with a small loss of Good recall and a slight decline in Balanced Accuracy.
evaluate_classification <- function(fit, model, version) {
predicted <- predict(fit, newdata = cls_test, type = "class")
predicted <- factor(as.character(predicted),
levels = levels(cls_test$quality_class))
cm <- caret::confusionMatrix(
data = predicted, reference = cls_test$quality_class,
positive = "Good", mode = "everything")
metrics <- tibble(
model = model, version = version,
Accuracy = unname(cm$overall["Accuracy"]),
Precision = unname(cm$byClass["Precision"]),
Recall = unname(cm$byClass["Recall"]),
F1_score = unname(cm$byClass["F1"]),
Specificity = unname(cm$byClass["Specificity"]),
Balanced_Accuracy = unname(cm$byClass["Balanced Accuracy"])
)
list(metrics = metrics, confusion_matrix = cm,
predicted = predicted)
}
gini_base_eval <- evaluate_classification(
cls_tree_gini, "Gini", "Baseline")
gini_tuned_eval <- evaluate_classification(
cls_tree_gini_tuned, "Gini", "Grid Search")
entropy_base_eval <- evaluate_classification(
cls_tree_entropy, "Entropy", "Baseline")
entropy_tuned_eval <- evaluate_classification(
cls_tree_entropy_tuned, "Entropy", "Grid Search")
cls_test_comparison <- bind_rows(
gini_base_eval$metrics, gini_tuned_eval$metrics,
entropy_base_eval$metrics, entropy_tuned_eval$metrics
)
knitr::kable(cls_test_comparison, digits = 5,
caption = "Classification Trees baseline vs tuned on test data")
| Model | Version | Accuracy | Precision | Recall | F1 | Specificity | Balanced Acc. |
|---|---|---|---|---|---|---|---|
| Gini | Baseline | 0,72864 | 0,76545 | 0,81709 | 0,79043 | 0,58040 | 0,69875 |
| Gini | Tuned | 0,72488 | 0,77259 | 0,79460 | 0,78344 | 0,60804 | 0,70132 |
| Entropy | Baseline | 0,73146 | 0,77810 | 0,79910 | 0,78846 | 0,61809 | 0,70860 |
| Entropy | Tuned | 0,72770 | 0,78009 | 0,78711 | 0,78358 | 0,62814 | 0,70762 |
Interpretation. Tuned Gini slightly improves test Balanced Accuracy from 0.69875 to 0.70132, although accuracy and F1 decrease. For entropy, Balanced Accuracy slightly declines from 0.70860 to 0.70762 despite improved specificity. Tuning does not improve every test measure.
This complete block shows the computational order for the stage. Run the stages from Data Preparation so dependencies are already available.
# FINAL TEST EVALUATION — BASELINE VS GRID SEARCH
evaluate_regression <- function(fit, label) {
actual <- reg_test$quality
predicted <- as.numeric(
predict(fit, newdata = reg_test, type = "vector"))
tibble(
version = label,
RMSE = sqrt(mean((actual - predicted)^2)),
MAE = mean(abs(actual - predicted)),
R2 = 1 - sum((actual - predicted)^2) /
sum((actual - mean(actual))^2)
)
}
reg_test_comparison <- bind_rows(
evaluate_regression(reg_tree_pruned, "Baseline"),
evaluate_regression(reg_tree_tuned, "Grid Search")
)
knitr::kable(reg_test_comparison, digits = 5,
caption = "Regression Tree baseline vs tuned on test data")
evaluate_classification <- function(fit, model, version) {
predicted <- predict(fit, newdata = cls_test, type = "class")
predicted <- factor(as.character(predicted),
levels = levels(cls_test$quality_class))
cm <- caret::confusionMatrix(
data = predicted, reference = cls_test$quality_class,
positive = "Good", mode = "everything")
metrics <- tibble(
model = model, version = version,
Accuracy = unname(cm$overall["Accuracy"]),
Precision = unname(cm$byClass["Precision"]),
Recall = unname(cm$byClass["Recall"]),
F1_score = unname(cm$byClass["F1"]),
Specificity = unname(cm$byClass["Specificity"]),
Balanced_Accuracy = unname(cm$byClass["Balanced Accuracy"])
)
list(metrics = metrics, confusion_matrix = cm,
predicted = predicted)
}
gini_base_eval <- evaluate_classification(
cls_tree_gini, "Gini", "Baseline")
gini_tuned_eval <- evaluate_classification(
cls_tree_gini_tuned, "Gini", "Grid Search")
entropy_base_eval <- evaluate_classification(
cls_tree_entropy, "Entropy", "Baseline")
entropy_tuned_eval <- evaluate_classification(
cls_tree_entropy_tuned, "Entropy", "Grid Search")
cls_test_comparison <- bind_rows(
gini_base_eval$metrics, gini_tuned_eval$metrics,
entropy_base_eval$metrics, entropy_tuned_eval$metrics
)
knitr::kable(cls_test_comparison, digits = 5,
caption = "Classification Trees baseline vs tuned on test data")
cat("\nTUNED GINI — TEST DATA\n")
print(gini_tuned_eval$confusion_matrix)
cat("\nTUNED ENTROPY — TEST DATA\n")
print(entropy_tuned_eval$confusion_matrix)
saveRDS(list(regression = reg_test_comparison,
classification = cls_test_comparison,
gini_cm = gini_tuned_eval$confusion_matrix,
entropy_cm = entropy_tuned_eval$confusion_matrix),
file.path(grid_dir, "final_test_comparison.rds"))
cat("\nFINAL TEST EVALUATION COMPLETED\n")
reg_plot_comparison <- bind_rows(
tibble(actual = reg_test$quality,
predicted = as.numeric(predict(reg_tree_pruned,
newdata = reg_test, type = "vector")),
version = "Baseline"),
tibble(actual = reg_test$quality,
predicted = as.numeric(predict(reg_tree_tuned,
newdata = reg_test, type = "vector")),
version = "Grid Search")
)
ggplot(reg_plot_comparison, aes(x = actual, y = predicted)) +
geom_abline(intercept = 0, slope = 1, linetype = "dashed") +
geom_count(alpha = 0.65) +
facet_wrap(~ version, ncol = 2) +
labs(title = "Regression Tree: Baseline vs Grid Search",
subtitle = "Predictions on Test Data",
x = "Actual Quality", y = "Predicted Quality",
size = "Observations") +
theme_minimal(base_size = 12)Marginal plots and heatmaps summarize all grid configurations, highlighting differences among parameter settings.
Examine how many configurations contribute to each summary, then read marginal plots and heatmaps. These are descriptive grid summaries, not isolated causal effects.
stopifnot(nrow(reg_grid_summary) == 360,
nrow(cls_grid_summary) == 720)
parameter_scores <- bind_rows(
reg_grid_summary %>% transmute(
model = "Regression", cp, minsplit, minbucket,
maxdepth, cv_score = cv_RMSE),
cls_grid_summary %>% transmute(
model = model, cp, minsplit, minbucket,
maxdepth, cv_score = cv_Balanced_Accuracy)
)
parameter_long <- parameter_scores %>%
pivot_longer(cols = c(cp, minsplit, minbucket, maxdepth),
names_to = "parameter", values_to = "value")
parameter_effect <- parameter_long %>%
group_by(model, parameter, value) %>%
summarise(mean_cv = mean(cv_score),
min_cv = min(cv_score), max_cv = max(cv_score),
configurations = n(), .groups = "drop")
parameter_coverage <- parameter_effect %>%
filter(model == "Regression") %>%
select(parameter, value, configurations) %>%
arrange(parameter, value)
knitr::kable(parameter_coverage,
caption = "Grid configurations represented per parameter")
| Parameter | Tested values | Configurations per value |
|---|---|---|
| cp | 8 nilai: 0 s.d. 0,05 | 45 |
| maxdepth | 3; 5; 8; 15; 30 | 72 |
| minbucket | 5; 7; 15 | 160; 120; 80 |
| minsplit | 10; 20; 40; 80 | 40; 80; 120; 120 |
Interpretation. Each cp value represents 45 grid configurations and each maxdepth value represents 72. Counts for minsplit and minbucket differ because minsplit ≥ 2 × minbucket filters out invalid pairings. Marginal curves are therefore descriptive summaries, not isolated one-factor experiments.
stopifnot(nrow(reg_grid_summary) == 360,
nrow(cls_grid_summary) == 720)
parameter_scores <- bind_rows(
reg_grid_summary %>% transmute(
model = "Regression", cp, minsplit, minbucket,
maxdepth, cv_score = cv_RMSE),
cls_grid_summary %>% transmute(
model = model, cp, minsplit, minbucket,
maxdepth, cv_score = cv_Balanced_Accuracy)
)
parameter_long <- parameter_scores %>%
pivot_longer(cols = c(cp, minsplit, minbucket, maxdepth),
names_to = "parameter", values_to = "value")
parameter_effect <- parameter_long %>%
group_by(model, parameter, value) %>%
summarise(mean_cv = mean(cv_score),
min_cv = min(cv_score), max_cv = max(cv_score),
configurations = n(), .groups = "drop")
parameter_coverage <- parameter_effect %>%
filter(model == "Regression") %>%
select(parameter, value, configurations) %>%
arrange(parameter, value)
knitr::kable(parameter_coverage,
caption = "Grid configurations represented per parameter")
reg_parameter_plot <- parameter_effect %>%
filter(model == "Regression") %>%
ggplot(aes(x = factor(value), y = mean_cv, group = 1)) +
geom_line(linewidth = 0.7) + geom_point(size = 2) +
facet_wrap(~ parameter, scales = "free_x", ncol = 2) +
labs(title = "Regression Tree — Hyperparameter Exploration",
subtitle = "Average 10-fold CV RMSE across grid configurations",
x = "Parameter Value", y = "Mean CV RMSE") +
theme_minimal(base_size = 12)
print(reg_parameter_plot)
Interpretation. Marginal mean CV RMSE is low around cp = 0.003–0.005 and maxdepth = 5, but the best individual configuration uses cp = 0.0005, minsplit = 80, minbucket = 15 and maxdepth = 5. Marginal averages and the best joint setting answer different questions.
stopifnot(nrow(reg_grid_summary) == 360,
nrow(cls_grid_summary) == 720)
parameter_scores <- bind_rows(
reg_grid_summary %>% transmute(
model = "Regression", cp, minsplit, minbucket,
maxdepth, cv_score = cv_RMSE),
cls_grid_summary %>% transmute(
model = model, cp, minsplit, minbucket,
maxdepth, cv_score = cv_Balanced_Accuracy)
)
parameter_long <- parameter_scores %>%
pivot_longer(cols = c(cp, minsplit, minbucket, maxdepth),
names_to = "parameter", values_to = "value")
parameter_effect <- parameter_long %>%
group_by(model, parameter, value) %>%
summarise(mean_cv = mean(cv_score),
min_cv = min(cv_score), max_cv = max(cv_score),
configurations = n(), .groups = "drop")
parameter_coverage <- parameter_effect %>%
filter(model == "Regression") %>%
select(parameter, value, configurations) %>%
arrange(parameter, value)
knitr::kable(parameter_coverage,
caption = "Grid configurations represented per parameter")
cls_parameter_plot <- parameter_effect %>%
filter(model %in% c("Gini", "Entropy")) %>%
ggplot(aes(x = factor(value), y = mean_cv,
group = model, color = model)) +
geom_line(linewidth = 0.7) + geom_point(size = 2) +
facet_wrap(~ parameter, scales = "free_x", ncol = 2) +
labs(title = "Classification Tree — Hyperparameter Exploration",
subtitle = "Average 10-fold CV Balanced Accuracy",
x = "Parameter Value", y = "Mean CV Balanced Accuracy",
color = "Splitting Criterion") +
theme_minimal(base_size = 12)
print(cls_parameter_plot)
Interpretation. Both criteria have relatively high mean CV Balanced Accuracy near cp = 0.003; increasing cp to 0.01 or above tends to reduce the mean. Depth affects Gini and entropy differently, showing why split criterion and complexity settings must be evaluated together.
reg_heatmap_data <- reg_grid_summary %>%
group_by(cp, maxdepth) %>%
summarise(mean_cv_rmse = mean(cv_RMSE), .groups = "drop")
reg_heatmap <- ggplot(reg_heatmap_data,
aes(x = factor(maxdepth),
y = factor(cp), fill = mean_cv_rmse)) +
geom_tile(color = "white", linewidth = 0.5) +
scale_fill_viridis_c(direction = -1, name = "CV RMSE") +
labs(title = "Regression Tree — CP × Maxdepth",
subtitle = "Average CV RMSE across minsplit and minbucket",
x = "Maxdepth", y = "CP") +
theme_minimal(base_size = 12)
print(reg_heatmap)
Interpretation. Lower mean regression CV RMSE tends to cluster at moderate-small cp values and depths near 5–8. Very low cp combined with depths 15–30 does not consistently improve error, illustrating why deeper trees need validation.
cls_heatmap_data <- cls_grid_summary %>%
group_by(model, cp, maxdepth) %>%
summarise(mean_cv_balanced_accuracy = mean(cv_Balanced_Accuracy),
.groups = "drop")
cls_heatmap <- ggplot(cls_heatmap_data,
aes(x = factor(maxdepth), y = factor(cp),
fill = mean_cv_balanced_accuracy)) +
geom_tile(color = "white", linewidth = 0.5) +
facet_wrap(~ model) +
scale_fill_viridis_c(name = "Balanced Accuracy") +
labs(title = "Classification Tree — CP × Maxdepth",
subtitle = "Average CV Balanced Accuracy across other parameters",
x = "Maxdepth", y = "CP") +
theme_minimal(base_size = 12)
print(cls_heatmap)
Interpretation. For Gini, cp = 0.003 at depths 15–30 has relatively high mean Balanced Accuracy; entropy shows another depth profile around the same cp. Each heatmap cell averages valid minsplit and minbucket combinations, not one specific tree.
This complete block shows the computational order for the stage. Run the stages from Data Preparation so dependencies are already available.
# HYPERPARAMETER EXPLORATION PLOTS — ALL 360 CONFIGURATIONS
stopifnot(nrow(reg_grid_summary) == 360,
nrow(cls_grid_summary) == 720)
parameter_scores <- bind_rows(
reg_grid_summary %>% transmute(
model = "Regression", cp, minsplit, minbucket,
maxdepth, cv_score = cv_RMSE),
cls_grid_summary %>% transmute(
model = model, cp, minsplit, minbucket,
maxdepth, cv_score = cv_Balanced_Accuracy)
)
parameter_long <- parameter_scores %>%
pivot_longer(cols = c(cp, minsplit, minbucket, maxdepth),
names_to = "parameter", values_to = "value")
parameter_effect <- parameter_long %>%
group_by(model, parameter, value) %>%
summarise(mean_cv = mean(cv_score),
min_cv = min(cv_score), max_cv = max(cv_score),
configurations = n(), .groups = "drop")
parameter_coverage <- parameter_effect %>%
filter(model == "Regression") %>%
select(parameter, value, configurations) %>%
arrange(parameter, value)
knitr::kable(parameter_coverage,
caption = "Grid configurations represented per parameter")
reg_parameter_plot <- parameter_effect %>%
filter(model == "Regression") %>%
ggplot(aes(x = factor(value), y = mean_cv, group = 1)) +
geom_line(linewidth = 0.7) + geom_point(size = 2) +
facet_wrap(~ parameter, scales = "free_x", ncol = 2) +
labs(title = "Regression Tree — Hyperparameter Exploration",
subtitle = "Average 10-fold CV RMSE across grid configurations",
x = "Parameter Value", y = "Mean CV RMSE") +
theme_minimal(base_size = 12)
print(reg_parameter_plot)
cls_parameter_plot <- parameter_effect %>%
filter(model %in% c("Gini", "Entropy")) %>%
ggplot(aes(x = factor(value), y = mean_cv,
group = model, color = model)) +
geom_line(linewidth = 0.7) + geom_point(size = 2) +
facet_wrap(~ parameter, scales = "free_x", ncol = 2) +
labs(title = "Classification Tree — Hyperparameter Exploration",
subtitle = "Average 10-fold CV Balanced Accuracy",
x = "Parameter Value", y = "Mean CV Balanced Accuracy",
color = "Splitting Criterion") +
theme_minimal(base_size = 12)
print(cls_parameter_plot)
reg_heatmap_data <- reg_grid_summary %>%
group_by(cp, maxdepth) %>%
summarise(mean_cv_rmse = mean(cv_RMSE), .groups = "drop")
reg_heatmap <- ggplot(reg_heatmap_data,
aes(x = factor(maxdepth),
y = factor(cp), fill = mean_cv_rmse)) +
geom_tile(color = "white", linewidth = 0.5) +
scale_fill_viridis_c(direction = -1, name = "CV RMSE") +
labs(title = "Regression Tree — CP × Maxdepth",
subtitle = "Average CV RMSE across minsplit and minbucket",
x = "Maxdepth", y = "CP") +
theme_minimal(base_size = 12)
print(reg_heatmap)
cls_heatmap_data <- cls_grid_summary %>%
group_by(model, cp, maxdepth) %>%
summarise(mean_cv_balanced_accuracy = mean(cv_Balanced_Accuracy),
.groups = "drop")
cls_heatmap <- ggplot(cls_heatmap_data,
aes(x = factor(maxdepth), y = factor(cp),
fill = mean_cv_balanced_accuracy)) +
geom_tile(color = "white", linewidth = 0.5) +
facet_wrap(~ model) +
scale_fill_viridis_c(name = "Balanced Accuracy") +
labs(title = "Classification Tree — CP × Maxdepth",
subtitle = "Average CV Balanced Accuracy across other parameters",
x = "Maxdepth", y = "CP") +
theme_minimal(base_size = 12)
print(cls_heatmap)In a step function, interval boundaries are specified in advance. CART uses a similar idea of region-wise predictions, but learns the splitting variables and thresholds from the data. Each branch rule and terminal-node value must therefore be read together: a rule determines which observations enter a region, and the terminal node determines their prediction.
For a numerical response, a regression tree chooses splits that reduce the residual sum of squares (RSS) and predicts the mean response within each terminal node. For a categorical response, a classification tree works with class composition: Gini or entropy guides splitting, while the majority class and class proportions determine node-level classification. The manual calculations and interactive examples illustrate how changing a cutpoint changes the groups, prediction error, or impurity.
A larger tree can reduce training error without necessarily improving predictions on unseen observations. Cost-complexity pruning penalizes additional leaves, while cross-validation compares prediction errors on folds excluded from model fitting. For Wine Quality, the baseline regression tree had five terminal nodes; choosing CP from its internal CV table did not change the tree. The subsequent grid search compared 360 configurations each for regression, Gini and entropy using ten-fold cross-validation on the training data.
The table below uses the 1,065 test observations that were not used to select hyperparameters. Lower RMSE indicates better regression predictions, while higher Balanced Accuracy indicates better average recognition across the two classes.
| Model | Test metric | Baseline | Grid search |
|---|---|---|---|
| Regression Tree | RMSE ↓ | 0.77330 | 0.75444 |
| Gini | Balanced Accuracy ↑ | 0.69875 | 0.70132 |
| Entropy | Balanced Accuracy ↑ | 0.70860 | 0.70762 |
Regression improved on the test data: RMSE fell from 0.77330 to 0.75444, MAE from 0.60672 to 0.58748, and R² increased from 0.2338 to 0.2707. For classification, Gini's Balanced Accuracy increased only slightly while entropy's decreased slightly. Other metrics can move in opposite directions—for example, higher specificity can coincide with lower recall—so a tuned tree is not automatically better in every respect.
The central lesson is to consider split rules, terminal-node composition, tree complexity, and test performance together. Hyperparameters are selected by cross-validation on training data; the test set evaluates the final model rather than deciding which configuration to use after seeing its score.
Bacallado, S., & Taylor, J. (2022). Regression trees. STATS 202, Stanford University (based on James et al., 2021). Course notes.
James, G., Witten, D., Hastie, T., & Tibshirani, R. (2021). An Introduction to Statistical Learning: With Applications in R (2nd ed.), Chapter 8. Springer. https://www.statlearning.com/resources-second-edition
Breiman, L., Friedman, J. H., Olshen, R. A., & Stone, C. J. (1984). Classification and Regression Trees. Wadsworth.
Cortez, P., Cerdeira, A., Almeida, F., Matos, T., & Reis, J. (2009). Modeling wine preferences by data mining from physicochemical properties. Decision Support Systems, 47, 547–553. https://doi.org/10.1016/j.dss.2009.05.016
UCI Machine Learning Repository. Wine Quality [Dataset]. https://archive.ics.uci.edu/dataset/186/wine+quality
R documentation: rpart, rpart.plot, caret, rsample.