U.UNIQUE / PRACTICUM NOTESSTATISTICS & DATA SCIENCE
IPB UNIVERSITYPRACTICUM 10
Daftar IsiTable of Contents

Distance-Based and Margin/Kernel-Based Learning

K-Nearest Neighbors · Support Vector Machine · Support Vector Regression

Bagaimana kita memprediksi kualitas anggur dari karakteristik fisikokimianya? KNN memanfaatkan observasi yang paling mirip, sementara SVM dan SVR membentuk fungsi keputusan atau prediksi dengan mempertimbangkan margin dan kernel. Pada praktikum ini kita mencoba kedua pendekatan untuk klasifikasi maupun regresi.How can we predict wine quality from physicochemical characteristics? KNN uses the most similar observations, while SVM and SVR construct decision or prediction functions using margins and kernels. In this practicum we apply both approaches to classification and regression.

Gunakan RStudio dan jalankan kode sesuai urutan. Hasil di bawah kode merupakan hasil render R yang tersedia untuk dataset praktikum; simulasi konsep berjalan langsung di browser dan memakai data ilustrasi apabila dinyatakan demikian.Use RStudio and run the code in order. Outputs beneath the code are rendered R results for the practicum dataset; conceptual simulations run in the browser and use illustrative data where indicated.

Wine QualityDataset
→
PreprocessingSplit · scaling
→
KNN · SVM · SVR5-fold CV
→
EvaluationClassification · regression

Konsep Dasar Distance-Based dan Support Vector LearningBasic Concepts of Distance-Based and Support Vector Learning

Dalam pembelajaran mesin terawasi (supervised learning), hubungan antara prediktor dan respons dapat dipelajari melalui pendekatan yang berbeda. Sebagian algoritma membentuk prediksi berdasarkan kedekatan suatu observasi dengan observasi lainnya, sedangkan algoritma lain membentuk fungsi keputusan melalui proses optimasi.

K-Nearest Neighbors (KNN) merupakan metode pembelajaran berbasis jarak (distance-based learning). Algoritma ini menggunakan sejumlah observasi data latih yang paling dekat dengan observasi baru untuk menentukan hasil prediksi. Sebaliknya, Support Vector Machine (SVM) menggunakan prinsip optimasi untuk membentuk fungsi keputusan berdasarkan karakteristik data latih.

Pada klasifikasi, SVM mencari batas keputusan yang memisahkan kelas dengan mempertimbangkan margin. Sementara itu, pengembangan SVM untuk respons numerik dikenal sebagai Support Vector Regression (SVR), yang membentuk fungsi regresi dengan toleransi kesalahan tertentu.

Perbedaan dasar kedua pendekatan dirangkum pada tabel berikut.

Aspek K-Nearest Neighbors Support Vector Machine
Prinsip pembelajaran Kedekatan antarobservasi Optimasi fungsi keputusan
Dasar prediksi Observasi terdekat Fungsi keputusan hasil optimasi
Klasifikasi Voting kelas tetangga Penentuan kelas melalui batas keputusan
Regresi Rata-rata respons tetangga Fungsi regresi dengan toleransi kesalahan
Karakteristik model Nonparametrik, berbasis observasi Berbasis optimasi margin dan regularisasi
Parameter utama Jumlah tetangga dan ukuran jarak Cost, kernel, dan parameter kernel

KNN dan SVM dapat digunakan pada klasifikasi maupun regresi, tetapi mempunyai formulasi dan mekanisme prediksi yang berbeda.

In supervised learning, the relationship between predictors and the response can be learned through different approaches. Some algorithms generate predictions based on the proximity of an observation to other observations, whereas others construct a decision function through an optimization process.

K-Nearest Neighbors (KNN) is a distance-based learning method. This algorithm uses a number of training observations closest to a new observation to determine its prediction. In contrast, Support Vector Machine (SVM) applies optimization principles to construct a decision function based on the characteristics of the training data.

In classification, SVM identifies a decision boundary that separates classes while considering the margin. The extension of SVM to numerical responses is known as Support Vector Regression (SVR), which constructs a regression function with a specified tolerance for prediction errors.

The fundamental differences between these approaches are summarized in the following table.

Aspect K-Nearest Neighbors Support Vector Machine
Learning principle Proximity between observations Optimization of a decision function
Basis of prediction Nearest observations Optimized decision function
Classification Voting among neighboring classes Class determination using a decision boundary
Regression Mean response of neighboring observations Regression function with error tolerance
Model characteristics Nonparametric and observation-based Margin optimization and regularization
Main parameters Number of neighbors and distance measure Cost, kernel, and kernel parameters

Both KNN and SVM can be used for classification and regression. However, their mathematical formulations and prediction mechanisms differ.

Representasi DataData Representation

Misalkan tersedia \(n\) observasi dengan \(p\) prediktor yang dinyatakan sebagai:

\[\mathcal{D} = \left\{ (\mathbf{x}_i,y_i) \right\}_{i=1}^{n}\]

dengan:

  • \(\mathbf{x}_i=(x_{i1},x_{i2},\ldots,x_{ip})^\top\) merupakan vektor prediktor observasi ke-\(i\);
  • \(y_i\) merupakan nilai respons observasi ke-\(i\);
  • \(n\) merupakan jumlah observasi;
  • \(p\) merupakan jumlah prediktor.

Untuk klasifikasi, \(y_i\) menunjukkan kategori kelas. Sementara itu, pada regresi, \(y_i\) merupakan respons numerik.

Tujuan pemodelan adalah membentuk aturan prediksi untuk observasi baru \(\mathbf{x}_0\) berdasarkan hubungan yang dipelajari dari data latih.

Suppose a dataset contains \(n\) observations and \(p\) predictors, represented as:

\[\mathcal{D} = \left\{ (\mathbf{x}_i,y_i) \right\}_{i=1}^{n}\]

where:

  • \(\mathbf{x}_i=(x_{i1},x_{i2},\ldots,x_{ip})^\top\) is the predictor vector for the \(i\)-th observation;
  • \(y_i\) is the response value for the \(i\)-th observation;
  • \(n\) is the number of observations;
  • \(p\) is the number of predictors.

For classification, \(y_i\) represents a class category. For regression, \(y_i\) represents a numerical response.

The objective of modeling is to construct a prediction rule for a new observation \(\mathbf{x}_0\) based on the relationship learned from the training data.

K-Nearest Neighbors (KNN)K-Nearest Neighbors (KNN)

Konsep Dasar KNNBasic Concept of KNN

K-Nearest Neighbors merupakan metode pembelajaran terawasi nonparametrik yang menggunakan kedekatan antarobservasi sebagai dasar prediksi. Algoritma ini tidak mengasumsikan bentuk hubungan tertentu antara prediktor dan respons, seperti hubungan linear atau kuadratik.

KNN bekerja dengan menghitung jarak antara observasi baru dan observasi pada data latih. Setelah seluruh jarak diperoleh, algoritma memilih \(K\) observasi dengan jarak terkecil. Respons dari observasi terdekat tersebut kemudian digunakan untuk menghasilkan prediksi.

Secara umum, proses KNN mencakup:

  • Menentukan jumlah tetangga \(K\).
  • Menghitung jarak observasi baru terhadap setiap observasi data latih.
  • Mengurutkan observasi berdasarkan jarak.
  • Memilih \(K\) observasi terdekat.
  • Menghasilkan prediksi berdasarkan respons tetangga terpilih.

KNN: nearest neighbors

Referensi gambar: James et al. (2021), An Introduction to Statistical Learning, Figure 2.14.

Keterangan: Ilustrasi pemilihan tiga observasi terdekat untuk menentukan kelas observasi baru.

Perhatikan titik berbentuk silang hitam pada panel kiri.

Titik tersebut merupakan observasi baru yang belum diketahui kelasnya. Lingkaran menunjukkan wilayah yang memuat tiga observasi terdekat.

Di dalam lingkaran terdapat:

  • Dua observasi berwarna biru.

  • Satu observasi berwarna oranye.

Karena mayoritas tetangganya merupakan kelas biru, KNN menetapkan observasi baru tersebut ke kelas biru.

Panel kanan memperlihatkan batas keputusan yang dihasilkan ketika prosedur yang sama diterapkan pada berbagai kemungkinan posisi observasi baru.

Hal penting: Batas keputusan KNN terbentuk dari aturan pemilihan tetangga di berbagai posisi dalam ruang prediktor. Algoritma tidak terlebih dahulu mengestimasi satu persamaan garis pemisah seperti pada model klasifikasi linear.

K-Nearest Neighbors is a nonparametric supervised learning method that uses proximity between observations as the basis for prediction. This algorithm does not assume a particular functional relationship between predictors and the response, such as a linear or quadratic relationship.

KNN works by calculating the distance between a new observation and each observation in the training data. After all distances have been calculated, the algorithm selects the \(K\) observations with the smallest distances. The responses of these nearest observations are then used to generate a prediction.

In general, the KNN procedure consists of the following steps:

  1. Determine the number of neighbors, \(K\).
  2. Calculate the distance between the new observation and each training observation.
  3. Sort the observations according to their distances.
  4. Select the \(K\) nearest observations.
  5. Generate a prediction based on the responses of the selected neighbors.

KNN: nearest neighbors

Figure reference: James et al. (2021), An Introduction to Statistical Learning, Figure 2.14.

Description: Illustration of selecting the three nearest observations to determine the class of a new observation.

Consider the black cross in the left panel.

This point represents a new observation whose class is unknown. The circle indicates the region containing its three nearest observations.

Inside the circle, there are:

  • Two blue observations.
  • One orange observation.

Because the majority of its nearest neighbors belong to the blue class, KNN assigns the new observation to the blue class.

The right panel shows the decision boundary obtained when the same procedure is applied to different possible locations of new observations.

Important point: The KNN decision boundary is formed by applying the nearest-neighbor rule across different locations in the predictor space. Unlike a linear classification model, KNN does not first estimate a single equation for a separating line.

Pengukuran Jarak AntarobservasiMeasuring Distances Between Observations

Pemilihan tetangga merupakan komponen utama KNN. Oleh karena itu, ukuran jarak menentukan observasi mana yang dianggap paling dekat.

Neighbor selection is the main component of KNN. Therefore, the distance measure determines which observations are considered closest to a new observation.

Euclidean DistanceEuclidean Distance

Jarak Euclidean antara observasi \(\mathbf{x}_i\) dan \(\mathbf{x}_j\) dinyatakan sebagai:

\[d(\mathbf{x}_i,\mathbf{x}_j) = \sqrt{ \sum_{r=1}^{p} (x_{ir}-x_{jr})^2 }\]

Untuk dua prediktor, formulasi tersebut menjadi:

\[d(\mathbf{x}_i,\mathbf{x}_j) = \sqrt{ (x_{i1}-x_{j1})^2+ (x_{i2}-x_{j2})^2 }\]

Sebagai contoh, misalkan:

\[\mathbf{x}_1=(2,3)\]

dan:

\[\mathbf{x}_2=(5,7)\]

Jarak kedua observasi adalah:

\[\begin{aligned} d(\mathbf{x}_1,\mathbf{x}_2) &= \sqrt{(2-5)^2+(3-7)^2}\\ &= \sqrt{9+16}\\ &=5 \end{aligned}\]

Semakin kecil nilai jarak, semakin dekat posisi kedua observasi dalam ruang prediktor.

The Euclidean distance between observations \(\mathbf{x}_i\) and \(\mathbf{x}_j\) is defined as:

\[d(\mathbf{x}_i,\mathbf{x}_j) = \sqrt{ \sum_{r=1}^{p} (x_{ir}-x_{jr})^2 }\]

For two predictors, the formula becomes:

\[d(\mathbf{x}_i,\mathbf{x}_j) = \sqrt{ (x_{i1}-x_{j1})^2+ (x_{i2}-x_{j2})^2 }\]

For example, suppose:

\[\mathbf{x}_1=(2,3)\]

and:

\[\mathbf{x}_2=(5,7)\]

The distance between these two observations is:

\[\begin{aligned} d(\mathbf{x}_1,\mathbf{x}_2) &= \sqrt{(2-5)^2+(3-7)^2}\\ &= \sqrt{9+16}\\ &=5 \end{aligned}\]

A smaller distance indicates that the two observations are closer to each other in the predictor space.

Manhattan DistanceManhattan Distance

Jarak Manhattan menghitung jumlah selisih absolut setiap prediktor:

\[d(\mathbf{x}_i,\mathbf{x}_j) = \sum_{r=1}^{p} |x_{ir}-x_{jr}|\]

Untuk contoh yang sama:

\[\begin{aligned} d(\mathbf{x}_1,\mathbf{x}_2) &= |2-5|+|3-7|\\ &=3+4\\ &=7 \end{aligned}\]

Manhattan distance calculates the sum of the absolute differences across all predictors:

\[d(\mathbf{x}_i,\mathbf{x}_j) = \sum_{r=1}^{p} |x_{ir}-x_{jr}|\]

Using the same example:

\[\begin{aligned} d(\mathbf{x}_1,\mathbf{x}_2) &= |2-5|+|3-7|\\ &=3+4\\ &=7 \end{aligned}\]

Minkowski DistanceMinkowski Distance

Euclidean Distance dan Manhattan Distance merupakan kasus khusus dari Minkowski Distance:

\[d_q(\mathbf{x}_i,\mathbf{x}_j) = \left( \sum_{r=1}^{p} |x_{ir}-x_{jr}|^q \right)^{1/q}\]

dengan \(q\geq1\).

Apabila \(q=1\), diperoleh Manhattan Distance. Apabila \(q=2\), diperoleh Euclidean Distance.

Perbedaan ukuran jarak dapat menghasilkan urutan tetangga yang berbeda sehingga turut memengaruhi hasil prediksi KNN.

Euclidean distance and Manhattan distance are special cases of Minkowski distance:

\[d_q(\mathbf{x}_i,\mathbf{x}_j) = \left( \sum_{r=1}^{p} |x_{ir}-x_{jr}|^q \right)^{1/q}\]

where \(q\geq1\).

When \(q=1\), the formula corresponds to Manhattan distance. When \(q=2\), it corresponds to Euclidean distance.

Different distance measures may produce different rankings of nearest neighbors and, consequently, affect KNN predictions.

INTERACTIVE 01

Laboratorium pengukuran jarakDistance measurement laboratory

Ubah titik B. Garis diagonal menunjukkan lintasan Euclidean, garis siku menunjukkan lintasan Manhattan.Move point B. The diagonal shows the Euclidean path; the right-angle path shows Manhattan distance.

KNN untuk KlasifikasiKNN for Classification

Pada klasifikasi, KNN menggunakan kelas yang paling banyak ditemukan di antara \(K\) tetangga terdekat.

Misalkan \(\mathcal{N}_K(\mathbf{x}_0)\) merupakan himpunan indeks \(K\) observasi terdekat dari observasi baru \(\mathbf{x}_0\).

Proporsi tetangga yang termasuk kelas \(g\) dinyatakan sebagai:

\[\widehat{P}(Y=g\mid\mathbf{X}=\mathbf{x}_0) = \frac{1}{K} \sum_{i\in\mathcal{N}_K(\mathbf{x}_0)} I(y_i=g)\]

dengan fungsi indikator:

\[I(y_i=g) = \begin{cases} 1, & \text{jika } y_i=g\\ 0, & \text{jika } y_i\neq g \end{cases}\]

Kelas prediksi ditentukan berdasarkan proporsi terbesar:

\[\boxed{ \hat y_0 = \arg\max_g \widehat{P}(Y=g\mid\mathbf{X}=\mathbf{x}_0) }\]

Sebagai contoh, apabila digunakan \(K=5\) dengan tiga tetangga kelas A dan dua tetangga kelas B, maka:

\[\widehat P(Y=A\mid\mathbf{x}_0) = \frac{3}{5} = 0{,}6\]

\[\widehat P(Y=B\mid\mathbf{x}_0) = \frac{2}{5} = 0{,}4\]

Dengan demikian, observasi baru diklasifikasikan sebagai kelas A.

Proporsi tersebut merupakan perkiraan probabilitas kelas berdasarkan komposisi tetangga terpilih. Nilainya tidak otomatis menjadi probabilitas yang terkalibrasi.

In classification, KNN uses the most frequently occurring class among the \(K\) nearest neighbors.

Let \(\mathcal{N}_K(\mathbf{x}_0)\) denote the set of indices corresponding to the \(K\) nearest training observations to a new observation \(\mathbf{x}_0\).

The proportion of neighboring observations belonging to class \(g\) is defined as:

\[\widehat{P}(Y=g\mid\mathbf{X}=\mathbf{x}_0) = \frac{1}{K} \sum_{i\in\mathcal{N}_K(\mathbf{x}_0)} I(y_i=g)\]

where the indicator function is:

\[I(y_i=g) = \begin{cases} 1, & \text{if } y_i=g\\ 0, & \text{if } y_i\neq g \end{cases}\]

The predicted class is determined by the largest class proportion:

\[\boxed{ \hat y_0 = \arg\max_g \widehat{P}(Y=g\mid\mathbf{X}=\mathbf{x}_0) }\]

For example, suppose \(K=5\), with three neighbors belonging to class A and two neighbors belonging to class B.

Then:

\[\widehat P(Y=A\mid\mathbf{x}_0) = \frac{3}{5} = 0.6\]

\[\widehat P(Y=B\mid\mathbf{x}_0) = \frac{2}{5} = 0.4\]

Therefore, the new observation is classified as class A.

These proportions represent estimated class probabilities based on the composition of the selected neighbors. However, they are not automatically calibrated probabilities.

KNN untuk RegresiKNN for Regression

Pada regresi, KNN menggunakan rata-rata nilai respons dari \(K\) tetangga terdekat.

Formulasinya adalah:

\[\boxed{ \hat y_0 = \frac{1}{K} \sum_{i\in\mathcal{N}_K(\mathbf{x}_0)} y_i }\]

Misalkan tiga observasi terdekat mempunyai nilai respons:

\[y_1=120,\qquad y_2=150,\qquad y_3=180\]

Dengan \(K=3\), prediksinya adalah:

\[\begin{aligned} \hat y_0 &= \frac{120+150+180}{3}\\ &=150 \end{aligned}\]

Perbedaan utama KNN klasifikasi dan regresi terletak pada cara menggabungkan respons tetangga. Klasifikasi menggunakan voting kelas, sedangkan regresi menggunakan rata-rata respons numerik.

In regression, KNN uses the mean response value of the \(K\) nearest neighbors.

The prediction formula is:

\[\boxed{ \hat y_0 = \frac{1}{K} \sum_{i\in\mathcal{N}_K(\mathbf{x}_0)} y_i }\]

Suppose the three nearest observations have the following response values:

\[y_1=120,\qquad y_2=150,\qquad y_3=180\]

With \(K=3\), the predicted response is:

\[\begin{aligned} \hat y_0 &= \frac{120+150+180}{3}\\ &=150 \end{aligned}\]

The main difference between KNN classification and regression lies in how the neighboring responses are combined. Classification uses class voting, whereas regression uses the mean of numerical responses.

Weighted KNNWeighted KNN

Pada KNN standar, setiap tetangga memberikan kontribusi yang sama. Akan tetapi, observasi yang lebih dekat dapat diberikan bobot lebih besar.

Untuk regresi, prediksi berbobot dinyatakan sebagai:

\[\hat y_0 = \frac{ \sum_{i\in\mathcal{N}_K(\mathbf{x}_0)} w_i(\mathbf{x}_0)y_i }{ \sum_{i\in\mathcal{N}_K(\mathbf{x}_0)} w_i(\mathbf{x}_0) }\]

dengan \(w_i(\mathbf{x}_0)\geq0\) merupakan bobot tetangga ke-\(i\).

Pada klasifikasi berbobot, kontribusi kelas dihitung berdasarkan jumlah bobot:

\[\hat y_0 = \arg\max_g \sum_{i\in\mathcal{N}_K(\mathbf{x}_0)} w_i(\mathbf{x}_0)I(y_i=g)\]

Pembobotan memungkinkan observasi yang lebih dekat mempunyai kontribusi lebih besar terhadap hasil prediksi.

In standard KNN, every selected neighbor contributes equally to the prediction. However, observations that are closer to the new observation can be assigned larger weights.

For regression, the weighted prediction is defined as:

\[\hat y_0 = \frac{ \sum_{i\in\mathcal{N}_K(\mathbf{x}_0)} w_i(\mathbf{x}_0)y_i }{ \sum_{i\in\mathcal{N}_K(\mathbf{x}_0)} w_i(\mathbf{x}_0) }\]

where \(w_i(\mathbf{x}_0)\geq0\) is the weight assigned to the \(i\)-th neighbor, with a positive total weight.

For weighted classification, class contributions are calculated using the sum of the corresponding weights:

\[\hat y_0 = \arg\max_g \sum_{i\in\mathcal{N}_K(\mathbf{x}_0)} w_i(\mathbf{x}_0)I(y_i=g)\]

Weighting allows observations closer to the new observation to have a greater influence on the prediction.

INTERACTIVE 02

Laboratorium KNNKNN laboratory

Data ilustrasi, bukan Wine Quality. Titik yang berimpit memperoleh seluruh bobot dalam mode inverse distance; seri kelas dilaporkan sebagai seri.Illustrative data, not Wine Quality. Exact matches receive all weight in inverse-distance mode; class ties are reported as ties.

Pengaruh Jumlah TetanggaEffect of the Number of Neighbors

Jumlah tetangga \(K\) menentukan tingkat fleksibilitas model KNN.

KNN: effect of k

Referensi gambar: James et al. (2021), An Introduction to Statistical Learning, Figure 2.16.

Keterangan: Perbandingan fleksibilitas batas keputusan KNN berdasarkan jumlah tetangga.

Pada panel kiri, \(K=1\) menghasilkan batas keputusan yang sangat tidak beraturan. Setiap prediksi bergantung pada satu observasi terdekat, sehingga perubahan kecil posisi observasi baru dapat mengubah kelas prediksi.

Pada panel kanan, \(K=100\) menghasilkan batas yang lebih sederhana. Prediksi dipengaruhi oleh lebih banyak observasi, sehingga pola lokal yang lebih kecil dapat terabaikan.

Nilai \(K\) yang kecil menghasilkan model lebih fleksibel karena prediksi sangat dipengaruhi observasi lokal. Namun, kondisi ini juga meningkatkan sensitivitas model terhadap variasi data.

Sebaliknya, nilai \(K\) yang besar menghasilkan prediksi lebih halus karena mempertimbangkan lebih banyak observasi.

Secara umum:

  • \(K\) kecil cenderung menghasilkan bias lebih rendah dan varians lebih tinggi.
  • \(K\) besar cenderung menghasilkan bias lebih tinggi dan varians lebih rendah.

Hubungan tersebut menunjukkan adanya pertukaran antara bias dan varians (bias-variance trade-off).

KNN: training and test error

Referensi gambar: James et al. (2021), An Introduction to Statistical Learning, Figure 2.17.

Keterangan: Hubungan fleksibilitas KNN dengan kesalahan prediksi pada data latih dan data uji.

Pada gambar 2.17, sumbu horizontal menggunakan \(1/k\), sehingga bergerak ke kanan berarti jumlah tetangga semakin kecil dan model semakin fleksibel.

Perhatikan bahwa kesalahan pada data latih cenderung turun ketika fleksibilitas meningkat. Namun, kesalahan pada data uji tidak selalu mengikuti pola tersebut.Ketika model terlalu fleksibel, kesalahan pada data latih dapat menjadi kecil, tetapi kemampuan prediksi pada observasi baru belum tentu meningkat. Kondisi tersebut berkaitan dengan risiko overfitting.

Pelajaran utamanya: nilai \(k\) tidak ditentukan berdasarkan kemampuan model menyesuaikan data latih semata. Nilai tersebut perlu dipilih menggunakan prosedur validasi.

The number of neighbors, \(K\), determines the flexibility of the KNN model.

KNN: effect of k

Figure reference: James et al. (2021), An Introduction to Statistical Learning, Figure 2.16.

Description: Comparison of the flexibility of KNN decision boundaries for different numbers of neighbors.

In the left panel, \(K=1\) produces a highly irregular decision boundary. Each prediction depends on only one nearest observation, so a small change in the location of a new observation may change its predicted class.

In the right panel, \(K=100\) produces a smoother and simpler decision boundary. Predictions are influenced by more observations, so smaller local patterns may be overlooked.

A small value of \(K\) produces a more flexible model because predictions are strongly influenced by local observations. However, this also increases the model’s sensitivity to variations in the data.

Conversely, a large value of \(K\) produces smoother predictions because more observations are considered.

In general:

  • A small \(K\) tends to produce lower bias and higher variance.
  • A large \(K\) tends to produce higher bias and lower variance.

This relationship illustrates the bias–variance trade-off.

KNN: training and test error

Figure reference: James et al. (2021), An Introduction to Statistical Learning, Figure 2.17.

Description: Relationship between KNN flexibility and prediction errors in training and test data.

In Figure 2.17, the horizontal axis uses \(1/K\). Therefore, moving to the right corresponds to a smaller number of neighbors and a more flexible model.

Notice that training error generally decreases as model flexibility increases. However, test error does not necessarily follow the same pattern.

When a model becomes too flexible, training error may become very small, but its predictive performance on new observations may not improve. This situation is associated with the risk of overfitting.

The key lesson: The value of \(K\) should not be selected solely based on how well the model fits the training data. It should be selected using a validation procedure.

Keterbatasan KNNLimitations of KNN

Ada empat persoalan penting.

Pertama, curse of dimensionality. Ketika jumlah dimensi meningkat, observasi cenderung semakin tersebar dalam ruang prediktor. Tetangga yang secara relatif paling dekat belum tentu benar-benar dekat secara geometris.

Kedua, sensitivitas terhadap skala. Prediktor dengan rentang nilai besar dapat mendominasi jarak.

Ketiga, sensitivitas terhadap distribusi kelas. Dalam klasifikasi dengan kelas tidak seimbang, kelas mayoritas berpotensi lebih sering muncul di lingkungan tetangga.

Keempat, biaya prediksi. KNN perlu mencari tetangga untuk setiap observasi baru. Untuk data besar, pencarian tersebut dapat memerlukan komputasi yang cukup tinggi, meskipun tersedia berbagai strategi pencarian yang lebih efisien.

There are four important limitations.

First, the curse of dimensionality. As the number of dimensions increases, observations tend to become more dispersed in the predictor space. The relatively nearest observation may no longer be particularly close in geometric terms.

Second, sensitivity to predictor scales. Predictors with larger numerical ranges may dominate distance calculations.

Third, sensitivity to class distributions. In classification with imbalanced classes, observations from the majority class may appear more frequently among the selected neighbors.

Fourth, computational cost during prediction. KNN must identify nearest neighbors for each new observation. For large datasets, this search may require substantial computation, although more efficient search strategies are available.

Support Vector Machine (SVM)Support Vector Machine (SVM)

Konsep Dasar SVMBasic Concept of SVM

Support Vector Machine merupakan metode pembelajaran terawasi yang mencari fungsi keputusan melalui proses optimasi.

Pada klasifikasi biner, SVM berusaha membentuk hyperplane yang memisahkan dua kelas dengan margin sebesar mungkin. Margin merupakan jarak antara hyperplane dan observasi terdekat yang menentukan batas pemisahan.

Observasi yang berperan dalam menentukan margin disebut support vectors.

SVM: hyperplane and support vectors

Referensi gambar: James et al. (2021), An Introduction to Statistical Learning, Figure 9.3.

Keterangan: Hyperplane optimal, batas margin, dan observasi yang berperan sebagai support vectors.

Pada gambar tersebut:

  1. Garis penuh merupakan hyperplane pemisah.

  2. Dua garis putus-putus merupakan batas margin.

  3. Titik yang berada tepat pada batas margin merupakan support vectors.

  4. Wilayah dengan warna berbeda menunjukkan kelas yang diprediksi oleh model.

Support vectors memiliki peranan penting karena menentukan posisi batas keputusan yang optimal. Pada kasus margin maksimum, perubahan posisi support vectors dapat mengubah hyperplane, sedangkan perubahan kecil pada observasi lain yang tetap berada di luar margin tidak selalu memengaruhinya.

Support Vector Machine is a supervised learning method that constructs a decision function through an optimization process.

In binary classification, SVM seeks to construct a hyperplane that separates two classes with the largest possible margin. The margin describes the distance between the separating hyperplane and the nearest observations that determine the separation.

Observations that play a role in determining the margin are called support vectors.

SVM: hyperplane and support vectors

Figure reference: James et al. (2021), An Introduction to Statistical Learning, Figure 9.3.

Description: Optimal separating hyperplane, margin boundaries, and observations acting as support vectors.

In the illustration:

  • The solid line represents the separating hyperplane.
  • The two dashed lines represent the margin boundaries.
  • Points located exactly on the margin boundaries are support vectors.
  • Regions with different colors indicate the classes predicted by the model.

Support vectors are important because they determine the position of the optimal decision boundary. In the maximum-margin setting, changing the positions of support vectors may change the hyperplane, whereas small changes to other observations that remain outside the margin do not necessarily affect it.

Formulasi HyperplaneHyperplane Formulation

Untuk \(p\) prediktor, fungsi keputusan linear dinyatakan sebagai:

\[f(\mathbf{x}) = \mathbf{w}^{\top}\mathbf{x}+b\]

dengan:

  • \(\mathbf{w}=(w_1,w_2,\ldots,w_p)^\top\) merupakan vektor bobot;
  • \(\mathbf{x}\) merupakan vektor prediktor;
  • \(b\) merupakan intersep.

Hyperplane pemisah dinyatakan sebagai:

\[\boxed{ \mathbf{w}^{\top}\mathbf{x}+b=0 }\]

Untuk dua prediktor, persamaan tersebut menjadi:

\[w_1x_1+w_2x_2+b=0\]

Pada klasifikasi biner, kelas respons direpresentasikan sebagai:

\[y_i\in\{-1,+1\}\]

Aturan prediksi dinyatakan sebagai:

\[\boxed{ \hat y = \operatorname{sign} \left( \mathbf{w}^{\top}\mathbf{x}+b \right) }\]

Nilai fungsi keputusan positif menghasilkan kelas \(+1\), sedangkan nilai negatif menghasilkan kelas \(-1\).

For \(p\) predictors, the linear decision function is defined as:

\[f(\mathbf{x}) = \mathbf{w}^{\top}\mathbf{x}+b\]

where:

  • \(\mathbf{w}=(w_1,w_2,\ldots,w_p)^\top\) is the weight vector;
  • \(\mathbf{x}\) is the predictor vector;
  • \(b\) is the intercept.

The separating hyperplane is defined as:

\[\boxed{ \mathbf{w}^{\top}\mathbf{x}+b=0 }\]

For two predictors, the equation becomes:

\[w_1x_1+w_2x_2+b=0\]

In binary classification, response classes are represented as:

\[y_i\in\{-1,+1\}\]

The prediction rule is:

\[\boxed{ \hat y = \operatorname{sign} \left( \mathbf{w}^{\top}\mathbf{x}+b \right) }\]

A positive decision-function value corresponds to class \(+1\), whereas a negative value corresponds to class \(-1\).

Hard-Margin SVMHard-Margin SVM

Hard-margin SVM digunakan pada kondisi ketika kedua kelas dapat dipisahkan secara linear tanpa kesalahan.

Batas margin kanonik dinyatakan sebagai:

\[\mathbf{w}^{\top}\mathbf{x}+b=1\]

dan:

\[\mathbf{w}^{\top}\mathbf{x}+b=-1\]

Jarak antara kedua batas tersebut adalah:

\[M = \frac{2}{\|\mathbf{w}\|}\]

dengan:

\[\|\mathbf{w}\| = \sqrt{ \sum_{j=1}^{p}w_j^2 }\]

Memaksimumkan margin ekuivalen dengan meminimumkan norma kuadrat vektor bobot.

Formulasi optimasi hard-margin SVM adalah:

\[\boxed{ \min_{\mathbf{w},b} \frac{1}{2}\|\mathbf{w}\|^2 }\]

dengan kendala:

\[y_i \left( \mathbf{w}^{\top}\mathbf{x}_i+b \right) \geq1, \qquad i=1,\ldots,n\]

Kendala tersebut memastikan setiap observasi berada pada sisi hyperplane yang sesuai dengan kelasnya dan tidak melanggar batas margin.

Hard-margin SVM is used when the two classes can be linearly separated without classification errors.

The canonical margin boundaries are defined as:

\[\mathbf{w}^{\top}\mathbf{x}+b=1\]

and:

\[\mathbf{w}^{\top}\mathbf{x}+b=-1\]

The distance between these two boundaries is:

\[M = \frac{2}{\|\mathbf{w}\|}\]

where:

\[\|\mathbf{w}\| = \sqrt{ \sum_{j=1}^{p}w_j^2 }\]

Maximizing the margin is equivalent to minimizing the squared norm of the weight vector.

The hard-margin SVM optimization problem is:

\[\boxed{ \min_{\mathbf{w},b} \frac{1}{2}\|\mathbf{w}\|^2 }\]

subject to:

\[y_i \left( \mathbf{w}^{\top}\mathbf{x}_i+b \right) \geq1, \qquad i=1,\ldots,n\]

These constraints ensure that every observation lies on the appropriate side of the separating hyperplane and does not violate the margin boundaries.

Soft-Margin SVMSoft-Margin SVM

Dalam data empiris, kelas sering kali tumpang tindih sehingga tidak seluruh observasi dapat dipisahkan secara sempurna.

Soft-margin SVM memperkenalkan variabel slack \(\xi_i\) untuk memberikan toleransi terhadap pelanggaran margin.

Fungsi optimasinya menjadi:

\[\boxed{ \min_{\mathbf{w},b,\boldsymbol{\xi}} \left[ \frac{1}{2}\|\mathbf{w}\|^2 + C\sum_{i=1}^{n}\xi_i \right] }\]

dengan kendala:

\[y_i \left( \mathbf{w}^{\top}\mathbf{x}_i+b \right) \geq1-\xi_i\]

\[\xi_i\geq0\]

Parameter \(C>0\) mengatur penalti terhadap pelanggaran margin.

  • Nilai \(C\) besar memberikan penalti lebih tinggi terhadap pelanggaran margin.
  • Nilai \(C\) kecil memberikan toleransi lebih besar terhadap pelanggaran margin.

Dengan demikian, pemilihan \(C\) memengaruhi keseimbangan antara kompleksitas fungsi keputusan dan kesalahan klasifikasi.

In empirical data, classes often overlap, making perfect linear separation impossible.

Soft-margin SVM introduces slack variables \(\xi_i\) to allow violations of the margin.

The optimization problem becomes:

\[\boxed{ \min_{\mathbf{w},b,\boldsymbol{\xi}} \left[ \frac{1}{2}\|\mathbf{w}\|^2 + C\sum_{i=1}^{n}\xi_i \right] }\]

subject to:

\[y_i \left( \mathbf{w}^{\top}\mathbf{x}_i+b \right) \geq1-\xi_i\]

and:

\[\xi_i\geq0\]

The parameter \(C>0\) controls the penalty imposed on margin violations.

  • A large value of \(C\) imposes a higher penalty on margin violations.
  • A small value of \(C\) allows greater tolerance for margin violations.

Thus, the choice of \(C\) affects the balance between the complexity of the decision function and classification errors.

INTERACTIVE 03

Eksplorasi soft-marginSoft-margin exploration

Model SVM linear benar-benar dilatih pada data ilustrasi untuk setiap C; titik bergaris lingkaran adalah support vectors. Ini bukan model Wine Quality.Linear SVMs are fitted on illustrative data for each C; circled points are support vectors. These are not Wine Quality models.

Kernel dalam SVMKernels in SVM

Hyperplane linear tidak selalu mampu merepresentasikan pemisahan kelas yang mempunyai pola nonlinear.

SVM dapat menggunakan fungsi kernel untuk membentuk batas keputusan nonlinear. Secara konseptual, prediktor dipetakan ke ruang fitur melalui fungsi \(\phi(\cdot)\).

Kernel menyatakan hasil perkalian dalam ruang fitur tersebut:

\[K(\mathbf{x}_i,\mathbf{x}_j) = \phi(\mathbf{x}_i)^\top \phi(\mathbf{x}_j)\]

Pendekatan ini memungkinkan perhitungan hubungan antarobservasi dalam ruang fitur tanpa harus membentuk seluruh koordinat hasil pemetaan secara eksplisit.

Beberapa kernel yang umum digunakan adalah:

A linear hyperplane cannot always represent the separation between classes when the underlying pattern is nonlinear.

SVM can use kernel functions to construct nonlinear decision boundaries. Conceptually, predictors are mapped into a feature space using a function \(\phi(\cdot)\).

A kernel represents the inner product in that feature space:

\[K(\mathbf{x}_i,\mathbf{x}_j) = \phi(\mathbf{x}_i)^\top \phi(\mathbf{x}_j)\]

This approach makes it possible to calculate relationships between observations in the feature space without explicitly constructing all coordinates resulting from the mapping.

Several commonly used kernels are described below.

Linear KernelLinear Kernel

\[K(\mathbf{x}_i,\mathbf{x}_j) = \mathbf{x}_i^\top\mathbf{x}_j\]

\[K(\mathbf{x}_i,\mathbf{x}_j) = \mathbf{x}_i^\top\mathbf{x}_j\]

Polynomial KernelPolynomial Kernel

\[K(\mathbf{x}_i,\mathbf{x}_j) = \left( \gamma\mathbf{x}_i^\top\mathbf{x}_j+r \right)^d\]

\[K(\mathbf{x}_i,\mathbf{x}_j) = \left( \gamma\mathbf{x}_i^\top\mathbf{x}_j+r \right)^d\]

Here, \(\gamma\) controls the scaling of the inner product, \(r\) is an offset parameter, and \(d\) is the polynomial degree.

Radial Basis Function KernelRadial Basis Function Kernel

\[K(\mathbf{x}_i,\mathbf{x}_j) = \exp \left( -\gamma \|\mathbf{x}_i-\mathbf{x}_j\|^2 \right)\]

dengan \(\gamma>0\) mengendalikan karakteristik kernel RBF.

Untuk SVM berbasis kernel, fungsi keputusan klasifikasi biner dapat ditulis sebagai:

\[f(\mathbf{x}) = \sum_{i\in SV} \alpha_i y_i K(\mathbf{x}_i,\mathbf{x}) +b\]

dengan \(SV\) menyatakan himpunan indeks support vectors dan \(\alpha_i\) merupakan koefisien dual yang tidak nol pada support vectors.

Prediksi kelas diperoleh melalui:

\[\hat y = \operatorname{sign} \left( f(\mathbf{x}) \right)\]

Dengan demikian, kernel memungkinkan pembentukan batas keputusan nonlinear, sedangkan prinsip pemilihan fungsi keputusan tetap didasarkan pada optimasi margin.

Formulasi dasar SVM merupakan klasifikasi biner. Untuk respons dengan lebih dari dua kelas, beberapa pengklasifikasi biner dapat digabungkan menggunakan strategi seperti one-versus-one atau one-versus-rest.

\[K(\mathbf{x}_i,\mathbf{x}_j) = \exp \left( -\gamma \|\mathbf{x}_i-\mathbf{x}_j\|^2 \right)\]

where \(\gamma>0\) controls the characteristics of the RBF kernel.

For kernel-based SVM, the binary classification decision function can be written as:

\[f(\mathbf{x}) = \sum_{i\in SV} \alpha_i y_i K(\mathbf{x}_i,\mathbf{x}) +b\]

where \(SV\) denotes the set of support-vector indices and \(\alpha_i\) represents the nonzero dual coefficients associated with the support vectors.

The predicted class is obtained using:

\[\hat y = \operatorname{sign} \left( f(\mathbf{x}) \right)\]

Thus, kernels allow nonlinear decision boundaries to be constructed, while the underlying principle of selecting a decision function remains based on margin optimization.

The basic SVM formulation addresses binary classification. For responses containing more than two classes, multiple binary classifiers can be combined using strategies such as one-versus-one or one-versus-rest.

INTERACTIVE 04

Eksplorasi fungsi kernelKernel explorer

Grafik nilai fungsi kernel satu dimensi, dengan z = 1 untuk linear dan polynomial; RBF menggunakan selisih x − z. Bukan batas keputusan hasil fitting.One-dimensional kernel values, with z = 1 for linear and polynomial kernels; RBF uses x − z. Not a fitted decision boundary.

Support Vector Regression (SVR)Support Vector Regression (SVR)

Konsep Dasar SVRBasic Concept of SVR

Support Vector Regression merupakan pengembangan prinsip support vector untuk respons numerik.

Berbeda dari SVM klasifikasi yang membentuk batas pemisah antarkelas, SVR mencari fungsi regresi dengan mengendalikan kompleksitas model dan kesalahan prediksi.

Pada SVR, diperkenalkan parameter \(\varepsilon\) yang menentukan wilayah toleransi di sekitar fungsi regresi.

Misalkan fungsi regresi linear dinyatakan sebagai:

\[f(\mathbf{x}) = \mathbf{w}^{\top}\mathbf{x}+b\]

Wilayah toleransi dibentuk berdasarkan:

\[f(\mathbf{x})-\varepsilon \leq y \leq f(\mathbf{x})+\varepsilon\]

Wilayah tersebut dikenal sebagai epsilon-insensitive tube atau \(\varepsilon\)-tube.

SVR: epsilon-insensitive tube

Referensi gambar: Smola dan Schölkopf (2004), A Tutorial on Support Vector Regression, Figure 1.

Keterangan: Wilayah toleransi di sekitar fungsi regresi dan observasi yang berada di dalam maupun di luar epsilon-tube.

Dalam ilustrasi tersebut, fungsi regresi berada di tengah suatu daerah toleransi yang dibatasi oleh:

\[f(\mathbf{x}) + \varepsilon\]

dan

\[f(\mathbf{x}) - \varepsilon\]

Observasi yang berada di dalam atau tepat pada batas tube tidak dikenai penalti berdasarkan fungsi epsilon-insensitive loss. Sebaliknya, observasi yang berada di luar tube menghasilkan penalti sesuai besarnya pelanggaran.

Support Vector Regression extends support vector principles to numerical responses.

Unlike SVM classification, which constructs a boundary between classes, SVR seeks a regression function while controlling model complexity and prediction errors.

SVR introduces a parameter \(\varepsilon\) that defines a tolerance region around the regression function.

Suppose a linear regression function is defined as:

\[f(\mathbf{x}) = \mathbf{w}^{\top}\mathbf{x}+b\]

The tolerance region is defined by:

\[f(\mathbf{x})-\varepsilon \leq y \leq f(\mathbf{x})+\varepsilon\]

This region is known as the epsilon-insensitive tube, or \(\varepsilon\)-tube.

SVR: epsilon-insensitive tube

Figure reference: Smola and Schölkopf (2004), A Tutorial on Support Vector Regression, Figure 1.

Description: Tolerance region around a regression function, showing observations located inside and outside the epsilon-tube.

In the illustration, the regression function lies at the center of a tolerance region bounded by:

\[f(\mathbf{x})+\varepsilon\]

and:

\[f(\mathbf{x})-\varepsilon\]

Observations located inside or exactly on the boundaries of the tube receive no penalty under the epsilon-insensitive loss function. In contrast, observations outside the tube incur a penalty according to the magnitude of their violations.

Epsilon-Insensitive LossEpsilon-Insensitive Loss

Fungsi kerugian SVR dinyatakan sebagai:

\[\boxed{ L_{\varepsilon} \left( y_i,f(\mathbf{x}_i) \right) = \max \left( 0, |y_i-f(\mathbf{x}_i)|-\varepsilon \right) }\]

Misalkan nilai prediksi adalah 100 dengan parameter \(\varepsilon=5\).

Nilai aktual Kesalahan absolut Epsilon-insensitive loss
102 2 0
105 5 0
108 8 3
112 12 7

Contoh tersebut memperlihatkan bahwa SVR tidak memberikan penalti terhadap seluruh kesalahan prediksi. Penalti baru muncul ketika kesalahan absolut melebihi nilai \(\varepsilon\).

The SVR loss function is defined as:

\[\boxed{ L_{\varepsilon} \left( y_i,f(\mathbf{x}_i) \right) = \max \left( 0, |y_i-f(\mathbf{x}_i)|-\varepsilon \right) }\]

Suppose the predicted value is 100 and the parameter is \(\varepsilon=5\).

Actual Value Absolute Error Epsilon-Insensitive Loss
102 2 0
105 5 0
108 8 3
112 12 7

This example shows that SVR does not penalize every prediction error. A penalty is incurred only when the absolute error exceeds \(\varepsilon\).

INTERACTIVE 05

Laboratorium epsilon-insensitive lossEpsilon-insensitive loss laboratory

Prediksi tetap 100. Hanya kesalahan di luar toleransi yang dikenai loss.Prediction is fixed at 100. Only error outside the tolerance incurs loss.

Formulasi Optimasi SVRSVR Optimization Formulation

Untuk mengakomodasi observasi yang berada di luar epsilon-tube, digunakan variabel slack \(\xi_i\) dan \(\xi_i^*\).

Fungsi optimasi epsilon-SVR dinyatakan sebagai:

\[\boxed{ \min_{ \mathbf{w},b, \boldsymbol{\xi}, \boldsymbol{\xi}^{*} } \left[ \frac{1}{2}\|\mathbf{w}\|^2 + C\sum_{i=1}^{n} (\xi_i+\xi_i^*) \right] }\]

dengan kendala:

\[y_i-f(\mathbf{x}_i) \leq \varepsilon+\xi_i\]

\[f(\mathbf{x}_i)-y_i \leq \varepsilon+\xi_i^*\]

\[\xi_i,\xi_i^*\geq0\]

Pada formulasi tersebut:

  • \(\frac12\|\mathbf{w}\|^2\) mengendalikan kompleksitas fungsi regresi;
  • \(C\) menentukan penalti kesalahan di luar epsilon-tube;
  • \(\varepsilon\) menentukan lebar wilayah toleransi;
  • \(\xi_i\) dan \(\xi_i^*\) menyatakan besarnya pelanggaran pada kedua sisi tube.

Observasi yang berada di luar tube dapat berperan sebagai support vectors. Observasi pada batas tube juga dapat menjadi support vectors, sedangkan observasi yang berada secara ketat di dalam tube umumnya tidak mempunyai kontribusi koefisien dual terhadap fungsi prediksi.

To accommodate observations located outside the epsilon-tube, SVR introduces slack variables \(\xi_i\) and \(\xi_i^*\).

The epsilon-SVR optimization problem is defined as:

\[\boxed{ \min_{ \mathbf{w},b, \boldsymbol{\xi}, \boldsymbol{\xi}^{*} } \left[ \frac{1}{2}\|\mathbf{w}\|^2 + C\sum_{i=1}^{n} (\xi_i+\xi_i^*) \right] }\]

subject to:

\[y_i-f(\mathbf{x}_i) \leq \varepsilon+\xi_i\]

\[f(\mathbf{x}_i)-y_i \leq \varepsilon+\xi_i^*\]

\[\xi_i,\xi_i^*\geq0\]

In this formulation:

  • \(\frac{1}{2}\|\mathbf{w}\|^2\) controls the complexity of the regression function;
  • \(C\) determines the penalty for errors outside the epsilon-tube;
  • \(\varepsilon\) determines the width of the tolerance region on either side of the regression function;
  • \(\xi_i\) and \(\xi_i^*\) represent violations on the two sides of the tube.

Observations located outside the tube may act as support vectors. Observations on the tube boundaries may also become support vectors, whereas observations strictly inside the tube generally have no dual-coefficient contribution to the prediction function.

Kernel dalam SVRKernels in SVR

SVR dapat menggunakan fungsi kernel untuk membentuk hubungan nonlinear.

Fungsi prediksinya dinyatakan sebagai:

\[\boxed{ f(\mathbf{x}) = \sum_{i\in SV} (\alpha_i-\alpha_i^*) K(\mathbf{x}_i,\mathbf{x}) +b }\]

dengan \(\alpha_i\) dan \(\alpha_i^*\) merupakan koefisien dual dari formulasi optimasi SVR.

Kernel yang digunakan dapat berupa linear, polynomial, maupun RBF.

Dengan demikian, SVM klasifikasi dan SVR memiliki dasar optimasi dan penggunaan kernel yang berkaitan, tetapi berbeda dalam bentuk fungsi kerugian dan tujuan prediksinya.

SVR can use kernel functions to represent nonlinear relationships.

Its prediction function is defined as:

\[\boxed{ f(\mathbf{x}) = \sum_{i\in SV} (\alpha_i-\alpha_i^*) K(\mathbf{x}_i,\mathbf{x}) +b }\]

where \(\alpha_i\) and \(\alpha_i^*\) are dual coefficients from the SVR optimization formulation.

The kernel can be linear, polynomial, or RBF.

Therefore, SVM classification and SVR share related optimization principles and kernel-based representations. However, they differ in their loss functions and prediction objectives.

Representasi prediktorPredictor representation

Pengaruh Skala PrediktorEffect of Predictor Scales

KNN dan SVM dapat dipengaruhi oleh skala prediktor.

Pada KNN, ukuran jarak ditentukan oleh selisih nilai setiap prediktor. Prediktor dengan rentang yang lebih besar dapat memberikan kontribusi dominan terhadap jarak Euclidean.

Pada SVM, perbedaan skala memengaruhi geometri ruang fitur, optimasi margin, serta hasil perhitungan kernel tertentu.

Standardisasi merupakan salah satu pendekatan untuk menyesuaikan skala prediktor:

\[z_{ij} = \frac{x_{ij}-\bar{x}_j}{s_j}\]

dengan \(\bar{x}_j\) dan \(s_j\) masing-masing merupakan rata-rata serta simpangan baku prediktor ke-\(j\) yang dihitung dari data latih.

Both KNN and SVM can be affected by predictor scales.

In KNN, distance measures depend on differences between predictor values. Predictors with larger numerical ranges may dominate Euclidean distance calculations.

In SVM, differences in scale affect the geometry of the feature space, margin optimization, and the calculation of certain kernel functions.

Standardization is one approach used to adjust predictor scales:

\[z_{ij} = \frac{x_{ij}-\bar{x}_j}{s_j}\]

where \(\bar{x}_j\) and \(s_j\) are the mean and standard deviation of the \(j\)-th predictor, respectively, calculated from the training data.

INTERACTIVE 06

Pengaruh standardisasi pada tetanggaEffect of scaling on neighbors

Contoh ilustratif: prediktor pertama memiliki skala lebih besar. Rata-rata dan simpangan baku dihitung hanya dari titik latih.Illustrative example: the first predictor has a larger scale. Means and standard deviations are calculated from training points only.

Prediktor KategorikCategorical Predictors

KNN dan SVM umumnya memerlukan representasi numerik untuk menghitung jarak atau fungsi kernel.

Prediktor kategorik nominal dapat direpresentasikan melalui pengodean indikator, misalnya:

\[D_k = I(X=c_k)\]

dengan \(c_k\) merupakan kategori ke-\(k\).

Namun, pengodean kategorik juga memengaruhi representasi geometris data. Pada KNN, perubahan pengodean dapat mengubah jarak antarobservasi. Pada SVM, perubahan tersebut dapat memengaruhi bentuk fungsi keputusan.

Oleh karena itu, representasi prediktor perlu disesuaikan dengan karakteristik data dan prinsip algoritma.

KNN and SVM generally require numerical representations to calculate distances or kernel functions.

Nominal categorical predictors can be represented using indicator encoding, for example:

\[D_k = I(X=c_k)\]

where \(c_k\) denotes the \(k\)-th category.

However, categorical encoding also affects the geometric representation of the data. In KNN, changing the encoding may alter distances between observations. In SVM, it may affect the resulting decision function.

Therefore, predictor representations should be selected according to the characteristics of the data and the principles of the algorithm.

Curse of DimensionalityCurse of Dimensionality

Pada metode berbasis jarak, peningkatan jumlah prediktor dapat menyebabkan observasi menjadi relatif berjauhan dalam ruang fitur.

Kondisi ini dikenal sebagai curse of dimensionality.

Ketika jumlah prediktor meningkat, perbedaan antara jarak observasi terdekat dan terjauh dapat menjadi kurang informatif. Akibatnya, konsep kedekatan lokal yang digunakan KNN dapat kehilangan sebagian kegunaannya.

Pada SVM, penambahan fitur juga dapat memengaruhi kompleksitas model, meskipun pengaruhnya bergantung pada kernel dan regularisasi yang digunakan.

In distance-based methods, increasing the number of predictors may cause observations to become relatively farther apart in the feature space.

This phenomenon is known as the curse of dimensionality.

As the number of predictors increases, the difference between distances to the nearest and farthest observations may become less informative. Consequently, the local proximity concept used in KNN may lose some of its usefulness.

In SVM, adding features can also affect model complexity, although the effects depend on the kernel and regularization being used.

Validitas PembelajaranLearning Validity

Seluruh transformasi yang memerlukan estimasi parameter harus didasarkan pada data latih. Informasi dari data uji tidak boleh digunakan untuk menentukan parameter transformasi maupun membentuk model.

Prinsip tersebut diperlukan agar evaluasi prediksi mencerminkan kemampuan model pada observasi yang tidak digunakan dalam proses pembelajaran.

All transformations requiring parameter estimation must be based on the training data. Information from the test data must not be used to determine transformation parameters or construct the model.

This principle is necessary to ensure that predictive evaluation reflects the model’s performance on observations that were not used during learning.

Persiapan packagePackage preparation

Praktikum ini menggunakan beberapa package R untuk pengolahan data, penerapan algoritma K-Nearest Neighbors (KNN) dan Support Vector Machine (SVM), serta evaluasi hasil prediksi. Package yang digunakan dipilih berdasarkan kebutuhan masing-masing tahap analisis, mulai dari penyiapan data hingga pemeriksaan kinerja model.

This practical session uses several R packages for data processing, the application of K-Nearest Neighbors (KNN) and Support Vector Machine (SVM) algorithms, and the evaluation of prediction results.

The packages are selected according to the requirements of each analytical stage, from data preparation to model performance assessment.

The KNN model achieved an accuracy of 0.7465 and a balanced accuracy of 0.7099 on the test set. The confusion matrix shows that 570 Good observations and 225 Not Good observations were correctly classified. However, 173 Not Good observations were incorrectly predicted as Good, while 97 Good observations were predicted as Not Good.

The sensitivity of 0.8546 indicates that the model correctly identified 85.46% of Good observations, whereas the specificity of 0.5653 indicates that only 56.53% of Not Good observations were correctly identified. Thus, the model performed better at recognizing Good wines than Not Good wines. The precision of 0.7672 and F1-score of 0.8085 further describe its performance for the Good class. This difference in class-specific performance remains important despite the relatively higher overall accuracy.

Package yang DigunakanRequired Packages

Praktikum ini menggunakan tidyverse untuk pengolahan dan visualisasi, tidymodels (rsample) untuk pembagian data, caret untuk validasi silang dan pelatihan, kernlab untuk kernel RBF, dan knitr untuk tabel. kknn dan e1071 juga dimuat agar kode persiapan konsisten; model utama tidak memanggil fungsi kknn() atau svm() secara langsung.

This practicum uses tidyverse for data processing and plots, tidymodels (rsample) for splitting, caret for cross-validation and training, kernlab for the RBF kernel, and knitr for tables. kknn and e1071 are also loaded for consistency; the main models do not call kknn() or svm() directly.

Instalasi PackagePackage Installation

Instalasi package hanya perlu dilakukan satu kali pada komputer yang digunakan. Jika package sudah tersedia, tahap instalasi dapat dilewati.

R
# Menginstal package yang diperlukan
install.packages(c(
  "tidyverse",
  "tidymodels",
  "kknn",
  "e1071",
  "knitr",
  "caret",
  "kernlab"
))

Jalankan blok ini sebelum melanjutkan. Tidak semua perintah mencetak hasil ke Console.

Kode instalasi di atas tidak dijalankan secara otomatis ketika dokumen Quarto dirender. Jika diperlukan, jalankan perintah instalasi secara langsung melalui Console R.

Packages only need to be installed once on the computer being used. If the required packages are already available, the installation step can be skipped.

R
# Install the required packages
install.packages(c(
  "tidyverse",
  "tidymodels",
  "kknn",
  "e1071",
  "knitr",
  "caret",
  "kernlab"
))

Run this block before continuing. Not every command prints a console result.

The installation code above is not executed automatically when the Quarto document is rendered. If necessary, run the installation commands directly in the R Console.

Memanggil PackageLoading Packages

Setelah instalasi selesai, package dipanggil menggunakan fungsi library() agar fungsi-fungsi yang diperlukan tersedia selama praktikum.

R
# Package untuk pengolahan dan visualisasi data
library(tidyverse)
OUTPUT R
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.2.1     ✔ readr     2.2.0
✔ forcats   1.0.1     ✔ stringr   1.6.0
✔ ggplot2   4.0.3     ✔ tibble    3.3.1
✔ lubridate 1.9.5     ✔ tidyr     1.3.2
✔ purrr     1.2.2     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors

After installation, the packages are loaded using the library() function so that the required functions are available throughout the practical session.

R
# Packages for data processing and visualization
library(tidyverse)
R OUTPUT
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.2.1     ✔ readr     2.2.0
## ✔ forcats   1.0.1     ✔ stringr   1.6.0
## ✔ ggplot2   4.0.3     ✔ tibble    3.3.1
## ✔ lubridate 1.9.5     ✔ tidyr     1.3.2
## ✔ purrr     1.2.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors

Penggunaan Package pada Setiap MetodePackage Usage by Method

Kedua tugas KNN menggunakan caret::train(method = "knn"). SVM Classification dan SVR menggunakan caret::train(method = "svmRadial"), dengan kernlab sebagai engine. Gunakan predict() untuk data uji; respons klasifikasi adalah faktor, sedangkan respons regresi tetap numerik. Kernel linear dan polynomial serta Weighted KNN dibahas sebagai konsep, bukan hasil eksperimen ini.

Both KNN tasks use caret::train(method = "knn"). SVM Classification and SVR use caret::train(method = "svmRadial"), with kernlab as the engine. Use predict() on the test set; classification responses are factors and regression responses are numeric. Linear and polynomial kernels and weighted KNN are conceptual extensions, not fitted models in this experiment.

Catatan PenggunaanNotes on Package Usage

Seluruh proses preprocessing yang memerlukan estimasi parameter, seperti standardisasi menggunakan rata-rata dan simpangan baku, dilakukan berdasarkan data latih. Parameter yang diperoleh kemudian diterapkan pada data uji. # H. Implementasi KNN dan SVM

All preprocessing procedures that require parameter estimation, such as standardization using means and standard deviations, must be performed based on the training data.

The resulting parameters are then applied to the test data. # H. Implementation of KNN and SVM

Deskripsi dataData understanding

Data yang digunakan pada praktikum ini adalah Wine Quality, yang memuat karakteristik fisikokimia dan hasil penilaian kualitas anggur Vinho Verde dari Portugal. Dataset ini diperkenalkan oleh Cortez et al. (2009) untuk mempelajari hubungan antara karakteristik fisikokimia anggur dan penilaian kualitas berdasarkan evaluasi sensorik.

Data terdiri atas dua jenis anggur, yaitu anggur merah (red wine) dan anggur putih (white wine). Pengukuran fisikokimia digunakan sebagai variabel prediktor, sedangkan skor kualitas (quality) digunakan sebagai variabel respons. Karakteristik tersebut memungkinkan data dipelajari melalui pendekatan klasifikasi maupun regresi.

Sumber data: UCI Machine Learning Repository – Wine Quality.

The dataset used in this practical session is Wine Quality, which contains physicochemical characteristics and quality assessments of Portuguese Vinho Verde wines. The dataset was introduced by Cortez et al. (2009) to investigate the relationship between wine physicochemical properties and quality ratings obtained through sensory evaluation.

The dataset includes two types of wine: red wine and white wine. Physicochemical measurements serve as predictor variables, while the quality score (quality) serves as the response variable. These characteristics allow the dataset to be examined using both classification and regression approaches.

Data source: UCI Machine Learning Repository – Wine Quality.

Identifikasi Struktur DataIdentifying the Data Structure

Simpan CSV di folder project RStudio dengan nama persis seperti kode. Dataset UCI terdiri atas dua file asli; untuk mengikuti hasil di sini gunakan berkas gabungan yang dipakai di kelas, dengan kolom type dan nama prediktor yang sama. Periksa dimensi dan nama sebelum menjalankan chunk berikutnya.Save the CSV in the RStudio project using the exact filename in the code. UCI provides two original files; to reproduce these results use the combined classroom file, with type and matching predictor names. Check dimensions and names before continuing.

Sebelum melakukan pemodelan, struktur data perlu diperiksa untuk mengetahui jumlah observasi, banyaknya variabel, tipe data, dan bentuk nilai yang tersimpan pada setiap kolom.

Pemeriksaan awal dilakukan dengan membaca berkas CSV dan menampilkan beberapa observasi pertama.

R
stopifnot(file.exists("wine-quality-white-and-red.csv"))
# Membaca data
wine_data <- read_csv("wine-quality-white-and-red.csv",
                      show_col_types = FALSE)

# Menampilkan enam observasi pertama
head(wine_data)
OUTPUT R
typefixed acidityvolatile aciditycitric acidresidual sugarchloridesfree sulfur dioxidetotal sulfur dioxidedensitypHsulphatesalcoholquality
white7.00.270.3620.70.045451701.00103.000.458.86
white6.30.300.341.60.049141320.99403.300.499.56
white8.10.280.406.90.05030970.99513.260.4410.16
white7.20.230.328.50.058471860.99563.190.409.96
white7.20.230.328.50.058471860.99563.190.409.96
white8.10.280.406.90.05030970.99513.260.4410.16

Selanjutnya, dimensi, nama variabel, dan struktur data diperiksa menggunakan fungsi dim(), names(), dan glimpse().

R
# Memeriksa dimensi data
dim(wine_data)
OUTPUT R
[1] 6497   13

Fungsi dim() memberikan informasi mengenai jumlah baris dan kolom, sedangkan names() menampilkan nama seluruh variabel. Fungsi glimpse() digunakan untuk melihat tipe data dan contoh nilai pada setiap variabel sehingga dapat diketahui variabel yang bersifat numerik maupun kategorik.

Berdasarkan pemeriksaan struktur data, diperoleh 6.497 observasi dengan 13 variabel. Variabel type tersimpan sebagai data karakter (chr) yang menunjukkan jenis anggur, sedangkan sebelas variabel fisikokimia tersimpan sebagai data numerik (dbl). Variabel quality juga terbaca sebagai numerik, tetapi nilainya merupakan skor penilaian kualitas yang memiliki urutan tertentu sehingga secara konseptual bersifat ordinal.

Beberapa nama variabel masih menggunakan spasi, seperti fixed acidity, volatile acidity, dan residual sugar. Penamaan tersebut perlu diperhatikan ketika variabel dipanggil dalam sintaks R. Penyesuaian nama variabel akan dilakukan pada tahap persiapan data agar lebih mudah digunakan selama pemodelan.

Before fitting the models, the data structure must be examined to determine the number of observations, number of variables, data types, and the values stored in each column.

The initial inspection begins by importing the CSV file and displaying the first few observations.

R
stopifnot(file.exists("wine-quality-white-and-red.csv"))
# Import the dataset
wine_data <- read_csv("wine-quality-white-and-red.csv",
                      show_col_types = FALSE)

# Display the first six observations
head(wine_data)
R OUTPUT
## # A tibble: 6 × 13
##   type  `fixed acidity` `volatile acidity` `citric acid` `residual sugar`
##   <chr>           <dbl>              <dbl>         <dbl>            <dbl>
## 1 white             7                 0.27          0.36             20.7
## 2 white             6.3               0.3           0.34              1.6
## 3 white             8.1               0.28          0.4               6.9
## 4 white             7.2               0.23          0.32              8.5
## 5 white             7.2               0.23          0.32              8.5
## 6 white             8.1               0.28          0.4               6.9
## # ℹ 8 more variables: chlorides <dbl>, `free sulfur dioxide` <dbl>,
## #   `total sulfur dioxide` <dbl>, density <dbl>, pH <dbl>, sulphates <dbl>,
## #   alcohol <dbl>, quality <dbl>

Next, the dataset dimensions, variable names, and structure are examined using dim(), names(), and glimpse().

R
# Check the dataset dimensions
dim(wine_data)
R OUTPUT
## [1] 6497   13

The dim() function provides the number of rows and columns, while names() displays the names of all variables. The glimpse() function shows the data types and sample values for each variable, allowing numerical and categorical variables to be identified.

The data structure inspection shows that the dataset contains 6,497 observations and 13 variables. The type variable is stored as character data (chr) and identifies the wine type, while the eleven physicochemical variables are stored as numerical data (dbl). The quality variable is also stored numerically, but its values represent ordered quality ratings and are therefore ordinal in nature.

Several variable names still contain spaces, including fixed acidity, volatile acidity, and residual sugar. This naming convention needs to be considered when referencing variables in R. The variable names will be adjusted during data preparation to simplify their use in modeling.

Statistik DeskriptifDescriptive Statistics

Statistik deskriptif digunakan untuk memberikan gambaran awal mengenai karakteristik prediktor numerik. Pemeriksaan dilakukan terhadap nilai minimum, kuartil pertama, median, rata-rata, simpangan baku, kuartil ketiga, dan nilai maksimum.

Ukuran pemusatan dan penyebaran tersebut dapat membantu mengidentifikasi perbedaan rentang nilai antarvariabel serta melihat indikasi distribusi yang tidak simetris. Informasi ini diperlukan karena representasi dan skala prediktor dapat memengaruhi proses pemodelan KNN dan SVM.

Statistik deskriptif dihitung untuk sebelas variabel fisikokimia, sedangkan variabel quality akan diperiksa secara terpisah melalui distribusi skor kualitas.

R
# Statistik deskriptif prediktor numerik
ringkasan_numerik <- wine_data %>%
  select(-type, -quality) %>%
  pivot_longer(
    cols = everything(),
    names_to = "variabel",
    values_to = "nilai"
  ) %>%
  group_by(variabel) %>%
  summarise(
    minimum = min(nilai, na.rm = TRUE),
    kuartil_1 = quantile(nilai, 0.25, na.rm = TRUE),
    median = median(nilai, na.rm = TRUE),
    rata_rata = mean(nilai, na.rm = TRUE),
    simpangan_baku = sd(nilai, na.rm = TRUE),
    kuartil_3 = quantile(nilai, 0.75, na.rm = TRUE),
    maksimum = max(nilai, na.rm = TRUE),
    .groups = "drop"
  )

knitr::kable(
  ringkasan_numerik,
  digits = 4,
  caption = "Statistik deskriptif variabel fisikokimia"
)
OUTPUT R
Statistik deskriptif variabel fisikokimia
variabel minimum kuartil_1 median rata_rata simpangan_baku kuartil_3 maksimum
alcohol 8.0000 9.5000 10.3000 10.4918 1.1927 11.300 14.900
chlorides 0.0090 0.0380 0.0470 0.0560 0.0350 0.065 0.611
citric acid 0.0000 0.2500 0.3100 0.3186 0.1453 0.390 1.660
density 0.9871 0.9923 0.9949 0.9947 0.0030 0.997 1.039
fixed acidity 3.8000 6.4000 7.0000 7.2153 1.2964 7.700 15.900
free sulfur dioxide 1.0000 17.0000 29.0000 30.5253 17.7494 41.000 289.000
pH 2.7200 3.1100 3.2100 3.2185 0.1608 3.320 4.010
residual sugar 0.6000 1.8000 3.0000 5.4432 4.7578 8.100 65.800
sulphates 0.2200 0.4300 0.5100 0.5313 0.1488 0.600 2.000
total sulfur dioxide 6.0000 77.0000 118.0000 115.7446 56.5219 156.000 440.000
volatile acidity 0.0800 0.2300 0.2900 0.3397 0.1646 0.400 1.580

Statistik deskriptif menunjukkan adanya perbedaan skala yang cukup besar antarvariabel fisikokimia. Sebagai contoh, total sulfur dioxide memiliki rentang 6–440, sedangkan density hanya berkisar antara 0,9871–1,0390. Perbedaan ini perlu diperhatikan karena prediktor dengan skala lebih besar dapat mendominasi perhitungan jarak pada KNN maupun kernel berbasis jarak pada SVM. Oleh karena itu, standardisasi prediktor diperlukan agar kontribusi setiap variabel terhadap perhitungan jarak tidak semata-mata ditentukan oleh satuan pengukurannya.

Beberapa variabel juga menunjukkan indikasi distribusi menceng ke kanan. Pada residual sugar, rata-rata sebesar 5,4432 lebih tinggi daripada median 3,0000, dengan nilai maksimum 65,8000 yang jauh melampaui kuartil ketiga 8,1000. Nilai maksimum yang relatif tinggi juga ditemukan pada chlorides dan free sulfur dioxide. Kondisi ini menunjukkan perlunya pemeriksaan nilai ekstrem, tetapi nilai tersebut tidak dapat langsung dianggap sebagai kesalahan pengukuran.

Descriptive statistics provide an initial overview of the numerical predictors. The examination includes the minimum, first quartile, median, mean, standard deviation, third quartile, and maximum.

These measures of central tendency and dispersion help identify differences in numerical ranges across variables and provide indications of asymmetric distributions. This information is relevant because predictor representation and scaling can influence the modeling process in KNN and SVM.

Descriptive statistics are calculated for the eleven physicochemical variables. The quality variable will be examined separately through the distribution of quality scores.

R
# Descriptive statistics for numerical predictors
ringkasan_numerik <- wine_data %>%
  select(-type, -quality) %>%
  pivot_longer(
    cols = everything(),
    names_to = "variabel",
    values_to = "nilai"
  ) %>%
  group_by(variabel) %>%
  summarise(
    minimum = min(nilai, na.rm = TRUE),
    kuartil_1 = quantile(nilai, 0.25, na.rm = TRUE),
    median = median(nilai, na.rm = TRUE),
    rata_rata = mean(nilai, na.rm = TRUE),
    simpangan_baku = sd(nilai, na.rm = TRUE),
    kuartil_3 = quantile(nilai, 0.75, na.rm = TRUE),
    maksimum = max(nilai, na.rm = TRUE),
    .groups = "drop"
  )

knitr::kable(
  ringkasan_numerik,
  digits = 4,
  caption = "Descriptive statistics of physicochemical variables"
)
R OUTPUT
Descriptive statistics of physicochemical variables
variabel minimum kuartil_1 median rata_rata simpangan_baku kuartil_3 maksimum
alcohol 8.0000 9.5000 10.3000 10.4918 1.1927 11.300 14.900
chlorides 0.0090 0.0380 0.0470 0.0560 0.0350 0.065 0.611
citric acid 0.0000 0.2500 0.3100 0.3186 0.1453 0.390 1.660
density 0.9871 0.9923 0.9949 0.9947 0.0030 0.997 1.039
fixed acidity 3.8000 6.4000 7.0000 7.2153 1.2964 7.700 15.900
free sulfur dioxide 1.0000 17.0000 29.0000 30.5253 17.7494 41.000 289.000
pH 2.7200 3.1100 3.2100 3.2185 0.1608 3.320 4.010
residual sugar 0.6000 1.8000 3.0000 5.4432 4.7578 8.100 65.800
sulphates 0.2200 0.4300 0.5100 0.5313 0.1488 0.600 2.000
total sulfur dioxide 6.0000 77.0000 118.0000 115.7446 56.5219 156.000 440.000
volatile acidity 0.0800 0.2300 0.2900 0.3397 0.1646 0.400 1.580

The descriptive statistics reveal substantial differences in scale across the physicochemical variables. For example, total sulfur dioxide ranges from 6 to 440, whereas density ranges only from 0.9871 to 1.0390. These differences are important because predictors with larger scales may dominate distance calculations in KNN and distance-based kernels in SVM. Predictor standardization is therefore needed to prevent measurement units from disproportionately influencing the calculated distances.

Several variables also show indications of right-skewed distributions. For residual sugar, the mean of 5.4432 exceeds the median of 3.0000, while the maximum value of 65.8000 is substantially higher than the third quartile of 8.1000. Relatively high maximum values are also observed for chlorides and free sulfur dioxide. These patterns indicate the need to examine extreme observations, although such values should not automatically be considered measurement errors.

Distribusi Variabel ResponsDistribution of the Response Variable

Variabel quality merupakan skor penilaian kualitas anggur yang memiliki urutan dari kualitas lebih rendah hingga lebih tinggi. Distribusinya diperiksa untuk mengetahui frekuensi setiap skor dan melihat apakah jumlah observasi tersebar secara merata.

R
# Menghitung distribusi skor kualitas
distribusi_quality <- wine_data %>%
  count(quality) %>%
  mutate(persentase = round(n / sum(n) * 100, 2))

knitr::kable(
  distribusi_quality,
  col.names = c("Skor Kualitas", "Jumlah", "Persentase (%)"),
  caption = "Distribusi skor kualitas anggur"
)
OUTPUT R
Distribusi skor kualitas anggur
Skor Kualitas Jumlah Persentase (%)
3 30 0.46
4 216 3.32
5 2138 32.91
6 2836 43.65
7 1079 16.61
8 193 2.97
9 5 0.08

Untuk memperjelas perbedaan frekuensi antarlevel kualitas, distribusi skor ditampilkan menggunakan diagram batang.

R
# Visualisasi distribusi skor kualitas
ggplot(distribusi_quality, aes(x = factor(quality), y = n)) +
  geom_col(fill = "#27689B", width = 0.7) +
  labs(
    title = "Distribusi Skor Kualitas Anggur",
    x = "Skor Kualitas",
    y = "Jumlah Observasi"
  ) +
  theme_minimal()
OUTPUT R

Wine quality distribution

Distribusi skor kualitas menunjukkan bahwa sebagian besar observasi berada pada skor 5 (32,91%) dan 6 (43,65%), dengan proporsi gabungan sebesar 76,56%. Sebaliknya, skor 3 dan 9 hanya mencakup 0,54% dari seluruh observasi. Konsentrasi ini menunjukkan bahwa kualitas menengah lebih banyak terwakili dibandingkan kualitas yang sangat rendah atau tinggi. Pada regresi, keterbatasan observasi di kedua ujung rentang skor perlu diperhatikan karena ketepatan prediksi pada nilai yang jarang muncul belum tentu sama dengan nilai yang lebih umum.

Jika skor dikelompokkan menjadi Good (skor ≥ 6) dan Not Good (skor < 6), proporsi kedua kelas adalah sekitar 63,31% dan 36,69%. Perbedaan ini perlu diperhatikan dalam evaluasi klasifikasi, sehingga ketepatan model tidak hanya dinilai melalui accuracy, tetapi juga melalui ukuran seperti balanced accuracy dan F1-score.

The quality variable represents an ordered wine quality rating, ranging from lower to higher quality levels. Its distribution is examined to determine the frequency of each score and assess whether observations are evenly distributed across quality levels.

R
# Calculate the distribution of quality scores
distribusi_quality <- wine_data %>%
  count(quality) %>%
  mutate(persentase = round(n / sum(n) * 100, 2))

knitr::kable(
  distribusi_quality,
  col.names = c("Quality Score", "Frequency", "Percentage (%)"),
  caption = "Distribution of wine quality scores"
)
R OUTPUT
Distribution of wine quality scores
Quality Score Frequency Percentage (%)
3 30 0.46
4 216 3.32
5 2138 32.91
6 2836 43.65
7 1079 16.61
8 193 2.97
9 5 0.08

A bar chart is used to illustrate differences in frequency across quality levels.

R
# Visualize the distribution of quality scores
ggplot(distribusi_quality, aes(x = factor(quality), y = n)) +
  geom_col(fill = "#27689B", width = 0.7) +
  labs(
    title = "Distribution of Wine Quality Scores",
    x = "Quality Score",
    y = "Number of Observations"
  ) +
  theme_minimal()
R OUTPUT

Wine quality distribution

The distribution of quality scores is concentrated at scores of 5 (32.91%) and 6 (43.65%), which together account for 76.56% of observations. In contrast, scores of 3 and 9 represent only 0.54% of the dataset. This concentration indicates that moderate quality levels are more strongly represented than very low or high quality levels. In regression, the limited number of observations at both ends of the score range should be considered because predictive accuracy for rare scores may differ from that for more common scores.

When the scores are grouped into Good (score ≥ 6) and Not Good (score < 6), the class proportions are approximately 63.31% and 36.69%, respectively. This difference should be considered when evaluating classification performance. Model performance should therefore be assessed using metrics such as balanced accuracy and F1-score in addition to overall accuracy.

Pemeriksaan Kualitas DataData Quality Assessment

Pemeriksaan kualitas data dilakukan untuk mengidentifikasi nilai hilang, baris yang memiliki nilai identik, dan observasi dengan nilai numerik yang jauh dari sebagian besar data. Hasil pemeriksaan menjadi dasar untuk menentukan langkah persiapan data sebelum pemodelan.

R
# Menghitung nilai hilang pada setiap variabel
missing_wine <- wine_data %>%
  summarise(across(everything(), ~ sum(is.na(.x)))) %>%
  pivot_longer(
    cols = everything(),
    names_to = "variabel",
    values_to = "jumlah_missing"
  )

knitr::kable(
  missing_wine,
  caption = "Jumlah nilai hilang pada setiap variabel"
)
OUTPUT R
Jumlah nilai hilang pada setiap variabel
variabel jumlah_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

Selain nilai hilang, pemeriksaan dilakukan terhadap baris yang memiliki nilai sama pada seluruh variabel.

R
# Memeriksa baris identik
duplikat_wine <- tibble(
  jumlah_observasi = nrow(wine_data),
  baris_identik = sum(duplicated(wine_data)),
  baris_unik = nrow(distinct(wine_data))
)

knitr::kable(
  duplikat_wine,
  caption = "Pemeriksaan baris identik"
)
OUTPUT R
Pemeriksaan baris identik
jumlah_observasi baris_identik baris_unik
6497 1177 5320

Nilai ekstrem pada prediktor numerik diperiksa menggunakan aturan IQR. Observasi ditandai apabila nilainya berada di bawah \(Q_1 - 1{,}5 \times IQR\) atau di atas \(Q_3 + 1{,}5 \times IQR\).

R
# Mengidentifikasi nilai ekstrem dengan metode IQR
ekstrem_wine <- wine_data %>%
  select(where(is.numeric), -quality) %>%
  summarise(across(everything(), ~ {
    q1 <- quantile(.x, 0.25, na.rm = TRUE)
    q3 <- quantile(.x, 0.75, na.rm = TRUE)
    iqr <- q3 - q1

    batas_bawah <- q1 - 1.5 * iqr
    batas_atas <- q3 + 1.5 * iqr

    sum(.x < batas_bawah | .x > batas_atas, na.rm = TRUE)
  })) %>%
  pivot_longer(
    cols = everything(),
    names_to = "variabel",
    values_to = "jumlah_ekstrem"
  )

knitr::kable(
  ekstrem_wine,
  caption = "Jumlah nilai ekstrem berdasarkan aturan IQR"
)
OUTPUT R
Jumlah nilai ekstrem berdasarkan aturan IQR
variabel jumlah_ekstrem
fixed acidity 357
volatile acidity 377
citric acid 509
residual sugar 118
chlorides 286
free sulfur dioxide 62
total sulfur dioxide 10
density 3
pH 73
sulphates 191
alcohol 3

Untuk melihat sebaran data dan keberadaan nilai ekstrem pada setiap variabel fisikokimia, digunakan visualisasi boxplot. Titik yang berada di luar whisker menunjukkan pengamatan yang teridentifikasi sebagai nilai ekstrem berdasarkan aturan 1,5 × IQR.

R
wine_data %>%
  select(where(is.numeric), -quality) %>%
  pivot_longer(
    cols = everything(),
    names_to = "variabel",
    values_to = "nilai"
  ) %>%
  ggplot(aes(x = "", y = nilai)) +
  geom_boxplot(
    fill = "#2C6E9B",
    color = "#253746",
    outlier.colour = "#D94F4F",
    outlier.size = 1,
    outlier.alpha = 0.7,
    width = 0.5
  ) +
  facet_wrap(~ variabel, scales = "free_y", ncol = 4) +
  labs(
    x = NULL,
    y = "Nilai pengamatan"
  ) +
  theme_minimal(base_size = 11) +
  theme(
    axis.text.x = element_blank(),
    axis.ticks.x = element_blank(),
    strip.text = element_text(face = "bold")
  )
OUTPUT R

Physicochemical predictor boxplots

Boxplot variabel fisikokimia anggur

Data quality assessment is performed to identify missing values, identical rows, and numerical observations that differ substantially from most of the data. The findings provide a basis for determining the required preprocessing steps before modeling.

R
# Count missing values in each variable
missing_wine <- wine_data %>%
  summarise(across(everything(), ~ sum(is.na(.x)))) %>%
  pivot_longer(
    cols = everything(),
    names_to = "variabel",
    values_to = "jumlah_missing"
  )

knitr::kable(
  missing_wine,
  caption = "Number of missing values by variable"
)
R OUTPUT
Number of missing values by variable
variabel jumlah_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

In addition to missing values, rows containing identical values across all variables are examined.

R
# Check for identical rows
duplikat_wine <- tibble(
  jumlah_observasi = nrow(wine_data),
  baris_identik = sum(duplicated(wine_data)),
  baris_unik = nrow(distinct(wine_data))
)

knitr::kable(
  duplikat_wine,
  caption = "Assessment of identical rows"
)
R OUTPUT
Assessment of identical rows
jumlah_observasi baris_identik baris_unik
6497 1177 5320

Extreme values in the numerical predictors are examined using the IQR rule. Observations are flagged when their values fall below \(Q_1 - 1.5 \times IQR\) or above \(Q_3 + 1.5 \times IQR\).

R
# Identify extreme values using the IQR rule
ekstrem_wine <- wine_data %>%
  select(where(is.numeric), -quality) %>%
  summarise(across(everything(), ~ {
    q1 <- quantile(.x, 0.25, na.rm = TRUE)
    q3 <- quantile(.x, 0.75, na.rm = TRUE)
    iqr <- q3 - q1

    batas_bawah <- q1 - 1.5 * iqr
    batas_atas <- q3 + 1.5 * iqr

    sum(.x < batas_bawah | .x > batas_atas, na.rm = TRUE)
  })) %>%
  pivot_longer(
    cols = everything(),
    names_to = "variabel",
    values_to = "jumlah_ekstrem"
  )

knitr::kable(
  ekstrem_wine,
  caption = "Number of extreme values based on the IQR rule"
)
R OUTPUT
Number of extreme values based on the IQR rule
variabel jumlah_ekstrem
fixed acidity 357
volatile acidity 377
citric acid 509
residual sugar 118
chlorides 286
free sulfur dioxide 62
total sulfur dioxide 10
density 3
pH 73
sulphates 191
alcohol 3

Boxplots are used to examine the distribution of physicochemical variables and identify potential extreme values. Points beyond the whiskers represent observations identified as extreme values according to the 1.5 × IQR rule.

R
wine_data %>%
  select(where(is.numeric), -quality) %>%
  pivot_longer(
    cols = everything(),
    names_to = "variabel",
    values_to = "nilai"
  ) %>%
  ggplot(aes(x = "", y = nilai)) +
  geom_boxplot(
    fill = "#2C6E9B",
    color = "#253746",
    outlier.colour = "#D94F4F",
    outlier.size = 1,
    outlier.alpha = 0.7,
    width = 0.5
  ) +
  facet_wrap(~ variabel, scales = "free_y", ncol = 4) +
  labs(
    x = NULL,
    y = "Observed value"
  ) +
  theme_minimal(base_size = 11) +
  theme(
    axis.text.x = element_blank(),
    axis.ticks.x = element_blank(),
    strip.text = element_text(face = "bold")
  )
R OUTPUT
Boxplots of wine physicochemical variables

Boxplots of wine physicochemical variables

Persiapan dataData preparation

Penentuan Variabel ResponsDefining Response Variables

Pemodelan KNN dan SVM dilakukan untuk dua jenis permasalahan, yaitu klasifikasi dan regresi. Pada klasifikasi, skor quality dikelompokkan menjadi dua kategori, yaitu Not Good untuk skor kurang dari 6 dan Good untuk skor 6 atau lebih. Sementara itu, pada regresi, variabel respons tetap berupa skor quality dalam bentuk numerik.

R
# Membentuk variabel respons untuk klasifikasi
wine_data <- wine_data %>%
  mutate(
    quality_class = factor(
      if_else(quality >= 6, "Good", "Not Good"),
      levels = c("Not Good", "Good")
    )
  )

# Memeriksa distribusi kelas hasil pengelompokan
distribusi_kelas <- wine_data %>%
  count(quality_class, name = "frekuensi") %>%
  mutate(
    persentase = round(100 * frekuensi / sum(frekuensi), 2)
  )

knitr::kable(
  distribusi_kelas,
  caption = "Distribusi kategori kualitas anggur"
)
OUTPUT R
Distribusi kategori kualitas anggur
quality_class frekuensi persentase
Not Good 2384 36.69
Good 4113 63.31

KNN and SVM models are implemented for two types of prediction tasks: classification and regression. For classification, the quality score is grouped into two categories: Not Good for scores below 6 and Good for scores of 6 or higher. For regression, the response variable remains the original numerical quality score.

R
# Create the response variable for classification
wine_data <- wine_data %>%
  mutate(
    quality_class = factor(
      if_else(quality >= 6, "Good", "Not Good"),
      levels = c("Not Good", "Good")
    )
  )

# Examine the distribution of the resulting classes
class_distribution <- wine_data %>%
  count(quality_class, name = "frequency") %>%
  mutate(
    percentage = round(100 * frequency / sum(frequency), 2)
  )

knitr::kable(
  class_distribution,
  caption = "Distribution of wine quality categories"
)
R OUTPUT
Distribution of wine quality categories
quality_class frequency percentage
Not Good 2384 36.69
Good 4113 63.31

Penanganan Baris IdentikHandling Identical Rows

Pengamatan yang memiliki nilai identik pada seluruh variabel dihapus menggunakan fungsi distinct(). Langkah ini dilakukan sebelum pembagian data latih dan uji untuk menghindari keberadaan baris yang sama pada kedua kelompok data.

R
# Menghapus baris yang identik pada seluruh variabel
wine_clean <- wine_data %>%
  distinct()

# Membandingkan jumlah pengamatan
ringkasan_duplikat <- tibble(
  tahap = c("Sebelum penghapusan", "Setelah penghapusan"),
  jumlah_observasi = c(
    nrow(wine_data),
    nrow(wine_clean)
  )
)

knitr::kable(
  ringkasan_duplikat,
  caption = "Jumlah pengamatan sebelum dan setelah penghapusan baris identik"
)
OUTPUT R
Jumlah pengamatan sebelum dan setelah penghapusan baris identik
tahap jumlah_observasi
Sebelum penghapusan 6497
Setelah penghapusan 5320

Hasil penghapusan menunjukkan bahwa jumlah pengamatan berkurang dari 6.497 menjadi 5.320, sehingga terdapat 1.177 baris identik (18,12%) yang dihapus. Proporsi kelas Good berubah dari 63,31% menjadi 62,63%, sedangkan Not Good meningkat dari 36,69% menjadi 37,37%. Perubahan yang relatif kecil ini menunjukkan bahwa penghapusan baris identik tidak banyak mengubah komposisi kelas. Data yang telah dibersihkan selanjutnya digunakan untuk pembagian data latih dan uji.

Observations with identical values across all variables are removed using the distinct() function. This step is performed before splitting the dataset to prevent identical rows from appearing in both the training and testing sets.

R
# Remove identical rows across all variables
wine_clean <- wine_data %>%
  distinct()

# Compare the number of observations
duplicate_summary <- tibble(
  stage = c("Before removal", "After removal"),
  observations = c(
    nrow(wine_data),
    nrow(wine_clean)
  )
)

knitr::kable(
  duplicate_summary,
  caption = "Number of observations before and after removing identical rows"
)
R OUTPUT
Number of observations before and after removing identical rows
stage observations
Before removal 6497
After removal 5320

Removing identical rows reduced the dataset from 6,497 to 5,320 observations, representing 1,177 removed rows (18.12%). The proportion of Good observations decreased from 63.31% to 62.63%, while Not Good increased from 36.69% to 37.37%. These relatively small changes indicate that removing identical rows did not substantially alter the class distribution. The cleaned dataset is then used for the training and testing split.

Pembagian Data Latih dan UjiTraining and Testing Data Split

Data dibagi menjadi 80% data latih dan 20% data uji menggunakan stratified random sampling berdasarkan kategori quality_class. Pembagian berstrata dilakukan agar proporsi kedua kategori relatif terjaga pada data latih dan uji.

R
# Pembagian data secara berstrata
set.seed(123)

split_wine <- rsample::initial_split(
  wine_clean,
  prop = 0.80,
  strata = quality_class
)

# Membentuk data latih dan data uji
wine_train <- rsample::training(split_wine)
wine_test  <- rsample::testing(split_wine)

# Memeriksa jumlah dan proporsi kelas
ringkasan_split <- bind_rows(
  wine_train %>% mutate(kelompok = "Latih"),
  wine_test %>% mutate(kelompok = "Uji")
) %>%
  count(kelompok, quality_class, name = "frekuensi") %>%
  group_by(kelompok) %>%
  mutate(
    persentase = round(100 * frekuensi / sum(frekuensi), 2)
  ) %>%
  ungroup()

knitr::kable(
  ringkasan_split,
  caption = "Distribusi kategori kualitas pada data latih dan uji"
)
OUTPUT R
Distribusi kategori kualitas pada data latih dan uji
kelompok quality_class frekuensi persentase
Latih Not Good 1590 37.37
Latih Good 2665 62.63
Uji Not Good 398 37.37
Uji Good 667 62.63

The dataset is divided into 80% training data and 20% testing data using stratified random sampling based on quality_class. Stratification helps preserve the relative proportions of both quality categories across the training and testing sets.

R
# Perform stratified data splitting
set.seed(123)

split_wine <- rsample::initial_split(
  wine_clean,
  prop = 0.80,
  strata = quality_class
)

# Create training and testing datasets
wine_train <- rsample::training(split_wine)
wine_test  <- rsample::testing(split_wine)

# Examine class counts and proportions
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 = "Distribution of wine quality categories in training and testing data"
)
R OUTPUT
Distribution of wine quality categories in training and testing data
dataset quality_class frequency percentage
Testing Not Good 398 37.37
Testing Good 667 62.63
Training Not Good 1590 37.37
Training Good 2665 62.63

Pengolahan PrediktorPredictor Sourcing and Processing

Standardisasi manual di bawah merupakan demonstrasi. Saat melatih model gunakan x_train yang belum diskalakan dan preProcess = c("center", "scale"); caret mengestimasi transformasi dalam resampling. Gunakan x_test untuk prediksi agar model menerapkan transformasi yang telah dipelajari.Manual scaling below is a demonstration. Train on unscaled x_train with preProcess = c("center", "scale"); caret estimates the transformation during resampling. Predict using x_test so the model applies its learned transformation.

Selanjutnya, kita perlu menyiapkan prediktor untuk KNN dan SVM.

Ada dua proses utama:

  1. Pengkodean kategori: Variabel type diubah menjadi variabel numerik menggunakan dummy encoding.

  2. Standardisasi: Seluruh prediktor distandardisasi menggunakan rata-rata dan simpangan baku data latih.

Standardisasi diperlukan karena KNN menggunakan ukuran jarak, sedangkan SVM dipengaruhi oleh skala prediktor dalam pembentukan batas keputusan. Variabel dengan rentang lebih besar dapat memberikan pengaruh yang tidak proporsional apabila skala prediktor tidak diseragamkan.

Standardisasi menggunakan rumus:

\[z_{ij} = \frac{x_{ij} - \bar{x}_{j,\text{latih}}}{s_{j,\text{latih}}}\]

dengan \(\bar{x}_{j,\text{latih}}\) dan \(s_{j,\text{latih}}\) masing-masing merupakan rata-rata dan simpangan baku prediktor ke-\(j\) pada data latih. Parameter standardisasi dihitung hanya dari data latih dan diterapkan pada data uji untuk mencegah data leakage.

R
# Menyiapkan prediktor tanpa variabel respons
prediktor_train <- wine_train %>%
  select(-quality, -quality_class) %>%
  mutate(type = factor(type, levels = c("red", "white")))

prediktor_test <- wine_test %>%
  select(-quality, -quality_class) %>%
  mutate(type = factor(type, levels = c("red", "white")))

# Mengubah kategori menjadi dummy
x_train <- model.matrix(~ ., data = prediktor_train)[, -1, drop = FALSE]
x_test  <- model.matrix(~ ., data = prediktor_test)[, -1, drop = FALSE]

# Menghitung parameter standardisasi dari data latih
rata_rata_train <- colMeans(x_train)
sd_train <- apply(x_train, 2, sd)

# Memastikan tidak ada prediktor dengan simpangan baku nol
stopifnot(all(sd_train > 0))

# Standardisasi data latih dan uji
x_train_scaled <- scale(
  x_train,
  center = rata_rata_train,
  scale = sd_train
)

x_test_scaled <- scale(
  x_test,
  center = rata_rata_train,
  scale = sd_train
)

# Memeriksa hasil standardisasi
ringkasan_skala <- tibble(
  variabel = colnames(x_train),
  rata_rata_awal = round(colMeans(x_train), 3),
  sd_awal = round(apply(x_train, 2, sd), 3),
  rata_rata_standar = round(colMeans(x_train_scaled), 3),
  sd_standar = round(apply(x_train_scaled, 2, sd), 3)
)

knitr::kable(
  ringkasan_skala,
  caption = "Perbandingan skala prediktor sebelum dan setelah standardisasi pada data latih"
)
OUTPUT R
Perbandingan skala prediktor sebelum dan setelah standardisasi pada data latih
variabel rata_rata_awal sd_awal rata_rata_standar sd_standar
typewhite 0.748 0.434 0 1
fixed acidity 7.218 1.324 0 1
volatile acidity 0.344 0.168 0 1
citric acid 0.319 0.148 0 1
residual sugar 5.074 4.541 0 1
chlorides 0.056 0.036 0 1
free sulfur dioxide 30.181 17.988 0 1
total sulfur dioxide 114.371 56.846 0 1
density 0.995 0.003 0 1
pH 3.223 0.161 0 1
sulphates 0.533 0.149 0 1
alcohol 10.548 1.179 0 1

Hasil standardisasi menunjukkan bahwa seluruh prediktor pada data latih telah memiliki rata-rata 0 dan simpangan baku 1. Sebelum standardisasi, terdapat perbedaan skala yang cukup besar, misalnya simpangan baku total sulfur dioxide sebesar 56,846, sedangkan density hanya 0,003. Standardisasi membuat setiap prediktor memiliki skala yang sebanding sehingga perhitungan jarak pada KNN dan pembentukan batas keputusan pada SVM tidak didominasi oleh variabel yang memiliki skala numerik lebih besar. Namun, standardisasi tidak menghilangkan nilai ekstrem yang sebelumnya teridentifikasi.

Next, we need to prepare the predictors for KNN and SVM.

There are two main processes:

  • Categorical encoding: The variable type is converted into a numerical variable using dummy encoding.

  • Standardization: All predictors are standardized using the mean and standard deviation of the training data.

Standardization is necessary because KNN relies on distance metrics, whereas SVM is influenced by the scale of the predictors when forming decision boundaries. Variables with larger ranges can exert a disproportionate influence if the scale of the predictors is not unified.

Standardization uses the formula:

\[z_{ij} = \frac{x_{ij} - \bar{x}_{j,\text{train}}}{s_{j,\text{train}}}\]

where \(\bar{x}_{j,\text{train}}\) and \(s_{j,\text{train}}\) are the mean and standard deviation of the \(j\)-th predictor in the training data, respectively. The standardization parameters are calculated solely from the training data and applied to the test data to prevent data leakage.

R
# Prepare predictors without response variables
train_predictors <- wine_train %>%
  select(-quality, -quality_class) %>%
  mutate(type = factor(type, levels = c("red", "white")))

test_predictors <- wine_test %>%
  select(-quality, -quality_class) %>%
  mutate(type = factor(type, levels = c("red", "white")))

# Convert the categorical variable into a dummy variable
x_train <- model.matrix(~ ., data = train_predictors)[, -1, drop = FALSE]
x_test  <- model.matrix(~ ., data = test_predictors)[, -1, drop = FALSE]

# Calculate standardization parameters from training data
train_mean <- colMeans(x_train)
train_sd <- apply(x_train, 2, sd)

# Check for predictors with zero standard deviation
stopifnot(all(train_sd > 0))

# Standardize training and testing predictors
x_train_scaled <- scale(
  x_train,
  center = train_mean,
  scale = train_sd
)

x_test_scaled <- scale(
  x_test,
  center = train_mean,
  scale = train_sd
)

# Examine the standardization results
scaling_summary <- tibble(
  variable = colnames(x_train),
  original_mean = round(colMeans(x_train), 3),
  original_sd = round(apply(x_train, 2, sd), 3),
  standardized_mean = round(colMeans(x_train_scaled), 3),
  standardized_sd = round(apply(x_train_scaled, 2, sd), 3)
)

knitr::kable(
  scaling_summary,
  caption = "Comparison of predictor scales before and after standardization in training data"
)
R OUTPUT
Comparison of predictor scales before and after standardization in training data
variable original_mean original_sd standardized_mean standardized_sd
typewhite 0.748 0.434 0 1
fixed acidity 7.218 1.324 0 1
volatile acidity 0.344 0.168 0 1
citric acid 0.319 0.148 0 1
residual sugar 5.074 4.541 0 1
chlorides 0.056 0.036 0 1
free sulfur dioxide 30.181 17.988 0 1
total sulfur dioxide 114.371 56.846 0 1
density 0.995 0.003 0 1
pH 3.223 0.161 0 1
sulphates 0.533 0.149 0 1
alcohol 10.548 1.179 0 1

The standardization results show that all training predictors have a mean of 0 and a standard deviation of 1. Before standardization, predictor scales differed considerably. For example, total sulfur dioxide had a standard deviation of 56.846, whereas density had a standard deviation of only 0.003. Standardization places predictors on comparable scales, preventing variables with larger numerical scales from disproportionately influencing distance calculations in KNN and decision boundaries in SVM. However, standardization does not remove previously identified extreme values.

Implementasi KNN di RStudioKNN implementation in RStudio

KNN ClassificationKNN Classification

Jalankan tab dari kiri ke kanan. Tab pelatihan membuat objek model; tab berikutnya membaca hasil CV, menggambar performa dan memilih k. Jangan memilih k berdasarkan data uji.Run tabs from left to right. Training creates the model object; later tabs read CV results, plot performance and select k. Do not choose k using test data.

Klasifikasi menggunakan K-Nearest Neighbors (KNN) dilakukan untuk memprediksi kategori kualitas anggur (Good atau Not Good) berdasarkan karakteristik fisikokimianya. KNN menentukan kelas suatu pengamatan berdasarkan suara mayoritas dari sejumlah (k) tetangga terdekat.

Pemilihan nilai (k) merupakan tahap penting dalam pembentukan model. Nilai (k) yang terlalu kecil cenderung sensitif terhadap variasi lokal dan nilai ekstrem, sedangkan nilai (k) yang terlalu besar dapat mengurangi kemampuan model dalam mengenali pola lokal.

Pada praktikum ini, pemilihan nilai (k) dilakukan dengan ketentuan berikut:

  1. Menguji nilai (k) ganjil dari 3 sampai 25 untuk mengurangi kemungkinan hasil suara yang sama (tie) pada klasifikasi biner.
  2. Menggunakan 5-fold cross-validation pada data latih untuk mengevaluasi kinerja model.
  3. Memilih nilai (k) yang menghasilkan rata-rata balanced accuracy tertinggi.

Balanced accuracy digunakan karena jumlah pengamatan pada kedua kategori kualitas tidak sama. Metrik ini menghitung rata-rata sensitivity dan specificity, sehingga kemampuan model mengenali kedua kelas ikut diperhitungkan.

\[\text{Balanced Accuracy} = \frac{\text{Sensitivity}+\text{Specificity}}{2}\]

Selanjutnya, model KNN dibangun untuk setiap kandidat nilai (k), kemudian hasil validasi silang dibandingkan untuk menentukan nilai (k) terbaik.

R
# Fungsi evaluasi balanced accuracy
ringkasan_knn <- function(data, lev = NULL, model = NULL) {
  cm <- caret::confusionMatrix(
    data = data$pred,
    reference = data$obs,
    positive = "Good"
  )

  c(
    BalancedAccuracy = unname(cm$byClass["Balanced Accuracy"]),
    Accuracy = unname(cm$overall["Accuracy"])
  )
}

# Pengaturan validasi silang
kontrol_knn <- caret::trainControl(
  method = "cv",
  number = 5,
  summaryFunction = ringkasan_knn
)

# Pemilihan nilai k
set.seed(123)

model_knn <- caret::train(
  x = x_train,
  y = wine_train$quality_class,
  method = "knn",
  tuneGrid = data.frame(k = seq(3, 25, 2)),
  trControl = kontrol_knn,
  preProcess = c("center", "scale"),
  metric = "BalancedAccuracy"
)
OUTPUT R
Loading required package: lattice

Attaching package: 'caret'
The following object is masked from 'package:kknn':

    contr.dummy
The following objects are masked from 'package:yardstick':

    precision, recall, sensitivity, specificity
The following object is masked from 'package:rsample':

    calibration
The following object is masked from 'package:purrr':

    lift

Hasil validasi silang menunjukkan bahwa balanced accuracy KNN meningkat dari 0,6867 pada \(k=3\) hingga mencapai nilai tertinggi 0,7178 pada \(k=19\). Setelah itu, kinerja cenderung menurun hingga 0,7068 pada \(k=25\). Pola ini menunjukkan bahwa penggunaan lebih banyak tetangga awalnya membantu menghasilkan klasifikasi yang lebih baik, tetapi penambahan tetangga tidak selalu meningkatkan kinerja. Berdasarkan kandidat yang diuji, \(k=19\) dipilih sebagai nilai terbaik, dengan accuracy sebesar 0,7523 dan simpangan baku balanced accuracy antar-fold sebesar 0,0159. Selisih kinerja antarbeberapa nilai \(k\) di sekitar titik terbaik relatif kecil, sehingga hasil ini tidak menunjukkan bahwa \(k=19\) pasti lebih unggul pada setiap sampel data.

K-Nearest Neighbors (KNN) classification is used to predict wine quality categories (Good or Not Good) based on physicochemical characteristics. KNN assigns an observation to a class based on the majority vote among its (k) nearest neighbors.

Selecting an appropriate value of (k) is an important step in model development. A small (k) tends to be sensitive to local variations and extreme values, while a large (k) may reduce the model’s ability to capture local patterns.

In this practical session, the optimal value of (k) is selected using the following procedure:

  1. Evaluate odd values of (k) from 3 to 25 to reduce the possibility of voting ties in binary classification.
  2. Apply 5-fold cross-validation to the training data to assess model performance.
  3. Select the value of (k) that produces the highest mean balanced accuracy.

Balanced accuracy is used because the two wine quality categories have different numbers of observations. This metric calculates the average of sensitivity and specificity, ensuring that the model’s ability to identify both classes is considered.

\[\text{Balanced Accuracy} = \frac{\text{Sensitivity}+\text{Specificity}}{2}\]

Next, KNN models are fitted using each candidate value of (k), and their cross-validation results are compared to determine the optimal number of neighbors.

R
# Define balanced accuracy as an evaluation metric
knn_summary <- function(data, lev = NULL, model = NULL) {
  cm <- caret::confusionMatrix(
    data = data$pred,
    reference = data$obs,
    positive = "Good"
  )
  
  c(
    BalancedAccuracy = unname(cm$byClass["Balanced Accuracy"]),
    Accuracy = unname(cm$overall["Accuracy"])
  )
}

# Set up cross-validation
knn_control <- caret::trainControl(
  method = "cv",
  number = 5,
  summaryFunction = knn_summary
)

# Select the optimal k
set.seed(123)

knn_model <- caret::train(
  x = x_train,
  y = wine_train$quality_class,
  method = "knn",
  tuneGrid = data.frame(k = seq(3, 25, 2)),
  trControl = knn_control,
  preProcess = c("center", "scale"),
  metric = "BalancedAccuracy"
)
R OUTPUT
## Loading required package: lattice
## 
## Attaching package: 'caret'
## The following object is masked from 'package:kknn':
## 
##     contr.dummy
## The following objects are masked from 'package:yardstick':
## 
##     precision, recall, sensitivity, specificity
## The following object is masked from 'package:rsample':
## 
##     calibration
## The following object is masked from 'package:purrr':
## 
##     lift

Cross-validation results show that the balanced accuracy of KNN increases from 0.6867 at \(k=3\) until reaching its highest value of 0.7178 at \(k=19\). After that, performance tends to decline to 0.7068 at \(k=25\). This pattern indicates that using more neighbors initially helps produce better classifications, but adding more neighbors does not always improve performance. Based on the tested candidates, \(k=19\) is selected as the best value, with an accuracy of 0.7523 and a standard deviation of balanced accuracy across folds of 0.0159. The performance difference among several \(k\) values around the optimal point is relatively small, suggesting that these results do not imply \(k=19\) is definitely superior for every data sample.

INTERACTIVE 07

Eksplorasi hasil cross-validation KNNExplore KNN cross-validation results

Angka berasal dari tabel hasil validasi silang R. Mengubah pilihan tidak melatih ulang model.Values come from R cross-validation tables. Changing the selection does not refit models.

Evaluasi KNN ClassificationKNN classification evaluation

Model KNN dengan nilai (k) terpilih digunakan untuk memprediksi kategori kualitas anggur pada data uji. Hasil prediksi dibandingkan dengan kategori sebenarnya melalui matriks konfusi. Kinerja klasifikasi kemudian diringkas menggunakan accuracy, balanced accuracy, sensitivity, specificity, precision, dan F1-score.

  • Accuracy: Proporsi seluruh prediksi yang benar.

  • Balanced accuracy: Rata-rata kemampuan model mengenali kedua kelas.

  • Sensitivity: Proporsi anggur Good yang berhasil dikenali.

  • Specificity: Proporsi anggur Not Good yang berhasil dikenali.

  • Precision: Proporsi prediksi Good yang benar-benar termasuk Good.

  • F1-score: Rata-rata harmonik antara precision dan sensitivity.

R
# Melakukan prediksi pada data uji
prediksi_knn <- predict(
  model_knn,
  newdata = x_test
)

# Membentuk matriks konfusi
evaluasi_knn <- caret::confusionMatrix(
  data = prediksi_knn,
  reference = wine_test$quality_class,
  positive = "Good",
  mode = "everything"
)

knitr::kable(
  as.data.frame.matrix(evaluasi_knn$table),
  caption = "Matriks konfusi KNN pada data uji"
)
OUTPUT R
Matriks konfusi KNN pada data uji
Not Good Good
Not Good 225 97
Good 173 570

Gunakan x_test, bukan x_test_scaled, saat menjalankan predict(). Model yang dibangun melalui caret::train() sudah menyimpan proses standardisasi sehingga transformasi diterapkan secara otomatis pada prediktor baru. Menggunakan data yang sudah distandardisasi akan menyebabkan standardisasi dilakukan dua kali.

Hasil pengujian menunjukkan bahwa KNN menghasilkan accuracy sebesar 0,7465 dan balanced accuracy sebesar 0,7099. Berdasarkan matriks konfusi, model berhasil mengklasifikasikan 570 anggur berkualitas Good dan 225 anggur berkualitas Not Good dengan benar. Namun, sebanyak 173 pengamatan Not Good diprediksi sebagai Good, sedangkan 97 pengamatan Good diprediksi sebagai Not Good.

Nilai sensitivity sebesar 0,8546 menunjukkan bahwa model mampu mengenali 85,46% pengamatan Good, sedangkan specificity sebesar 0,5653 menunjukkan bahwa hanya 56,53% pengamatan Not Good yang berhasil dikenali. Dengan demikian, model lebih baik dalam mengidentifikasi kategori Good dibandingkan Not Good. Nilai precision sebesar 0,7672 dan F1-score sebesar 0,8085 juga menggambarkan kinerja model terhadap kelas Good. Perbedaan kemampuan mengenali kedua kelas ini perlu diperhatikan meskipun nilai accuracy keseluruhan relatif lebih tinggi.

The KNN model with the selected \(k\) value is used to predict the wine quality categories on the test data. The predicted results are compared with the actual categories through a confusion matrix. The classification performance is then summarized using accuracy, balanced accuracy, sensitivity, specificity, precision, and F1-score.

  • Accuracy: The proportion of all correct predictions.

  • Balanced accuracy: The average ability of the model to recognize both classes.

  • Sensitivity: The proportion of “Good” wine successfully recognized.

  • Specificity: The proportion of “Not Good” wine successfully recognized.

  • Precision: The proportion of “Good” predictions that actually belong to the “Good” category.

  • F1-score: The harmonic mean of precision and sensitivity.

R
# Predict wine quality categories on the test set
knn_predictions <- predict(
  knn_model,
  newdata = x_test
)

# Construct the confusion matrix
knn_evaluation <- caret::confusionMatrix(
  data = knn_predictions,
  reference = wine_test$quality_class,
  positive = "Good",
  mode = "everything"
)

knitr::kable(
  as.data.frame.matrix(knn_evaluation$table),
  caption = "KNN confusion matrix on the test set"
)
R OUTPUT
KNN confusion matrix on the test set
Not Good Good
Not Good 225 97
Good 173 570

Use x_test, not x_test_scaled, when running predict(). Models built via caret::train() already store the standardization process, so the transformation is automatically applied to new predictors. Using data that has already been standardized will cause the standardization to be performed twice.

KNN RegressionKNN Regression

Ubah tujuan prediksi dari kelas menjadi skor numerik. Gunakan RMSE CV sebagai dasar pemilihan k, bukan balanced accuracy.Switch the response from a class to a numeric score. Select k using CV RMSE, not balanced accuracy.

KNN Regression digunakan untuk memprediksi skor kualitas anggur (quality) berdasarkan karakteristik fisikokimianya. Berbeda dengan klasifikasi yang menggunakan suara mayoritas, regresi KNN menghasilkan prediksi numerik melalui rata-rata nilai respons dari (k) tetangga terdekat.

Secara matematis, prediksi KNN Regression dinyatakan sebagai:

\[\hat{y}(\mathbf{x}) = \frac{1}{k} \sum_{i \in N_k(\mathbf{x})} y_i\]

dengan:

  • ŷ(x): prediksi skor kualitas untuk pengamatan x.
  • Nₖ(x): himpunan (k) tetangga terdekat dari x.
  • (y_i): skor kualitas pengamatan tetangga ke-(i).
  • (k): jumlah tetangga yang digunakan.

Nilai (k) dipilih menggunakan 5-fold cross-validation pada data latih. Berbeda dengan klasifikasi biner, regresi tidak memerlukan nilai (k) ganjil karena prediksi dihitung menggunakan rata-rata, bukan suara mayoritas.

Pada praktikum ini, nilai (k) genap dari 2 sampai 30 dievaluasi menggunakan Root Mean Squared Error (RMSE). RMSE mengukur besarnya kesalahan prediksi dalam satuan yang sama dengan variabel respons.

\[RMSE = \sqrt{ \frac{1}{n} \sum_{i=1}^{n} (y_i-\hat{y}_i)^2 }\]

Semakin kecil RMSE, semakin dekat hasil prediksi dengan nilai aktual. Nilai (k) dengan rata-rata RMSE validasi silang terendah dipilih sebagai parameter terbaik.

R
# Pengaturan validasi silang
kontrol_knn_reg <- caret::trainControl(
  method = "cv",
  number = 5
)

# Pemilihan nilai k
set.seed(123)

model_knn_reg <- caret::train(
  x = x_train,
  y = wine_train$quality,
  method = "knn",
  tuneGrid = data.frame(k = seq(2, 30, 2)),
  trControl = kontrol_knn_reg,
  preProcess = c("center", "scale"),
  metric = "RMSE"
)

# Menampilkan hasil validasi silang
hasil_knn_reg <- model_knn_reg$results %>%
  select(k, RMSE, RMSESD, Rsquared, MAE)

knitr::kable(
  hasil_knn_reg,
  digits = 4,
  caption = "Hasil validasi silang KNN Regression"
)
OUTPUT R
Hasil validasi silang KNN Regression
k RMSE RMSESD Rsquared MAE
2 0.8133 0.0361 0.2460 0.5978
4 0.7561 0.0369 0.2886 0.5787
6 0.7367 0.0338 0.3091 0.5655
8 0.7302 0.0346 0.3158 0.5650
10 0.7281 0.0350 0.3176 0.5659
12 0.7231 0.0362 0.3257 0.5633
14 0.7229 0.0347 0.3259 0.5633
16 0.7204 0.0361 0.3308 0.5627
18 0.7192 0.0368 0.3333 0.5619
20 0.7192 0.0379 0.3338 0.5621
22 0.7197 0.0375 0.3334 0.5629
24 0.7193 0.0382 0.3346 0.5632
26 0.7206 0.0385 0.3328 0.5647
28 0.7196 0.0389 0.3353 0.5646
30 0.7195 0.0389 0.3357 0.5648

RMSE KNN Regression berdasarkan nilai k

Hasil validasi silang menunjukkan bahwa RMSE KNN Regression menurun dari 0,8133 pada \(k=2\) menjadi sekitar 0,7192 pada \(k=18\)–\(20\). Penurunan yang cukup besar pada nilai \(k\) kecil menunjukkan bahwa penggunaan lebih banyak tetangga membantu mengurangi kesalahan prediksi. Namun, mulai sekitar \(k=18\), RMSE relatif stabil sehingga penambahan tetangga tidak lagi menghasilkan perbaikan yang berarti. Berdasarkan hasil pemilihan parameter, \(k=20\) terpilih dengan RMSE 0,7192, MAE 0,5621, dan Rsquared 0,3338. Nilai RMSE pada \(k=18\) dan \(k=20\) sama setelah pembulatan empat desimal, sehingga keunggulan \(k=20\) perlu dipahami sebagai hasil pemilihan berdasarkan nilai RMSE sebelum pembulatan, bukan perbedaan kinerja yang besar.

KNN Regression is used to predict numerical wine quality scores (quality) based on physicochemical characteristics. Unlike classification, which relies on majority voting, KNN Regression produces numerical predictions by averaging the response values of the (k) nearest neighbors.

Mathematically, KNN Regression predictions are expressed as:

\[\hat{y}(\mathbf{x}) = \frac{1}{k} \sum_{i \in N_k(\mathbf{x})} y_i\]

where:

  • ŷ(x): predicted quality score for observation x.
  • Nₖ(x): set of the (k) nearest neighbors of x.
  • (y_i): observed quality score of neighbor (i).
  • (k): number of neighbors used for prediction.

The value of (k) is selected using 5-fold cross-validation on the training data. Unlike binary classification, KNN Regression does not require odd values of (k) because predictions are obtained through averaging rather than majority voting.

In this practical session, even values of (k) from 2 to 30 are evaluated using Root Mean Squared Error (RMSE). RMSE measures prediction errors in the same units as the response variable.

\[RMSE = \sqrt{ \frac{1}{n} \sum_{i=1}^{n} (y_i-\hat{y}_i)^2 }\]

A lower RMSE indicates that predictions are closer to the observed values. The value of (k) with the lowest mean cross-validation RMSE is selected as the optimal parameter.

R
# Set up cross-validation
knn_reg_control <- caret::trainControl(
  method = "cv",
  number = 5
)

# Select the optimal k
set.seed(123)

knn_reg_model <- caret::train(
  x = x_train,
  y = wine_train$quality,
  method = "knn",
  tuneGrid = data.frame(k = seq(2, 30, 2)),
  trControl = knn_reg_control,
  preProcess = c("center", "scale"),
  metric = "RMSE"
)

# Display cross-validation results
knn_reg_results <- knn_reg_model$results %>%
  select(k, RMSE, RMSESD, Rsquared, MAE)

knitr::kable(
  knn_reg_results,
  digits = 4,
  caption = "KNN Regression cross-validation results"
)
R OUTPUT
KNN Regression cross-validation results
k RMSE RMSESD Rsquared MAE
2 0.8133 0.0361 0.2460 0.5978
4 0.7561 0.0369 0.2886 0.5787
6 0.7367 0.0338 0.3091 0.5655
8 0.7302 0.0346 0.3158 0.5650
10 0.7281 0.0350 0.3176 0.5659
12 0.7231 0.0362 0.3257 0.5633
14 0.7229 0.0347 0.3259 0.5633
16 0.7204 0.0361 0.3308 0.5627
18 0.7192 0.0368 0.3333 0.5619
20 0.7192 0.0379 0.3338 0.5621
22 0.7197 0.0375 0.3334 0.5629
24 0.7193 0.0382 0.3346 0.5632
26 0.7206 0.0385 0.3328 0.5647
28 0.7196 0.0389 0.3353 0.5646
30 0.7195 0.0389 0.3357 0.5648

Cross-validation results show that the RMSE of KNN Regression decreases from 0.8133 at \(k=2\) to approximately 0.7192 at \(k=18\)–\(20\). The substantial decline at small \(k\) values indicates that using more neighbors helps reduce prediction errors. However, starting around \(k=18\), the RMSE becomes relatively stable, meaning that adding more neighbors no longer yields meaningful improvements. Based on the parameter selection results, \(k=20\) is selected with an RMSE of 0.7192, MAE of 0.5621, and R-squared of 0.3338. The RMSE values for \(k=18\) and \(k=20\) are identical after rounding to four decimal places; therefore, the advantage of \(k=20\) should be understood as a selection result based on the pre-rounded RMSE value, rather than a major difference in performance.

On the test set, KNN Regression achieved an RMSE of 0.7145 and an MAE of 0.5598. This indicates an average absolute prediction error of approximately 0.56 points on the wine quality scale, while the higher RMSE suggests that some observations have relatively large prediction errors. The Rsquared value of 0.3521 indicates a limited relationship between actual and predicted values.

The scatter plot shows that predictions are concentrated around quality scores of 5 to 7. Observations with low actual scores, particularly 3 and 4, tend to be overestimated, while observations with scores of 7 to 9 tend to be underestimated. This pattern reflects a tendency toward middle-range predictions because KNN Regression averages the response values of nearby observations. Thus, the model has not fully captured variations in wine quality scores, particularly for observations with extreme values.

Evaluasi KNN RegressionKNN regression evaluation

Model KNN Regression dengan nilai (k) terpilih digunakan untuk memprediksi skor kualitas anggur pada data uji. Kinerja model dievaluasi menggunakan RMSE, MAE, dan Rsquared. Selain itu, hubungan antara skor aktual dan hasil prediksi divisualisasikan menggunakan diagram pencar.

Pada diagram pencar, garis diagonal menunjukkan kondisi ketika hasil prediksi sama dengan nilai aktual. Semakin dekat titik pengamatan terhadap garis tersebut, semakin kecil kesalahan prediksinya.

R
# Melakukan prediksi pada data uji
prediksi_knn_reg <- predict(
  model_knn_reg,
  newdata = x_test
)

# Menghitung metrik evaluasi
hasil_evaluasi_knn_reg <- caret::postResample(
  pred = prediksi_knn_reg,
  obs = wine_test$quality
)

metrik_knn_reg <- tibble(
  metrik = names(hasil_evaluasi_knn_reg),
  nilai = round(as.numeric(hasil_evaluasi_knn_reg), 4)
)

knitr::kable(
  metrik_knn_reg,
  caption = "Kinerja KNN Regression pada data uji"
)
OUTPUT R
Kinerja KNN Regression pada data uji
metrik nilai
RMSE 0.7145
Rsquared 0.3521
MAE 0.5598

Perbandingan skor kualitas aktual dan prediksi KNN Regression

Dalam caret::postResample(), \(R^2\) dihitung sebagai kuadrat korelasi antara nilai aktual dan prediksi. Jadi, metrik ini tidak selalu identik dengan koefisien determinasi berbasis \(1-\mathrm{SSE}/\mathrm{SST}\).

Pada data uji, KNN Regression menghasilkan RMSE sebesar 0,7145 dan MAE sebesar 0,5598. Artinya, rata-rata kesalahan absolut prediksi sekitar 0,56 poin pada skala kualitas anggur, sedangkan RMSE yang lebih besar menunjukkan adanya kesalahan prediksi yang relatif tinggi pada sebagian pengamatan. Nilai Rsquared sebesar 0,3521 menunjukkan hubungan antara nilai aktual dan prediksi yang masih terbatas.

Diagram pencar memperlihatkan bahwa prediksi cenderung terkonsentrasi di sekitar skor 5 hingga 7. Pengamatan dengan skor aktual rendah, terutama 3 dan 4, cenderung diprediksi lebih tinggi, sedangkan pengamatan dengan skor 7 hingga 9 cenderung diprediksi lebih rendah. Pola ini menunjukkan kecenderungan prediksi menuju nilai tengah karena KNN Regression menggunakan rata-rata respons dari tetangga terdekat. Dengan demikian, model belum sepenuhnya mampu menangkap variasi skor kualitas, khususnya pada pengamatan dengan nilai ekstrem.

The KNN Regression model with the selected value of (k) is used to predict wine quality scores on the test set. Model performance is evaluated using RMSE, MAE, and Rsquared. The relationship between actual and predicted scores is also visualized using a scatter plot.

The diagonal line represents perfect predictions, where predicted values equal actual values. Observations closer to this line have smaller prediction errors.

R
# Predict quality scores on the test set
knn_reg_predictions <- predict(
  knn_reg_model,
  newdata = x_test
)

# Calculate evaluation metrics
knn_reg_evaluation <- caret::postResample(
  pred = knn_reg_predictions,
  obs = wine_test$quality
)

knn_reg_metrics <- tibble(
  metric = names(knn_reg_evaluation),
  value = round(as.numeric(knn_reg_evaluation), 4)
)

knitr::kable(
  knn_reg_metrics,
  caption = "KNN Regression performance on the test set"
)
R OUTPUT
KNN Regression performance on the test set
metric value
RMSE 0.7145
Rsquared 0.3521
MAE 0.5598

In caret::postResample(), \(R^2\) is calculated as the squared correlation between the actual and predicted values. Therefore, this metric is not always identical to the coefficient of determination based on \(1-\mathrm{SSE}/\mathrm{SST}\).

Implementasi SVM dan SVR di RStudioSVM and SVR implementation in RStudio

SVM ClassificationSVM Classification

Dengan data latih yang sama, gunakan kernel RBF. Sigma dan C dipilih melalui grid search; nilai terbaik ditentukan oleh balanced accuracy.With the same training data, use the RBF kernel. Sigma and C are selected by grid search; balanced accuracy determines the best pair.

Support Vector Machine (SVM) merupakan metode klasifikasi yang mencari batas keputusan (hyperplane) untuk memisahkan pengamatan dari kelas yang berbeda. SVM berusaha memperoleh batas keputusan dengan margin yang besar, yaitu jarak antara batas keputusan dan pengamatan terdekat dari masing-masing kelas. Pengamatan yang menentukan batas tersebut disebut support vectors.

Pada praktikum ini, digunakan SVM dengan kernel Radial Basis Function (RBF) untuk memungkinkan pembentukan batas keputusan nonlinier. Kernel RBF dinyatakan sebagai:

\[K(\mathbf{x}_i,\mathbf{x}_j) = \exp\left( -\sigma\|\mathbf{x}_i-\mathbf{x}_j\|^2 \right)\]

dengan:

  • K(xᵢ, xⱼ): nilai kemiripan antara dua pengamatan berdasarkan kernel RBF.
  • xᵢ dan xⱼ: vektor prediktor dari dua pengamatan.
  • (σ): parameter yang mengatur seberapa cepat kemiripan menurun ketika jarak antarpengamatan meningkat.

Kinerja SVM dipengaruhi oleh dua parameter utama, yaitu (C) dan (σ). Parameter (C) mengatur penalti kesalahan klasifikasi. Nilai (C) yang besar memberikan penalti lebih tinggi terhadap kesalahan, sedangkan nilai yang kecil memungkinkan model lebih toleran terhadap kesalahan. Sementara itu, nilai (σ) yang lebih besar membuat pengaruh setiap pengamatan semakin lokal sehingga batas keputusan dapat menjadi lebih kompleks.

Pemilihan parameter dilakukan menggunakan grid search dengan 5-fold cross-validation. Setiap kombinasi (C) dan (σ) dievaluasi berdasarkan balanced accuracy, kemudian kombinasi dengan rata-rata tertinggi dipilih untuk membangun model akhir.

R
# Fungsi evaluasi balanced accuracy
ringkasan_svm <- function(data, lev = NULL, model = NULL) {
  cm <- caret::confusionMatrix(
    data = data$pred,
    reference = data$obs,
    positive = "Good"
  )

  c(
    BalancedAccuracy = unname(cm$byClass["Balanced Accuracy"]),
    Accuracy = unname(cm$overall["Accuracy"])
  )
}

# Pengaturan validasi silang
kontrol_svm <- caret::trainControl(
  method = "cv",
  number = 5,
  summaryFunction = ringkasan_svm
)

# Menentukan kombinasi parameter
grid_svm <- expand.grid(
  sigma = c(0.02, 0.08, 0.20),
  C = c(0.1, 1, 10)
)

# Melatih dan memilih model terbaik
set.seed(123)

model_svm <- caret::train(
  x = x_train,
  y = wine_train$quality_class,
  method = "svmRadial",
  tuneGrid = grid_svm,
  trControl = kontrol_svm,
  preProcess = c("center", "scale"),
  metric = "BalancedAccuracy"
)

# Menampilkan hasil validasi silang
hasil_svm <- model_svm$results %>%
  select(sigma, C, BalancedAccuracy, BalancedAccuracySD, Accuracy)

knitr::kable(
  hasil_svm,
  digits = 4,
  caption = "Hasil validasi silang SVM Classification"
)
OUTPUT R
Hasil validasi silang SVM Classification
sigma C BalancedAccuracy BalancedAccuracySD Accuracy
0.02 0.1 0.6878 0.0152 0.7311
0.02 1.0 0.7203 0.0199 0.7506
0.02 10.0 0.7286 0.0244 0.7572
0.08 0.1 0.7111 0.0149 0.7459
0.08 1.0 0.7418 0.0206 0.7669
0.08 10.0 0.7415 0.0125 0.7645
0.20 0.1 0.6983 0.0153 0.7429
0.20 1.0 0.7451 0.0131 0.7687
0.20 10.0 0.7226 0.0063 0.7481

Balanced accuracy SVM untuk berbagai kombinasi parameter

Hasil validasi silang menunjukkan bahwa kombinasi (C=1) dan (σ = 0,20) menghasilkan balanced accuracy tertinggi, yaitu 0,7451, dengan accuracy sebesar 0,7687. Pada (C=0,1), kinerja cenderung lebih rendah untuk seluruh nilai (σ) yang diuji. Peningkatan (C) menjadi 1 memperbaiki hasil klasifikasi, tetapi peningkatan lebih lanjut menjadi 10 tidak selalu memberikan perbaikan.

Pengaruh (σ) juga bergantung pada nilai (C). Sebagai contoh, pada (C=1), balanced accuracy meningkat dari 0,7203 menjadi 0,7451 ketika (σ) dinaikkan dari 0,02 menjadi 0,20. Namun, pada (C=10), penggunaan (σ = 0,20) justru menghasilkan kinerja lebih rendah. Hal ini menunjukkan pentingnya pemilihan kedua parameter secara bersamaan. Meskipun demikian, selisih kinerja beberapa kombinasi terbaik relatif kecil dibandingkan variasi antar-fold, sehingga kombinasi terpilih merupakan yang terbaik di antara kandidat yang diuji, bukan jaminan terbaik untuk seluruh kemungkinan parameter.

Support Vector Machine (SVM) is a classification method that identifies a decision boundary (hyperplane) to separate observations from different classes. SVM aims to maximize the margin, defined as the distance between the decision boundary and the closest observations from each class. The observations that determine this boundary are called support vectors.

In this practical session, SVM with a Radial Basis Function (RBF) kernel is used to allow nonlinear decision boundaries. The RBF kernel is defined as:

\[K(\mathbf{x}_i,\mathbf{x}_j) = \exp\left( -\sigma\|\mathbf{x}_i-\mathbf{x}_j\|^2 \right)\]

where:

  • K(xᵢ, xⱼ): similarity between two observations measured using the RBF kernel.
  • xᵢ and xⱼ: predictor vectors of two observations.
  • (σ): a parameter controlling how rapidly similarity decreases as the distance between observations increases.

SVM performance is influenced by two main parameters, (C) and (σ). The parameter (C) controls the penalty for classification errors. A larger (C) imposes a stronger penalty, while a smaller (C) allows greater tolerance for classification errors. Meanwhile, a larger (σ) makes the influence of individual observations more localized, potentially producing more complex decision boundaries.

Hyperparameters are selected through grid search using 5-fold cross-validation. Each combination of (C) and (σ) is evaluated using balanced accuracy, and the combination with the highest mean value is selected for the final model.

R
# Define balanced accuracy as an evaluation metric
svm_summary <- function(data, lev = NULL, model = NULL) {
  cm <- caret::confusionMatrix(
    data = data$pred,
    reference = data$obs,
    positive = "Good"
  )

  c(
    BalancedAccuracy = unname(cm$byClass["Balanced Accuracy"]),
    Accuracy = unname(cm$overall["Accuracy"])
  )
}

# Set up cross-validation
svm_control <- caret::trainControl(
  method = "cv",
  number = 5,
  summaryFunction = svm_summary
)

# Define hyperparameter combinations
svm_grid <- expand.grid(
  sigma = c(0.02, 0.08, 0.20),
  C = c(0.1, 1, 10)
)

# Train and select the optimal model
set.seed(123)

svm_model <- caret::train(
  x = x_train,
  y = wine_train$quality_class,
  method = "svmRadial",
  tuneGrid = svm_grid,
  trControl = svm_control,
  preProcess = c("center", "scale"),
  metric = "BalancedAccuracy"
)

# Display cross-validation results
svm_results <- svm_model$results %>%
  select(sigma, C, BalancedAccuracy, BalancedAccuracySD, Accuracy)

knitr::kable(
  svm_results,
  digits = 4,
  caption = "SVM Classification cross-validation results"
)
R OUTPUT
SVM Classification cross-validation results
sigma C BalancedAccuracy BalancedAccuracySD Accuracy
0.02 0.1 0.6878 0.0152 0.7311
0.02 1.0 0.7203 0.0199 0.7506
0.02 10.0 0.7286 0.0244 0.7572
0.08 0.1 0.7111 0.0149 0.7459
0.08 1.0 0.7418 0.0206 0.7669
0.08 10.0 0.7415 0.0125 0.7645
0.20 0.1 0.6983 0.0153 0.7429
0.20 1.0 0.7451 0.0131 0.7687
0.20 10.0 0.7226 0.0063 0.7481

Cross-validation results show that the combination of (C=1) and (σ=0.20) achieved the highest balanced accuracy of 0.7451, with an accuracy of 0.7687. At (C=0.1), model performance was generally lower across all evaluated (σ) values. Increasing (C) to 1 improved classification performance, but a further increase to 10 did not consistently produce better results.

The effect of (σ) also depended on the value of (C). For example, at (C=1), balanced accuracy increased from 0.7203 to 0.7451 as (σ) increased from 0.02 to 0.20. However, at (C=10), using (σ=0.20) resulted in lower performance. This highlights the importance of selecting both parameters jointly. Nevertheless, performance differences among several leading combinations were relatively small compared with variation across folds. Therefore, the selected combination is the best among those evaluated, rather than a guarantee of global optimality.

INTERACTIVE 08

Eksplorasi kombinasi hyperparameterExplore hyperparameter combinations

Hasil aktual grid search pada data latih; bukan evaluasi pada data uji.Actual grid-search results on training data; not test-set evaluation.

Evaluasi SVM ClassificationSVM classification evaluation

Model SVM dengan parameter (C=1) dan (σ = 0,20) digunakan untuk memprediksi kategori kualitas anggur pada data uji. Hasil prediksi dibandingkan dengan kategori aktual melalui matriks konfusi. Kinerja model kemudian diukur menggunakan accuracy, balanced accuracy, sensitivity, specificity, precision, dan F1-score.

R
# Melakukan prediksi pada data uji
prediksi_svm <- predict(
  model_svm,
  newdata = x_test
)

# Membentuk matriks konfusi
evaluasi_svm <- caret::confusionMatrix(
  data = prediksi_svm,
  reference = wine_test$quality_class,
  positive = "Good",
  mode = "everything"
)

knitr::kable(
  as.data.frame.matrix(evaluasi_svm$table),
  caption = "Matriks konfusi SVM pada data uji"
)
OUTPUT R
Matriks konfusi SVM pada data uji
Not Good Good
Not Good 257 108
Good 141 559

Pada data uji, SVM menghasilkan accuracy sebesar 0,7662 dan balanced accuracy sebesar 0,7419. Berdasarkan matriks konfusi, model berhasil mengklasifikasikan 559 pengamatan Good dan 257 pengamatan Not Good dengan benar. Sementara itu, sebanyak 141 pengamatan Not Good diprediksi sebagai Good, dan 108 pengamatan Good diprediksi sebagai Not Good.

Nilai sensitivity sebesar 0,8381 menunjukkan bahwa model mampu mengenali 83,81% pengamatan Good, sedangkan specificity sebesar 0,6457 menunjukkan bahwa 64,57% pengamatan Not Good berhasil dikenali. Dengan demikian, SVM masih lebih baik dalam mengidentifikasi kelas Good, tetapi perbedaan kemampuan mengenali kedua kelas lebih kecil dibandingkan KNN Classification. Nilai precision sebesar 0,7986 dan F1-score sebesar 0,8178 juga menunjukkan bahwa prediksi terhadap kelas Good memiliki tingkat ketepatan yang cukup baik.

The SVM model with (C=1) and (σ=0.20) is used to predict wine quality categories on the test set. Predicted categories are compared with actual categories using a confusion matrix. Classification performance is then evaluated using accuracy, balanced accuracy, sensitivity, specificity, precision, and F1-score.

R
# Predict wine quality categories on the test set
svm_predictions <- predict(
  svm_model,
  newdata = x_test
)

# Construct the confusion matrix
svm_evaluation <- caret::confusionMatrix(
  data = svm_predictions,
  reference = wine_test$quality_class,
  positive = "Good",
  mode = "everything"
)

knitr::kable(
  as.data.frame.matrix(svm_evaluation$table),
  caption = "SVM confusion matrix on the test set"
)
R OUTPUT
SVM confusion matrix on the test set
Not Good Good
Not Good 257 108
Good 141 559

On the test set, SVM achieved an accuracy of 0.7662 and a balanced accuracy of 0.7419. The confusion matrix shows that 559 Good observations and 257 Not Good observations were correctly classified. Meanwhile, 141 Not Good observations were incorrectly predicted as Good, and 108 Good observations were predicted as Not Good.

The sensitivity of 0.8381 indicates that the model correctly identified 83.81% of Good observations, while the specificity of 0.6457 indicates that 64.57% of Not Good observations were correctly identified. Thus, SVM still performed better at recognizing the Good class, but the difference in class-specific performance was smaller than that observed for KNN Classification. The precision of 0.7986 and F1-score of 0.8178 also indicate reasonably good predictive performance for the Good class.

Support Vector RegressionSupport Vector Regression

SVR menggunakan skor kualitas numerik. Grid search memilih pasangan C dan sigma berdasarkan RMSE, sementara epsilon ditetapkan sebesar 0,1 dalam kode ini.SVR uses numeric quality scores. Grid search selects C and sigma using RMSE, while epsilon is fixed at 0.1 in this code.

Support Vector Regression (SVR) merupakan pengembangan SVM untuk memprediksi variabel respons numerik. Pada praktikum ini, SVR digunakan untuk memprediksi skor kualitas anggur (quality) berdasarkan karakteristik fisikokimianya.

Berbeda dengan regresi yang meminimalkan seluruh kesalahan prediksi secara langsung, SVR menggunakan konsep epsilon-insensitive loss. Melalui konsep ini, kesalahan prediksi yang berada dalam batas toleransi (ε) tidak dikenai penalti.

Fungsi kerugian tersebut dinyatakan sebagai:

\[L_{\epsilon}(y_i,\hat{y}_i) = \max\left(0,\lvert y_i-\hat{y}_i\rvert-\epsilon\right)\]

dengan:

  • (y_i): skor kualitas aktual pengamatan ke-(i).
  • ŷᵢ: skor kualitas hasil prediksi.
  • (ε): batas toleransi kesalahan prediksi.
  • Lε: besarnya kesalahan yang dikenai penalti.

Dengan demikian, SVR berusaha membentuk fungsi prediksi yang tidak terlalu kompleks sekaligus membatasi kesalahan yang melebihi toleransi tersebut.

Pada praktikum ini, digunakan SVR dengan kernel Radial Basis Function (RBF). Kinerja model dipengaruhi oleh parameter (C), yang mengatur penalti terhadap kesalahan di luar batas toleransi, dan (σ), yang mengatur karakteristik kernel RBF.

Pemilihan parameter dilakukan menggunakan grid search dengan 5-fold cross-validation. Setiap kombinasi dievaluasi berdasarkan RMSE, dan kombinasi dengan rata-rata RMSE terendah dipilih sebagai parameter terbaik. Parameter (ε) ditetapkan sebesar 0,1 selama proses pemodelan.

R
# Pengaturan validasi silang
kontrol_svr <- caret::trainControl(
  method = "cv",
  number = 5
)

# Menentukan kombinasi parameter
grid_svr <- expand.grid(
  sigma = c(0.02, 0.08, 0.20),
  C = c(0.1, 1, 10)
)

# Melatih dan memilih model SVR
set.seed(123)

model_svr <- caret::train(
  x = x_train,
  y = wine_train$quality,
  method = "svmRadial",
  tuneGrid = grid_svr,
  trControl = kontrol_svr,
  preProcess = c("center", "scale"),
  metric = "RMSE",
  epsilon = 0.1
)

# Menampilkan hasil validasi silang
hasil_svr <- model_svr$results %>%
  select(sigma, C, RMSE, RMSESD, Rsquared, MAE)

knitr::kable(
  hasil_svr,
  digits = 4,
  caption = "Hasil validasi silang Support Vector Regression"
)
OUTPUT R
Hasil validasi silang Support Vector Regression
sigma C RMSE RMSESD Rsquared MAE
0.02 0.1 0.7252 0.0440 0.3247 0.5600
0.02 1.0 0.7080 0.0447 0.3524 0.5451
0.02 10.0 0.7022 0.0459 0.3645 0.5378
0.08 0.1 0.7125 0.0424 0.3455 0.5465
0.08 1.0 0.6969 0.0402 0.3728 0.5293
0.08 10.0 0.7125 0.0314 0.3550 0.5415
0.20 0.1 0.7193 0.0373 0.3359 0.5475
0.20 1.0 0.7052 0.0335 0.3588 0.5332
0.20 10.0 0.7676 0.0303 0.2946 0.5888

RMSE SVR untuk berbagai kombinasi parameter

Hasil validasi silang menunjukkan bahwa kombinasi (C=1) dan (σ = 0,08) menghasilkan RMSE terendah sebesar 0,6969, dengan MAE 0,5293 dan Rsquared 0,3728. Pada (C=1), RMSE menurun ketika (σ) meningkat dari 0,02 menjadi 0,08, tetapi kembali meningkat pada (σ = 0,20). Sementara itu, kombinasi (C=10) dan (σ = 0,20) menghasilkan RMSE tertinggi sebesar 0,7676.

Pola tersebut menunjukkan bahwa pengaruh parameter (C) dan (σ) saling berkaitan. Penalti kesalahan yang lebih besar dan pengaruh kernel yang semakin lokal tidak selalu menghasilkan prediksi yang lebih baik. Berdasarkan kombinasi yang diuji, (C=1) dan (σ = 0,08) dipilih untuk membangun model SVR akhir, yang selanjutnya dievaluasi menggunakan data uji.

Support Vector Regression (SVR) extends SVM to predict numerical response variables. In this practical session, SVR is used to predict wine quality scores (quality) based on physicochemical characteristics.

Unlike regression approaches that directly penalize all prediction errors, SVR uses the concept of epsilon-insensitive loss. Under this approach, prediction errors within a tolerance threshold (ε) are not penalized.

The loss function is expressed as:

\[L_{\epsilon}(y_i,\hat{y}_i) = \max\left(0,\lvert y_i-\hat{y}_i\rvert-\epsilon\right)\]

where:

  • (y_i): actual quality score of observation (i).
  • ŷᵢ: predicted quality score.
  • (ε): prediction error tolerance.
  • Lε: the magnitude of the penalized prediction error.

Thus, SVR aims to construct a prediction function that balances model complexity and errors exceeding the specified tolerance.

In this practical session, SVR with a Radial Basis Function (RBF) kernel is implemented. Model performance is influenced by (C), which controls the penalty for errors outside the tolerance threshold, and (), which determines the characteristics of the RBF kernel.

Hyperparameters are selected through grid search using 5-fold cross-validation. Each parameter combination is evaluated using RMSE, and the combination with the lowest mean RMSE is selected. The parameter (ε) is fixed at 0.1 throughout model training.

R
# Set up cross-validation
svr_control <- caret::trainControl(
  method = "cv",
  number = 5
)

# Define hyperparameter combinations
svr_grid <- expand.grid(
  sigma = c(0.02, 0.08, 0.20),
  C = c(0.1, 1, 10)
)

# Train and select the optimal SVR model
set.seed(123)

svr_model <- caret::train(
  x = x_train,
  y = wine_train$quality,
  method = "svmRadial",
  tuneGrid = svr_grid,
  trControl = svr_control,
  preProcess = c("center", "scale"),
  metric = "RMSE",
  epsilon = 0.1
)

# Display cross-validation results
svr_results <- svr_model$results %>%
  select(sigma, C, RMSE, RMSESD, Rsquared, MAE)

knitr::kable(
  svr_results,
  digits = 4,
  caption = "Support Vector Regression cross-validation results"
)
R OUTPUT
Support Vector Regression cross-validation results
sigma C RMSE RMSESD Rsquared MAE
0.02 0.1 0.7252 0.0440 0.3247 0.5600
0.02 1.0 0.7080 0.0447 0.3524 0.5451
0.02 10.0 0.7022 0.0459 0.3645 0.5378
0.08 0.1 0.7125 0.0424 0.3455 0.5465
0.08 1.0 0.6969 0.0402 0.3728 0.5293
0.08 10.0 0.7125 0.0314 0.3550 0.5415
0.20 0.1 0.7193 0.0373 0.3359 0.5475
0.20 1.0 0.7052 0.0335 0.3588 0.5332
0.20 10.0 0.7676 0.0303 0.2946 0.5888

Cross-validation results show that the combination of (C=1) and (σ=0.08) achieved the lowest RMSE of 0.6969, with an MAE of 0.5293 and Rsquared of 0.3728. At (C=1), RMSE decreased as (σ) increased from 0.02 to 0.08, but increased again at (σ=0.20). Meanwhile, the combination of (C=10) and (σ=0.20) produced the highest RMSE of 0.7676.

This pattern indicates that the effects of (C) and (σ) are interrelated. Stronger penalties for prediction errors and more localized kernel effects do not necessarily improve predictive performance. Among the evaluated combinations, (C=1) and (σ=0.08) were selected for the final SVR model, which is subsequently evaluated using the test set.

Evaluasi SVRSVR evaluation

Model SVR dengan parameter (C=1) dan (σ = 0,08) digunakan untuk memprediksi skor kualitas anggur pada data uji. Hasil prediksi dievaluasi menggunakan RMSE, MAE, dan Rsquared.

Hubungan antara nilai aktual dan prediksi juga divisualisasikan menggunakan diagram pencar. Garis diagonal menunjukkan kondisi prediksi sempurna, sehingga jarak titik terhadap garis tersebut membantu menggambarkan besarnya kesalahan prediksi.

R
# Melakukan prediksi pada data uji
prediksi_svr <- predict(
  model_svr,
  newdata = x_test
)

# Menghitung metrik evaluasi
hasil_evaluasi_svr <- caret::postResample(
  pred = prediksi_svr,
  obs = wine_test$quality
)

metrik_svr <- tibble(
  metrik = names(hasil_evaluasi_svr),
  nilai = round(as.numeric(hasil_evaluasi_svr), 4)
)

knitr::kable(
  metrik_svr,
  caption = "Kinerja Support Vector Regression pada data uji"
)
OUTPUT R
Kinerja Support Vector Regression pada data uji
metrik nilai
RMSE 0.6864
Rsquared 0.3974
MAE 0.5221

Perbandingan skor kualitas aktual dan prediksi SVR

Pada data uji, SVR menghasilkan RMSE sebesar 0,6864 dan MAE sebesar 0,5221. Nilai MAE menunjukkan bahwa rata-rata kesalahan absolut prediksi sekitar 0,52 poin kualitas anggur. Sementara itu, Rsquared sebesar 0,3974 menunjukkan adanya hubungan antara skor aktual dan prediksi, meskipun kemampuan model dalam merepresentasikan variasi skor masih terbatas.

Diagram pencar menunjukkan bahwa skor kualitas rendah, terutama 3 dan 4, cenderung diprediksi lebih tinggi, sedangkan skor 8 dan 9 cenderung diprediksi lebih rendah. Sebagian besar hasil prediksi masih berada di sekitar skor 5 hingga 7. Dengan demikian, SVR belum sepenuhnya mampu memprediksi skor kualitas ekstrem secara akurat, tetapi menghasilkan kesalahan prediksi yang lebih kecil dibandingkan KNN Regression pada data uji yang sama.

The SVR model with (C=1) and (σ=0.08) is used to predict wine quality scores on the test set. Prediction performance is evaluated using RMSE, MAE, and Rsquared.

The relationship between actual and predicted values is also visualized using a scatter plot. The diagonal line represents perfect predictions, so the distance between observations and this line provides a visual indication of prediction errors.

R
# Predict quality scores on the test set
svr_predictions <- predict(
  svr_model,
  newdata = x_test
)

# Calculate evaluation metrics
svr_evaluation <- caret::postResample(
  pred = svr_predictions,
  obs = wine_test$quality
)

svr_metrics <- tibble(
  metric = names(svr_evaluation),
  value = round(as.numeric(svr_evaluation), 4)
)

knitr::kable(
  svr_metrics,
  caption = "Support Vector Regression performance on the test set"
)
R OUTPUT
Support Vector Regression performance on the test set
metric value
RMSE 0.6864
Rsquared 0.3974
MAE 0.5221

On the test set, SVR achieved an RMSE of 0.6864 and an MAE of 0.5221. The MAE indicates an average absolute prediction error of approximately 0.52 wine quality points. Meanwhile, the Rsquared value of 0.3974 indicates a relationship between actual and predicted scores, although the model’s ability to represent variations in quality scores remains limited.

The scatter plot shows that low quality scores, particularly 3 and 4, tend to be overestimated, while scores of 8 and 9 tend to be underestimated. Most predictions remain concentrated around scores of 5 to 7. Thus, SVR has not fully captured extreme quality scores accurately, but it produces smaller prediction errors than KNN Regression on the same test set.

Evaluasi dan perbandingan modelModel evaluation and comparison

Perbandingan Model KlasifikasiClassification Model Comparison

Perbandingan KNN Classification dan SVM Classification dilakukan menggunakan hasil evaluasi pada data uji yang sama. Metrik yang digunakan meliputi accuracy, balanced accuracy, sensitivity, specificity, precision, dan F1-score.

Balanced accuracy menjadi ukuran utama karena mempertimbangkan kemampuan model mengenali kedua kategori kualitas. Sensitivity dan specificity juga dibandingkan untuk melihat apakah kedua model memiliki perbedaan kemampuan dalam mengklasifikasikan anggur Good dan Not Good.

R
# Menggabungkan metrik kedua model
perbandingan_klasifikasi <- bind_rows(
  metrik_knn %>% mutate(model = "KNN"),
  metrik_svm %>% mutate(model = "SVM")
)

# Menampilkan tabel perbandingan
perbandingan_klasifikasi %>%
  pivot_wider(
    names_from = metrik,
    values_from = nilai
  ) %>%
  knitr::kable(
    digits = 4,
    caption = "Perbandingan kinerja model klasifikasi pada data uji"
  )
OUTPUT R
Perbandingan kinerja model klasifikasi pada data uji
model Accuracy Balanced Accuracy Sensitivity Specificity Precision F1-score
KNN 0.7465 0.7099 0.8546 0.5653 0.7672 0.8085
SVM 0.7662 0.7419 0.8381 0.6457 0.7986 0.8178

Perbandingan kinerja KNN dan SVM Classification

Perbandingan pada data uji menunjukkan bahwa SVM memiliki balanced accuracy sebesar 0,7419, lebih tinggi daripada KNN sebesar 0,7099. SVM juga menghasilkan accuracy, precision, dan F1-score yang lebih tinggi. Keunggulan SVM terutama terlihat pada specificity, yang meningkat dari 0,5653 pada KNN menjadi 0,6457 pada SVM. Artinya, SVM lebih mampu mengenali anggur berkualitas Not Good.

Sebaliknya, KNN memiliki sensitivity sedikit lebih tinggi, yaitu 0,8546 dibandingkan 0,8381 pada SVM, sehingga lebih banyak pengamatan Good yang berhasil dikenali. Dengan mempertimbangkan kemampuan mengenali kedua kelas secara seimbang, SVM menunjukkan kinerja yang lebih baik pada data uji ini. Namun, perbandingan tersebut bersifat deskriptif berdasarkan satu pembagian data, sehingga belum membuktikan bahwa keunggulan SVM berlaku secara konsisten pada pembagian data lainnya.

KNN Classification and SVM Classification are compared using evaluation results from the same test set. The metrics include accuracy, balanced accuracy, sensitivity, specificity, precision, and F1-score.

Balanced accuracy is the primary comparison metric because it considers the model’s ability to recognize both quality categories. Sensitivity and specificity are also compared to examine differences in identifying Good and Not Good wines.

R
# Combine evaluation metrics
classification_comparison <- bind_rows(
  knn_metrics %>% mutate(model = "KNN"),
  svm_metrics %>% mutate(model = "SVM")
)

# Display the comparison table
classification_comparison %>%
  pivot_wider(
    names_from = metric,
    values_from = value
  ) %>%
  knitr::kable(
    digits = 4,
    caption = "Classification model performance comparison on the test set"
  )
R OUTPUT
Classification model performance comparison on the test set
model Accuracy Balanced Accuracy Sensitivity Specificity Precision F1-score
KNN 0.7465 0.7099 0.8546 0.5653 0.7672 0.8085
SVM 0.7662 0.7419 0.8381 0.6457 0.7986 0.8178

The test-set comparison shows that SVM achieved a balanced accuracy of 0.7419, exceeding KNN’s 0.7099. SVM also produced higher accuracy, precision, and F1-score. Its main advantage was observed in specificity, which increased from 0.5653 for KNN to 0.6457 for SVM. This indicates that SVM was more effective at identifying Not Good wines.

Conversely, KNN achieved slightly higher sensitivity, at 0.8546 compared with 0.8381 for SVM, meaning that it correctly identified more Good observations. Considering performance across both classes, SVM demonstrated better classification performance on this test set. However, this comparison is descriptive and based on a single data split, so it does not establish that SVM would consistently outperform KNN across other splits.

Perbandingan Model RegresiRegression Model Comparison

R² pada caret::postResample() adalah kuadrat korelasi nilai aktual dan prediksi, bukan selalu sama dengan 1 − SSE/SST. Perbandingan ini bersifat deskriptif pada satu pembagian data.R² in caret::postResample() is squared correlation between observed and predicted values, not necessarily 1 − SSE/SST. This is a descriptive comparison for one data split.

Kinerja KNN Regression dan Support Vector Regression (SVR) dibandingkan menggunakan hasil prediksi pada data uji yang sama. Perbandingan dilakukan berdasarkan RMSE, MAE, dan Rsquared.

RMSE dan MAE digunakan untuk menilai besarnya kesalahan prediksi, sedangkan Rsquared menggambarkan kekuatan hubungan antara nilai aktual dan prediksi. Visualisasi difokuskan pada RMSE dan MAE karena kedua metrik tersebut dinyatakan dalam satuan skor kualitas anggur dan dapat dibandingkan secara langsung.

R
# Menggabungkan hasil evaluasi regresi
perbandingan_regresi <- bind_rows(
  metrik_knn_reg %>% mutate(model = "KNN Regression"),
  metrik_svr %>% mutate(model = "SVR")
)

# Menampilkan tabel perbandingan
perbandingan_regresi %>%
  pivot_wider(
    names_from = metrik,
    values_from = nilai
  ) %>%
  knitr::kable(
    digits = 4,
    caption = "Perbandingan kinerja model regresi pada data uji"
  )
OUTPUT R
Perbandingan kinerja model regresi pada data uji
model RMSE Rsquared MAE
KNN Regression 0.7145 0.3521 0.5598
SVR 0.6864 0.3974 0.5221

Perbandingan kesalahan prediksi KNN Regression dan SVR

Hasil perbandingan menunjukkan bahwa SVR menghasilkan RMSE sebesar 0,6864, lebih rendah daripada KNN Regression sebesar 0,7145. Nilai MAE SVR juga lebih kecil, yaitu 0,5221 dibandingkan 0,5598 pada KNN Regression. Sementara itu, Rsquared SVR sebesar 0,3974 lebih tinggi daripada KNN Regression sebesar 0,3521. Ketiga metrik tersebut menunjukkan bahwa SVR memberikan prediksi yang lebih baik pada data uji.

Meskipun demikian, kedua model masih cenderung menghasilkan prediksi yang mendekati skor kualitas tengah. Pengamatan dengan kualitas sangat rendah atau tinggi belum dapat diprediksi secara akurat. Dengan demikian, SVR merupakan model regresi terbaik di antara kedua metode yang diuji, tetapi masih memiliki keterbatasan dalam menangkap variasi skor kualitas anggur, khususnya pada nilai ekstrem.

KNN Regression and Support Vector Regression (SVR) are compared using predictions from the same test set. Model performance is evaluated based on RMSE, MAE, and Rsquared.

RMSE and MAE measure the magnitude of prediction errors, while Rsquared represents the strength of the relationship between actual and predicted values. The visualization focuses on RMSE and MAE because both metrics are expressed in wine quality score units and can be directly compared.

R
# Combine regression evaluation results
regression_comparison <- bind_rows(
  knn_reg_metrics %>% mutate(model = "KNN Regression"),
  svr_metrics %>% mutate(model = "SVR")
)

# Display the comparison table
regression_comparison %>%
  pivot_wider(
    names_from = metric,
    values_from = value
  ) %>%
  knitr::kable(
    digits = 4,
    caption = "Regression model performance comparison on the test set"
  )
R OUTPUT
Regression model performance comparison on the test set
model RMSE Rsquared MAE
KNN Regression 0.7145 0.3521 0.5598
SVR 0.6864 0.3974 0.5221

The comparison shows that SVR achieved an RMSE of 0.6864, lower than KNN Regression’s 0.7145. SVR also produced a lower MAE of 0.5221 compared with 0.5598 for KNN Regression. Meanwhile, SVR achieved a higher Rsquared value of 0.3974 compared with 0.3521 for KNN Regression. These three metrics indicate that SVR provided better predictions on the test set.

Nevertheless, both models still tended to produce predictions concentrated around middle-range quality scores. Observations with very low or high quality scores were not predicted accurately. Thus, SVR was the better regression model among the two evaluated methods, although it remained limited in capturing variations in wine quality, particularly at extreme values.

Ringkasan dan referensiSummary and references

Ringkasan MetodeSummary of Methods

KNN dan SVM merupakan dua pendekatan pembelajaran terawasi dengan mekanisme berbeda.

KNN menggunakan informasi lokal berdasarkan jarak antarobservasi. Pada klasifikasi, prediksi diperoleh melalui voting kelas tetangga, sedangkan pada regresi digunakan rata-rata respons tetangga.

SVM membentuk fungsi keputusan berdasarkan prinsip optimasi. Untuk klasifikasi, proses tersebut berkaitan dengan pemisahan kelas dan margin. Untuk regresi, SVR menggunakan wilayah toleransi epsilon untuk menentukan penalti kesalahan prediksi.

Metode Jenis Respons Prinsip Prediksi Parameter Utama
KNN Classification Kategorik Voting kelas tetangga terdekat \(K\), jarak, bobot
KNN Regression Numerik Rata-rata respons tetangga terdekat \(K\), jarak, bobot
Support Vector Classification Kategorik Fungsi keputusan berdasarkan margin \(C\), kernel, parameter kernel
Support Vector Regression Numerik Fungsi regresi dengan epsilon-insensitive loss \(C\), \(\varepsilon\), kernel, parameter kernel

Perbedaan prinsip kerja tersebut menyebabkan pemilihan metode perlu mempertimbangkan tipe respons, karakteristik prediktor, bentuk hubungan yang ingin dipelajari, dan kompleksitas model.

KNN and SVM are two supervised learning approaches with different mechanisms.

KNN uses local information based on distances between observations. In classification, predictions are obtained through voting among neighboring classes, whereas regression uses the mean response of the nearest neighbors.

SVM constructs a decision function based on optimization principles. For classification, this process involves class separation and margin optimization. For regression, SVR uses an epsilon-tolerance region to determine prediction-error penalties.

Method Response Type Prediction Principle Main Parameters
KNN Classification Categorical Voting among nearest neighbors \(K\), distance, weights
KNN Regression Numerical Mean response of nearest neighbors \(K\), distance, weights
Support Vector Classification Categorical Margin-based decision function \(C\), kernel, kernel parameters
Support Vector Regression Numerical Regression function with epsilon-insensitive loss \(C\), \(\varepsilon\), kernel, kernel parameters

These differences in learning mechanisms mean that method selection should consider the response type, predictor characteristics, the form of the relationship to be learned, and model complexity.

Ringkasan Hasil ImplementasiImplementation Summary

Penerapan KNN dan SVM pada data kualitas anggur menunjukkan bahwa pemilihan metode perlu disesuaikan dengan tujuan pemodelan. Pada klasifikasi, SVM menghasilkan balanced accuracy lebih tinggi dibandingkan KNN serta lebih baik dalam mengenali kategori Not Good, meskipun KNN memiliki sensitivity sedikit lebih tinggi untuk kategori Good. Pada regresi, SVR menghasilkan RMSE dan MAE lebih rendah dibandingkan KNN Regression, tetapi kedua metode masih memiliki keterbatasan dalam memprediksi skor kualitas yang ekstrem.

Hasil ini juga memperlihatkan pentingnya standardisasi prediktor, pemilihan parameter melalui validasi silang, dan evaluasi menggunakan data uji yang terpisah. Penilaian kinerja tidak cukup didasarkan pada satu metrik, melainkan perlu mempertimbangkan karakteristik variabel respons dan jenis kesalahan prediksi. Secara keseluruhan, SVM dengan kernel RBF menunjukkan kinerja lebih baik pada kedua tugas dalam pengujian ini, tetapi hasil tersebut belum dapat digeneralisasikan tanpa evaluasi pada pembagian atau kumpulan data lainnya.

The application of KNN and SVM to the wine quality dataset demonstrates that model selection should be aligned with the prediction task. In classification, SVM achieved higher balanced accuracy than KNN and performed better at identifying Not Good wines, although KNN showed slightly higher sensitivity for the Good category. In regression, SVR achieved lower RMSE and MAE than KNN Regression, but both approaches remained limited in predicting extreme quality scores.

These findings also highlight the importance of predictor standardization, hyperparameter selection through cross-validation, and evaluation on a separate test set. Model performance should not be judged using a single metric, but should account for the characteristics of the response variable and the types of prediction errors. Overall, SVM with an RBF kernel performed better on both tasks in this evaluation, although these results should not be generalized without further assessment across different data splits or datasets.

Daftar PustakaReferences

Cortes, C., & Vapnik, V. (1995). Support-vector networks. Machine Learning, 20(3), 273–297. https://doi.org/10.1007/BF00994018

Cortez, P., Cerdeira, A., Almeida, F., Matos, T., & Reis, J. (2009a). Modeling wine preferences by data mining from physicochemical properties. Decision Support Systems, 47(4), 547–553. https://doi.org/10.1016/j.dss.2009.05.016

Cortez, P., Cerdeira, A., Almeida, F., Matos, T., & Reis, J. (2009b). Wine Quality [Data set]. UCI Machine Learning Repository. https://doi.org/10.24432/C56S3T

Cover, T. M., & Hart, P. E. (1967). Nearest neighbor pattern classification. IEEE Transactions on Information Theory, 13(1), 21–27. https://doi.org/10.1109/TIT.1967.1053964

James, G., Witten, D., Hastie, T., & Tibshirani, R. (2021). An introduction to statistical learning: With applications in R (2nd ed.). Springer. https://doi.org/10.1007/978-1-0716-1418-1

Kuhn, M. (2008). Building predictive models in R using the caret package. Journal of Statistical Software, 28(5), 1–26. https://doi.org/10.18637/jss.v028.i05

Smola, A. J., & Schölkopf, B. (2004). A tutorial on support vector regression. Statistics and Computing, 14(3), 199–222. https://doi.org/10.1023/B:STCO.0000035301.49549.88

Wickham, H. (2016). ggplot2: Elegant graphics for data analysis. Springer. https://doi.org/10.1007/978-3-319-24277-4

Cortes, C., & Vapnik, V. (1995). Support-vector networks. Machine Learning, 20(3), 273–297. https://doi.org/10.1007/BF00994018

Cortez, P., Cerdeira, A., Almeida, F., Matos, T., & Reis, J. (2009a). Modeling wine preferences by data mining from physicochemical properties. Decision Support Systems, 47(4), 547–553. https://doi.org/10.1016/j.dss.2009.05.016

Cortez, P., Cerdeira, A., Almeida, F., Matos, T., & Reis, J. (2009b). Wine Quality \[Data set\]. UCI Machine Learning Repository. https://doi.org/10.24432/C56S3T

Cover, T. M., & Hart, P. E. (1967). Nearest neighbor pattern classification. IEEE Transactions on Information Theory, 13(1), 21–27. https://doi.org/10.1109/TIT.1967.1053964

James, G., Witten, D., Hastie, T., & Tibshirani, R. (2021). An introduction to statistical learning: With applications in R (2nd ed.). Springer. https://doi.org/10.1007/978-1-0716-1418-1

Kuhn, M. (2008). Building predictive models in R using the caret package. Journal of Statistical Software, 28(5), 1–26. https://doi.org/10.18637/jss.v028.i05

Smola, A. J., & Schölkopf, B. (2004). A tutorial on support vector regression. Statistics and Computing, 14(3), 199–222. https://doi.org/10.1023/B:STCO.0000035301.49549.88

Wickham, H. (2016). ggplot2: Elegant graphics for data analysis. Springer. https://doi.org/10.1007/978-3-319-24277-4

Dokumentasi pendukungSupporting documentation

caret · kernlab · rsample · dplyr · ggplot2 · UCI Wine Quality

PENULISAUTHOR
Unique Desyrre A. Resiloy