Report on SVM with Kernal Trick Classifying MNIST Dataset
By LRL
1. Introduction
Support Vector Machines (SVM) have been one of the most successful machine learning algorithms for classification tasks. They are especially powerful in high-dimensional spaces and are effective when the number of dimensions is greater than the number of samples. However, a linear SVM, which finds a hyperplane to separate different classes, is limited in its capacity to model more complex relationships. Kernel functions are used in SVM to transform input data into a higher-dimensional space, making it possible to perform non-linear classification. The ability to automatically recognize and classify handwritten digits has numerous practical applications, from postal mail sorting to bank check processing. The Modified National Institute of Standards and Technology (MNIST) dataset is a large database of handwritten digits that has become a standard for evaluating various image processing systems.
Digit classification is not only an interesting academic problem but also has various real-world applications such as automatic data entry, recognition of numbers in images, and aiding accessibility for the visually impaired. Thus, this study focuses on using SVM to classify MNIST dataset, specifically, first, to verify the effect of kernel functions in dealing with non-linear problems i.e. Digit Classification; second, to find the best configuration of an SVM for classifying the MNIST dataset.
The report is structured as follows: In Section II methodology, we will discuss the dataset, data preprocessing techniques, SVM classifiers, and model evaluation. Section III presents the experiment setup, hyperparameter tuning, model training, and evaluation results. In Section IV, we will discuss the insights and observations from the results, potential reasons for the outcomes, limitations of the study, and practical implications. Finally, Section V concludes the report with a summary of findings, future directions for improvement, and final thoughts. Appendices contains the full Python code and additional tables.
2. Methodology
In the introduction, we have explored the background of the MNIST dataset and the significance of Support Vector Machines for digit classification. With that context in place, we now proceed to the heart of this report: the methodology. This section is structured to provide clarity on how the study was conducted, focusing on four core components - the dataset, data preprocessing techniques, SVM classifiers, and model evaluation. Each segment is integral to understanding the approach and findings of this study. Let’s start by discussing the dataset utilized for the experiment.
2.1. Dataset
The Modified National Institute of Standards and Technology (MNIST) dataset is a collection of handwritten digits that has been widely used for training and testing in the field of machine learning. The MNIST dataset contains grayscale images of handwritten digits, ranging from to . Each image is pixels in height and pixels in width, with a total of pixels. The pixel values range from to , where represents the color white, and represents black.
MNIST has been an essential benchmark dataset in machine learning because of its simplicity and size. It’s considered as the “hello world” of machine learning, especially for image classification tasks. The dataset is large enough to be representative of real-world handwritten digits but small enough to be manageable for training algorithms even on modest hardware. It allows experts to develop, test, and compare machine learning algorithms for classification tasks efficiently.
2.2. Data Preprocessing
2.2.1 Dimensionality Reduction using PCA
One of the critical steps in preprocessing data for machine learning tasks, especially for image data, is dimensionality reduction. This is implemented using Principal Component Analysis (PCA) in this study. Mathematically, PCA seeks to project data onto a lower-dimensional subspace that captures the maximum variance in the data.
Suppose the original data matrix is denoted by of dimensions , where is the number of samples and is the number of features (in this case, pixels). The covariance matrix of is given by:
where is the sample and is the mean of the data (mean vector). PCA aims to find a set of orthogonal vectors, known as principal components, that maximize the variance of the projected data. These vectors are the eigenvectors of the covariance matrix , and the amount of variance they capture is represented by their corresponding eigenvalues. The principal components are sorted by their eigenvalues in decreasing order.
In the study, PCA is applied to the MNIST dataset to reduce its dimensionality. The number of principal components is chosen such that of the total variance in the data is retained, which only dimensions are left after compression. The principal axes are computed solely based on the training dataset. The transformed training, validation, and test sets are stored in X_train_compact, X_val_compact, and X_test_compact respectively.
Computation Trick of PCA
According to Singular Value Decomposition, we can factorize , thus we have:
Those two matrices are semi-definite, and are both of the shape , where is the eigenvalues of both and , i.e. . Note that is exactly the eigenvectors of , and is also exactly the eigenvectors of . Now consider the MNIST problem, is the dimention of samples, which is , where is the number of samples which is much greater than m, i.e. , which tells us is a small matrix. Consider:
Once is calculated, we can derive from the above equation, and then take the firsk entries of as the principal axis of PCA.
2.2.2 Deskewing of Images
In the second part of data preprocessing, deskewing of images is performed. Deskewing is the process of straightening an image that has been scanned or captured askew. In the context of the MNIST dataset, it is particularly important because handwritten digits can often be written at different angles, and deskewing can help in standardizing the images, which is likely to improve the performance of the classifier.
Deskewing is achieved by three main functions:
-
calculate_image_moments(image): This function computes the moments of the image which are used to calculate the skewness. Mathematically, the moments are given by:where is the -th moment, and and are the spatial coordinates of the image.
-
deskew_image(image): This function takes the raw image and deskews it by using an affine transform. The skewness alpha is computed from the covariance matrix obtained from image moments. The affine transform matrix is given by:Then, the image is transformed using this affine transform matrix.
-
deskew_vectors(images): This function takes a batch of images and applies the deskewing to each image. The deskewing process is essentially a geometric transformation of the image. The reason behind deskewing is to reduce variations between images due to different orientations. This makes the learning algorithm focus more on the essential features rather than being affected by the orientations
In summary, deskewing normalizes these images to a standard form which helps in improving the accuracy and performance of machine learning models.
2.3. SVM Classifiers
2.3.1 Introduction to SVM classifiers
Support Vector Machines (SVM) are a class of supervised learning algorithms primarily used for classification and regression tasks. SVM is based on the idea of finding a hyperplane that best separates the data into different classes. The objective is to find the optimal hyperplane that maximizes the margin between the closest data points of the two classes, which are known as support vectors.
Mathematically, Given a dataset , where and , we assume that the dataset is linearly separable. Our goal is to find a decision boundary that classifies the dataset into two groups. Ideally, this boundary should maximize the distance from the data points of both classes. We refer to the maximum margin as .
The distance from sample to the boundary is . The samples closest to the boundary hyperplane are termed support vectors. The objective of linear SVM is to find the hyperplane that maximizes the margin . It is important to note that to maximize the margin, we need to focus only on the support vectors and can disregard the other samples.
Consequently, we have:
For every support vector , the inequality turns into an equality, and in such cases, should be:
As we should only focus on the support vectors, the margin can be expressed as:
We can then formulate a quadratic optimization problem as:
This is equivalent to:
We construct the Lagrangian corresponding to the problem above:
We then calculate the derivatives of the Lagrange function for :
Substituting into :
We have thus constructed the dual form of the primal problem:
Let be the optimal solution of the dual problem. The solution to the primal problem is then given by:
- The optimal coefficient is a linear combination of the samples.
However, deriving the optimal is not straightforward. It is verified that this problem satisfies the Karush-Kuhn-Tucker conditions, which indicate that:
As we are maximizing , if , then must be zero. This implies that those samples are distant from the decision boundary. The samples for which , making greater than zero, are the support vectors, meaning they are nearest to the decision hyperplane. These support vectors, which constitute a small fraction of the entire training set, determine the position of the decision boundary. In practice, we calculate all the values for which is greater than zero and take the average. Therefore:
We can find the optimal using the Sequential Minimal Optimization (SMO) Algorithm. This, in turn, allows us to determine the solutions for and .
The above formulation is known as the hard-margin SVM which does not allow any misclassification. In practical applications, a soft-margin SVM is often used to allow some degree of misclassification, which introduces a slack variable and a regularization parameter , leading to the following constraint:
The objective then becomes minimizing , which represents a trade-off between maximizing the margin and minimizing classification errors.
2.3.2 Linear SVM
Linear SVM is a special case of SVM where the separating hyperplane is linear, i.e., the decision boundary is a straight line (in 2D) or a plane (in 3D) or a hyperplane in higher dimensions. It is used when the data is linearly separable or when a linear decision boundary is desired. In Linear SVM, the kernel function is simply the dot product between the feature vectors, i.e., . The linear SVM finds the optimal hyperplane in the original feature space.
In the study, we assess the performance of a Linear Support Vector Machine classifier on the MNIST dataset. Specifically, we conduct an empirical analysis to evaluate the effectiveness of the classifier on two versions of the dataset: the original high-dimensional data and data that has been subjected to dimensionality reduction using Principal Component Analysis. The Linear SVM is configured with a regularization parameter set to and employs regularization. The purpose of this comparison is to investigate how the dimensionality of the feature space impacts the classification performance. This will allow us to discern if PCA compression maintains classification accuracy while possibly improving computational efficiency.
2.3.3 Non-Linear SVM
Non-Linear SVM is an extension of the linear SVM algorithm, which is adept at dealing with data that cannot be separated by a linear hyperplane. Non-Linear SVM utilizes kernel functions to transform the input data into a higher-dimensional space where a linear hyperplane can effectively separate the classes. Essentially, the kernel functions facilitate the SVM in handling complex relationships in the data.
The general SVM solves the following primal problem:
The dual problem to the primal is:
where is the vector of all ones, and is an by positive semidefinite matrix, , where is the kernel. The terms are called the dual coefficients, and they are upper-bounded by . This dual representation highlights the fact that training vectors are implicitly mapped into a higher (maybe infinite) dimensional space by the function.
Once the optimization problem is solved, the output of decision_function for a given sample becomes:
and the predicted class correspond to its sign. We only need to sum over the support vectors (i.e. the samples that lie within the margin) because the dual coefficients are zero for the other samples.
- Note: In
ScikitLibrary, These parameters can be accessed through the attributesdual_coef_which holds the product,support_vectors_which holds the support vectors, andintercept_which holds the independent term
Support Vector Machines are powerful tools, but their compute and storage requirements increase rapidly with the number of training vectors. The core of an SVM is a quadratic programming problem (QP), separating support vectors from the rest of the training data. The QP solver used by the libsvm-based implementation scales between and depending on how efficiently the libsvm cache is used in practice (dataset dependent). If the data is very sparse should be replaced by the average number of non-zero features in a sample vector.
Kernel functions
The kernel function used in the study are the following:
Linear:
Polynomial:
The polynomial kernel is another kernel function defined as:
where is a scale factor, is the coefficient term (coef0), and is the degree of the polynomial. The polynomial kernel is capable of learning complex relationships by raising the input features to a power.
Radial Basis Function (RBF):
The RBF kernel is a popular kernel function commonly used in SVM classification. It is defined as:
where is a parameter that controls the shape of the decision boundary. RBF kernels are especially adept at managing cases where the boundary separating the classes is highly non-linear.
Searching for the Best HyperParameters
To search for the best hyperparameters for the Non-Linear SVM, we employ a grid search approach, iterating through various combinations of kernel functions and hyperparameters. We evaluate each configuration on both the original and PCA-reduced datasets.
For each configuration, the model is trained on the training set and evaluated on the validation set. The configuration that achieves the highest validation accuracy is selected as the best set of hyperparameters. This is an exhaustive but effective way to tune the hyperparameters of the Non-Linear SVM for optimal performance.
After identifying the best configuration, the model is then retrained using this configuration on the entire dataset, and its performance is evaluated. This approach ensures that we use the most optimal parameters for the Non-Linear SVM, thus maximizing its classification accuracy.
The configuration tested in the study are:

2.3.4 Multi-class Classification
In the study, we implement the “one-versus-one” approach for multi-class classification. In total, n_classes * (n_classes - 1) / 2 classifiers are constructed and each one trains data from two classes.
2.4. Model Evaluation
2.4.1 Performance Metrics
In this study, the performance of the SVM classifiers is evaluated using two metrics: accuracy and F1 Score.
-
Accuracy: This is a common metric for classification problems and is defined as the ratio of the number of correct predictions to the total number of predictions made. It is expressed as:
-
F1 Score: The F1 Score is the harmonic mean of precision and recall, and it tries to balance these two values. Precision is the number of true positive predictions divided by the total number of positive predictions made, while recall is the number of true positive predictions divided by the total number of actual positives. The F1 Score is especially useful in cases where class distributions are imbalanced. It is defined as:
The evaluation is conducted on both the original data and the PCA compressed data during the hyperparameter search process, utilizing the validation set. This allows us to understand how different model configurations perform with respect to the selected metrics, and how dimensionality reduction affects model performance.
2.4.2 Smaller Sample Training
After identifying the optimal parameters and evaluating on the whole training set, the SVM model was then trained on a subset of the dataset. Specifically, a sample comprising 1,000 instances was randomly extracted from the original dataset, which encompasses 50,000 instances in total. The training process was conducted over 50 independent iterations to ascertain the model’s aggregate performance. It is imperative to recognize that employing a reduced sample size for training could potentially affect the model’s generalization capability and overall performance. Moreover, the selected training subset underwent two preprocessing techniques in parallel, namely deskewing and PCA compression, prior to being input into the model for the evaluation of preprocessing effects.
3. Experiments and Results
3.1. Experiment Setup
3.1.1 Hardware and Software Specifications
The experiments were conducted on an Apple M1 Pro chipset, which boasts high performance and efficiency. The specifications of the hardware used in the experiments are as follows:
- Processor: Apple M1 Pro
- Core Configuration: The M1 Pro chip features a total of 8 cores. Out of these, six are high-performance cores (P-cores) that can operate within a frequency range of 600 MHz to 3220 MHz. The remaining two are high-efficiency cores (E-cores) with an operating frequency range of 600 MHz to 2064 MHz.
- Unified Memory: 16GB of unified memory, which allows for seamless performance and memory management.
This hardware configuration provides a robust and efficient environment for the execution of machine learning models and algorithms.
3.1.2 Libraries and Tools Used
The experiments were implemented using Python, a popular programming language for data science and machine learning. Below is a table with the libraries and tools used, along with their respective versions:
| Library | Version | Description |
|---|---|---|
| python | 3.9.16 | The programming language used for implementing the machine learning models and data processing. |
| numpy | 1.23.5 | A library for Python that adds support for large, multi-dimensional arrays and matrices. |
| scikit-learn | 1.2.2 | A machine learning library for Python. It features various classification, regression and clustering algorithms including support vector machines. |
| matplotlib | 3.7.1 | A plotting library for Python, used for creating static, interactive, and animated visualizations. |
The selection of these libraries was made to ensure a powerful and efficient experimentation environment. Scikit-learn is especially relevant as it provides the implementation of the Support Vector Machine (SVM) algorithm, along with functions for model evaluation and selection. Numpy supports numerical computations, while Matplotlib is used for visualizing the results and performance metrics.
3.2. Model Training
3.2.1 PCA Compression Outcomes
The application of PCA was instrumental in efficiently reducing the dimensionality of the MNIST dataset. Initially consisting of 784 features, PCA was configured to maintain 90% of the dataset’s variance. This resulted in the number of features being condensed to 87, a significant reduction achieved in approximately 2.41 seconds. This streamlined dataset retains the majority of the original information while potentially enabling swifter model training and economizing storage resources, which are vital in practical applications.
3.2.2 Training SVM
Upon employing Principal Component Analysis (PCA) for dimensionality reduction, the SVM were trained. The Linear SVM model displayed a training accuracy of 96.8% and a validation accuracy of 89.79% without the application of PCA. With PCA, a marginal increase in validation accuracy to 91.08% was observed. An SVM model incorporating a Radial Basis Function (RBF) kernel, and optimized hyperparameters (C=3.0, gamma='scale'), yielded the most commendable performance. Without PCA, it attained a training accuracy of 99.82% and a validation accuracy of 97.14%; whereas, with PCA, the training accuracy rose slightly to 99.9% and the validation accuracy to 97.48%. It is important to highlight that the utilization of PCA considerably curtailed the model training duration and elicited a modest augmentation in validation accuracy, thus expediting the hyperparameter tuning process. Additionally, the SVM model with a polynomial kernel exhibited strong performance, attaining a peak validation accuracy of 97.27% when PCA was employed.
The tuned parameters and their performance is shown below.


3.3 Final Model Evaluation and Analysis
3.3.1 Whole Training Set Evaluation
With the best hyperparameters identified, the next step was to evaluate the performance of the SVM model on the entire dataset. To achieve this, the training set and validation set were concatenated to form a comprehensive training dataset. The model was then trained using this combined dataset with the optimized hyperparameters ('C': 3.0, 'kernel': 'rbf', 'gamma': 0.05).
It’s important to note that training the model on the whole dataset was computationally more demanding and took significantly longer to process compared to the initial hyperparameter tuning phase. The performance of the model was subsequently evaluated on the test set, which had been held out and not used during the training or hyperparameter tuning phases. This evaluation on the test set provided an unbiased assessment of the model’s ability to generalize to new, unseen data. The following performance statistics were observed:
- Training time: 227.6s (on average)
- Test Accuracy: 98.68%
- F1 score: 98.67%
In summary, the SVM classifier with the RBF kernel, a regularization parameter of 3.0, and gamma of 0.05, demonstrated remarkable performance on the test dataset. The training process took an average of 227.6 seconds to complete. The model achieved an impressive test accuracy of 98.68%, coupled with an F1 score of 98.67%. These metrics indicate that the classifier is highly effective in accurately predicting the classes of the test data, and has a balanced harmony between precision and recall. The results suggest that the SVM model, with the specified hyperparameters, is well-suited for this classification task and is capable of making reliable predictions with high accuracy.
3.3.2 Small Training Set Evaluation

Given the promising performance of the model on the entire training set, it was deemed important to evaluate its efficacy on smaller datasets. To accomplish this, the training data was partitioned into 50 distinct subsets, each comprising 1000 images. This methodology not only facilitated a more streamlined and efficient evaluation process but also enabled an in-depth analysis of the model’s adaptability and performance in scenarios with limited data availability.
Two types of preprocessing were applied to the data: deskewing and PCA for dimensionality reduction. The performance of the model with these preprocessing techniques was compared.
Deskewed Data
For the deskewed data, the following statistics were observed:
- Mean Score: 95.0134%
- Variance of Scores: 1.1437e-05
The mean score indicates a relatively high accuracy achieved by the model on deskewed data. The low variance signifies that the scores were consistently high across the 50 subsets.
PCA Compressed Data
For the PCA compressed data, the following statistics were observed:
- Mean Score: 91.8573%
- Variance of Scores: 4.825e-05
The mean score for the PCA compressed data is somewhat lower than the deskewed data. Additionally, the variance is higher, indicating that there was more variability in the scores across the 50 subsets.
In summary, from the evaluation on small training sets, it is evident that preprocessing the data with deskewing resulted in better performance than using PCA for dimensionality reduction. The model trained on deskewed data not only achieved a higher mean accuracy but also exhibited more consistent performance across different subsets of the training data. This suggests that deskewing is a more effective preprocessing technique for SVM when working with small datasets in this context.
3.3.3 Misclassified Examples
Below are some misclassified examples:
The examples of misclassified images demonstrated that the numbers in question were highly similar in appearance. Remarkably, even to the human eye, distinguishing between the actual and predicted labels for these images is challenging. This observation is critical as it implies that the errors made by the model are not necessarily indicative of significant shortcomings.
4. Discussion
4.1 Insights and Observations
4.1.1 Effects of Dimensionality Reduction
One of the significant aspects of this study was the use of Principal Component Analysis in reducing the dimensionality of the dataset. By retaining 90% of the variance, PCA effectively reduced the feature dimensions from 784 to 87. It is notable that this reduction did not result in a substantial loss of information.
Interestingly, the validation accuracy of the models experienced a slight improvement with the application of PCA. For instance, the Linear SVM model’s validation accuracy increased from 89.79% without PCA to 91.08% with PCA. This observation is counter-intuitive as one might expect a drop in performance due to the reduced feature set. However, this can be attributed to PCA filtering out noise and redundancies in the data, which in turn may have contributed to a more robust representation of the underlying structure, improving the generalization capabilities of the models.
Moreover, employing PCA substantially reduced the training time, making the model training process more efficient. This has practical implications, especially in resource-constrained environments, where optimizing computational resources is crucial.
4.1.2 Sensitivity to Parameter Tuning
This study has showcased the sensitivity of SVM models to their parameter configurations. Hyperparameters, namely C, gamma, and kernel, have been thoroughly experimented with to assess their impact on the SVM’s performance.
In the context of SVMs, the regularization parameter, denoted as C, plays a pivotal role in the model’s configuration. Opting for a smaller C engenders a broader margin which, although permitting a certain degree of misclassifications, often results in a more parsimonious model that demonstrates enhanced generalization. In contrast, a larger C value yields a narrower margin, thus intensifying the model’s endeavor to correctly classify a higher percentage of instances, albeit potentially elevating model complexity. This delicate balance manifests itself evidently when contrasting Configuration 1 (linear SVM with C set to 1.0) with Configuration 4 (characterized by C equating to 3.0, kernel type as ‘rbf’, and ‘gamma’ as ‘scale’). The amplification of C corresponded with a significant surge in validation accuracy, both for the original data (escalating from 89.79% to 97.14%) and the PCA compressed data (increasing from 91.08% to 97.48%). Importantly, an intriguing trend was discerned wherein the training accuracy invariably reaches 100% as C adopts larger values, echoing the theoretical understanding of C as a determinant of the trade-off between simplicity and classification precision.
The kernel parameter specifies the type of hyperplane used to separate the data. In this study, the use of the Radial Basis Function (RBF) kernel (Configuration 4) significantly outperformed the linear kernel (Configuration 2), with the original data’s validation accuracy increasing from 92.32% to 97.14%. This difference underscores the RBF kernel’s ability to capture the nonlinear relationships in the MNIST dataset more effectively.
The study also explored the use of a polynomial kernel (Configurations 11-14), which provides another way to handle non-linearities. Although it did not surpass the performance of the RBF kernel, it did outperform the linear kernel, making it a feasible alternative for certain datasets.
In conclusion, careful tuning of SVM parameters is critical in optimizing model performance. Different datasets may necessitate different configurations, emphasizing the need for comprehensive exploration of the parameter space.
4.1.3 Long Training Time
Although PCA was utilized to reduce training times significantly, it is important to note that training the final SVM model with the RBF kernel on the entire dataset was computationally demanding and took an extended period to complete (averaging around 227.6 seconds). This is indicative of the computational complexity inherent in SVMs, especially with non-linear kernels such as RBF. The training time is likely to be even more prolonged for larger datasets, which can be a limiting factor in certain applications where rapid model training is necessary.
The long training time is a trade-off for the high performance achieved by the model. For applications where training time is a critical factor, one might consider employing simpler models or using more efficient training algorithms. Nonetheless, the high accuracy achieved by the SVM classifier makes it a viable option for applications where model performance is paramount and computational resources are not as constrained.
In conclusion, the study reveals the importance of dimensionality reduction, hyperparameter tuning, and the consideration of computational costs in achieving high performance on the MNIST dataset using SVMs. The insights gained could be valuable in making informed decisions in practical applications involving image classification.
4.2 Limitations and Future Directions
- Dimensionality Reduction: The study employed PCA for dimensionality reduction, which is a linear technique. This limits the ability to capture non-linear relationships in the dataset. The application of non-linear dimensionality reduction methods, such as t-SNE or UMAP, may lead to different insights.
- Parameter Tuning: The analysis relied on a select range of values for the hyperparameters such as
Candgamma. A more exhaustive search or employing advanced optimization techniques such as Bayesian optimization might yield different results. Moreover, the study did not investigate the impact of other relevant parameters, such as class weights, which might affect the model’s performance, especially if the dataset is imbalanced. - Training Time Sensitivity: The analysis showed that training times are sensitive to changes in hyperparameters. However, there is no in-depth examination of how different hardware configurations or optimization algorithms may affect these times. This limits the generalizability of the training time observations.
- Choice of Metrics: The study primarily focused on metrics such as accuracy and F1-score. Depending on the nature of the dataset and the problem domain, other metrics like precision, recall, or AUC-ROC might be more appropriate for evaluating model performance.
5. Conclusion
The aim of this study was twofold: first, to ascertain the impact of kernel functions in handling non-linear problems in the context of digit classification using Support Vector Machines (SVM), and second, to discern the optimal configuration of SVM for the classification of the Modified National Institute of Standards and Technology (MNIST) dataset. The study employed a rigorous methodology involving data preprocessing, implementation of SVM classifiers, and model evaluation using a comprehensive set of metrics.
Our investigation has demonstrated that kernel functions substantially improve the capacity of SVMs to model complex, non-linear relationships in high-dimensional spaces, as evidenced by the improved performance metrics when employing radial basis function (RBF) and polynomial kernels compared to a linear SVM. Particularly, the RBF kernel emerged as highly efficacious in capturing non-linearity in the data.
In light of the findings and limitations, future research could consider exploring non-linear dimensionality reduction techniques, employing more sophisticated hyperparameter optimization strategies, and comparing SVMs with other machine learning algorithms. Furthermore, it would be worthwhile to investigate the scalability of the optimal SVM configuration on larger datasets and in different domains.
In conclusion, this study has provided valuable insights into the role of kernel functions in enhancing the performance of SVMs for digit classification. Through rigorous experimentation and analysis, an optimal configuration of SVM for the MNIST dataset was identified, paving the way for practical applications and future research in this area.
6. References
Omitted some because of the coming final :(
- Platt, J. “Probabilistic outputs for SVMs and comparisons to regularized likehood methods.” Advances in Large Margin Classifiers. MIT Press, 1999.
- Wu, Ting-Fan, Chih-Jen Lin, and Ruby Weng. “Probability estimates for multi-class classification by pairwise coupling.” Advances in Neural Information Processing Systems 16 (2003).
- Smola, Alex J., and Bernhard Schölkopf. “A tutorial on support vector regression.” Statistics and computing 14 (2004): 199-222.
- Crammer, Koby, and Yoram Singer. “On the algorithmic implementation of multiclass kernel-based vector machines.” Journal of machine learning research 2.Dec (2001): 265-292.
- https://scikit-learn.org/stable/modules/svm.html#complexity
- https://www.csie.ntu.edu.tw/~cjlin/libsvm/
7. Appendices
7.1 Python Code
main.py
import numpy as np
from matplotlib import pyplot as plt
from sklearn.svm import SVC
from helpers import read_mnist, pca_fit, evaluate_model
from sklearn.model_selection import learning_curve
from initialization import deskew_vectors
import SMO
# Load the MNIST data with the shape of (N, 784)
X_train_origin, y_train_origin, X_val_origin, y_val_origin, X_test_origin, y_test_origin = read_mnist('./data/mnist.pkl.gz')
print('Shape of initial data:', X_train_origin.shape)
print('Applying PCA to reduce data dimensions...')
# Reduce dimensions of the original data (784 dimensions) through PCA
pca = pca_fit(X=X_train_origin, variation_preserve=87)
X_train_compact = pca.transform(X_train_origin) # Use transform method of PCA object
print(type(X_train_compact))
X_val_compact = pca.transform(X_val_origin)
X_test_compact = pca.transform(X_test_origin)
y_train = y_train_origin
y_val = y_val_origin
print('Shape of Data after reduction to 90%:', X_train_compact.shape, X_val_compact.shape, X_test_compact.shape) # dim = 87
# Hyperparameter Configurations for SVM
configs = [
{'kernel': 'linear'},
{'C': 1.0, 'kernel': 'rbf', 'gamma': 'scale'},
{'C': 3.0, 'kernel': 'rbf', 'gamma': 'scale'},
{'C': 5.0, 'kernel': 'rbf', 'gamma': 'scale'},
{'C': 10.0, 'kernel': 'rbf', 'gamma': 'scale'},
{'C': 1.0, 'kernel': 'rbf', 'gamma': .05},
{'C': 3.0, 'kernel': 'rbf', 'gamma': .05}, # Best Performance
{'C': 5.0, 'kernel': 'rbf', 'gamma': .05},
{'C': 10.0, 'kernel': 'rbf', 'gamma': .05},
{'C': 1.0, 'kernel': 'poly', 'degree': 3, 'gamma': 'scale', 'coef0': 0.0},
{'C': 3.0, 'kernel': 'poly', 'degree': 3, 'gamma': 'scale', 'coef0': 0.0},
{'C': 5.0, 'kernel': 'poly', 'degree': 3, 'gamma': 'scale', 'coef0': 0.0},
{'C': 10.0, 'kernel': 'poly', 'degree': 3, 'gamma': 'scale', 'coef0': 0.0},
]
# Evaluate Linear SVM
print("\n\n")
print("-" * 40, "\n", "*** Evaluating Linear SVM ***")
print("--- Performance on Original Data ---")
evaluate_model({'C': 1.0, 'penalty': 'l2'}, X_train_origin, y_train_origin, X_val_origin, y_val_origin, linear=True)
print("--- Performance on PCA-Reduced Data ---")
evaluate_model({'C': 1.0, 'penalty': 'l2'}, X_train_compact, y_train, X_val_compact, y_val, linear=True)
print("\n\n")
# Non-Linear SVM
print("\n\n")
print("-" * 40, "\n", "*** Evaluating SVM with Kernel Functions ***")
# Search Hyperparameters
print(f"{'~' * 40}\n"
f"Searching for the Best Parameters...")
best_score = 0
best_config = None
for config in configs:
print("Config :", config)
print("--- Performance on Original Data ---")
score, model = evaluate_model(config, X_train_origin, y_train_origin, X_val_origin, y_val_origin)
if score > best_score:
best_score = score
best_config = config
print("--- Performance on PCA-Reduced Data ---")
score, model = evaluate_model(config, X_train_compact, y_train, X_val_compact, y_val)
if score > best_score:
best_score = score
best_config = config
print("*" * 40)
print("\n")
best_config = {'C': 3.0, 'kernel': 'rbf', 'gamma': .05}
best_score = 95
print(f"The best model with respect to config\n"
f"----{best_config}\n"
f"Validation Accuracy: {best_score}\n")
print('-' * 40)
print(f"{'~' * 40}\n"
f"** Start training 'best' model after validation with all dataset **")
# Combine the training and validation sets
print("Combining the training and validation sets for final training...")
X_train_total_origin = np.concatenate((X_train_origin, X_val_origin), axis=0)
X_train_total_compact = np.concatenate((X_train_compact, X_val_compact), axis=0)
y_train_total = np.concatenate((y_train, y_val), axis=0)
# Deskew original images
print("Deskewing images......)")
deSkewed_train = deskew_vectors(X_train_total_origin)
print(deSkewed_train)
deSkewed_test = deskew_vectors(X_test_origin)
print(deSkewed_test)
# Takes longer time since it's not compressed through PCA
print("Evaluating the final deskewed result ......... ????️????️????️Takes longer time")
score, clf = evaluate_model(best_config, deSkewed_train, y_train_total, deSkewed_test, y_test_origin, 500, 10_000)
print("Evaluating the final PCA result ......... ????️????️????️Takes longer time")
score, clf = evaluate_model(best_config, X_train_total_compact, y_train_total, X_test_compact, y_test_origin, 500, 10_000)
print("????????????????????????")
# Initialize an empty list to store the scores
scores_deSkewed = []
scores_compact = []
# Divide training set into segments of 1000 samples and evaluate the model
for i in range(50):
start_idx = i * 1000
end_idx = start_idx + 1000
# Subset of training data
subset_X_train_deSkewed = deSkewed_train[start_idx:end_idx]
subset_X_train_compact = X_train_total_compact[start_idx:end_idx]
subset_y_train = y_train_total[start_idx:end_idx]
# Evaluate the model with this subset
score, clf = evaluate_model(best_config, subset_X_train_deSkewed, subset_y_train, deSkewed_test, y_test_origin, 1000, 10_000)
scores_deSkewed.append(score)
score, clf = evaluate_model(best_config, subset_X_train_compact, subset_y_train, X_test_compact, y_test_origin, 1000, 10_000)
scores_compact.append(score)
# Append the score to the list
# Calculate the mean and variance of scores
mean_score_deSkewed = np.mean(scores_deSkewed)
variance_score_deSkewed = np.var(scores_deSkewed)
print(f'Mean Score deSkewed: {mean_score_deSkewed}')
print(f'Variance of Scores deSkewed: {variance_score_deSkewed}')
print(scores_deSkewed)
mean_score_compact = np.mean(scores_compact)
variance_score_compact = np.var(scores_compact)
print(f'Mean Score compact: {mean_score_compact}')
print(f'Variance of Scores compact: {variance_score_compact}')
print(scores_compact)
# Print the mean and variance of F1 scores
predict_y = clf.predict(X_test_compact)
idx = np.argwhere(predict_y != y_test_origin)
plt.xticks([])
plt.yticks([])
for i in idx:
plt.imshow(X_test_origin[i].reshape(28, 28), cmap="gray")
plt.title(f"Correct label {y_test_origin[i]}, predicted label {predict_y[i]}")
plt.show()helpers.py
from functools import wraps
from time import time
import numpy as np
import pickle
import gzip
from sklearn.decomposition import PCA
from sklearn.svm import SVC
from sklearn.svm import LinearSVC
import time
from functools import wraps
from sklearn.metrics import f1_score
def timing(f):
"""A decorator that times the execution of a function.
Parameters
-------------------
f : function
The function to time.
Returns
-------------------
wrapper : function
The wrapped function.
"""
@wraps(f)
def wrapper(*args, **kwargs):
print(f"{'-' * 40}")
print(f"Start running '{f.__name__}' function...")
start_time = time.perf_counter()
result = f(*args, **kwargs)
end_time = time.perf_counter()
elapsed_time = end_time - start_time
print(f"Finished '{f.__name__}'. Elapsed time: {elapsed_time:.6f} seconds")
print(f"{'-' * 40}")
return result
return wrapper
@timing
def pca_fit(X, variation_preserve=0.95):
"""
Fit a PCA model to the data X, choosing the number of components
such that `information_preserve` proportion of the variance is retained.
Parameters:
X: array-like, shape (n_samples, n_features)
Data to perform PCA on.
information_preserve: float, between 0 and 1
Proportion of variance to retain.
Returns:
PCA object fitted to the data.
"""
obj = PCA(n_components=variation_preserve)
obj.fit(X)
return obj
@timing
def read_mnist(mnist_file):
"""
Reads MNIST data.
Parameters
----------
mnist_file : string, The name of the MNIST file (e.g., 'mnist.pkl.gz').
Returns
-------
(train_X, train_Y, val_X, val_Y, test_X, test_Y) : tuple
train_X : numpy array, shape (N=50000, d=784)
Input vectors of the training set.
train_Y: numpy array, shape (N=50000)
Outputs of the training set.
val_X : numpy array, shape (N=10000, d=784)
Input vectors of the validation set.
val_Y: numpy array, shape (N=10000)
Outputs of the validation set.
test_X : numpy array, shape (N=10000, d=784)
Input vectors of the test set.
test_Y: numpy array, shape (N=10000)
Outputs of the test set.
"""
with gzip.open(mnist_file, 'rb') as f:
train_data, val_data, test_data = pickle.load(f, encoding='latin1')
train_X, train_Y = train_data
val_X, val_Y = val_data
test_X, test_Y = test_data
return train_X, train_Y, val_X, val_Y, test_X, test_Y
@timing
def evaluate_model(param, X_train, y_train, X_val, y_val, N_train=10_000, N_val=10_000, print_score=True, linear=False):
"""
Validate an SVM model with given parameters and data.
Parameters:
-----------
param : dict
Parameters for the SVC model.
X_train : array-like
Features for the training set.
y_train : array-like
Target variable for the training set.
X_val : array-like
Features for the validation set.
y_val : array-like
Target variable for the validation set.
N_train : int, optional (default=10_000)
Number of training samples to use.
N_val : int, optional (default=10_000)
Number of validation samples to use.
print_score : bool, optional (default=True)
Whether to print the model score or not.
Returns:
--------
score : float
Validation score of the model.
clf : SVC object
Trained model object.
"""
print(f"*** Evaluating model with parameters:{param} ***")
# Limit the data size for training and validation
X_train, y_train = X_train[:N_train], y_train[:N_train]
X_val, y_val = X_val[:N_val], y_val[:N_val]
# Create and fit the model
if not linear:
clf = SVC(**param)
else:
clf = LinearSVC(**param)
clf.fit(X_train, y_train)
# Calculate and print scores if requested
print("Calculating Accuracy...")
score = clf.score(X_val, y_val)
y_pred = clf.predict(X_val)
f1 = f1_score(y_val, y_pred, average='weighted')
if print_score:
print(f"Training Accuracy: {clf.score(X_train, y_train) * 100:.4f}%")
print(f"Validation Accuracy: {score * 100:.4f}%")
print(f"F1 score: {f1 * 100:.4f}%")
return score, clfinitialization.py
import numpy as np
from scipy.ndimage import interpolation
def calculate_image_moments(image):
"""
Calculate the first-order and second-order moments of the given image.
:param image: A 2D array representing the grayscale image.
:return: A tuple containing the mean vector and covariance matrix of the image.
"""
# Calculate the total intensity of the image
grid_x, grid_y = np.mgrid[:image.shape[0], :image.shape[1]]
total_image_intensity = np.sum(image)
# Calculate the first-order moments (mean)
mu_x = np.sum(grid_x * image) / total_image_intensity
mu_y = np.sum(grid_y * image) / total_image_intensity
# Calculate the second-order moments (variances and covariance)
var_x = np.sum((grid_x - mu_x) ** 2 * image) / total_image_intensity
var_y = np.sum((grid_y - mu_y) ** 2 * image) / total_image_intensity
cov_xy = np.sum((grid_x - mu_x) * (grid_y - mu_y) * image) / total_image_intensity
# the mean vector and covariance matrix
mu_vector = np.array([mu_x, mu_y])
covariance_matrix = np.array([[var_x, cov_xy], [cov_xy, var_y]])
return mu_vector, covariance_matrix
def deskew_image(image):
"""
Correct the skewness of the given image using an affine transformation.
:param image: A 2D array representing the grayscale image.
:return: The deskewed image as a 2D array.
"""
# Calculate the image moments
mu_vector, covariance_matrix = calculate_image_moments(image)
# Calculate the skewness and build the affine transform matrix
alpha = covariance_matrix[0, 1] / covariance_matrix[0, 0]
affine_transform_matrix = np.array([[1, 0], [alpha, 1]])
# Calculate the transformation offset
image_center = np.array(image.shape) / 2.0
offset = mu_vector - np.dot(affine_transform_matrix, image_center)
transformed_image = interpolation.affine_transform(image, affine_transform_matrix, offset=offset)
# Normalize the transformed image
return (transformed_image - transformed_image.min()) / (transformed_image.max() - transformed_image.min())
def deskew_vectors(images):
"""
Deskew a batch of images represented as vectors.
:param images: A 2D array of shape (number_of_images, 784), where each row is a flattened 28x28 image.
:return: A 2D array of the same shape as input, containing the deskewed images.
"""
# Reshape the flattened images to 28x28
num_images = images.shape[0]
reshaped_images = images.reshape(num_images, 28, 28)
deskewed_images = np.array([deskew_image(image) for image in reshaped_images])
return deskewed_images.reshape(num_images, 28*28)SMO.py
import numpy as np
import random
import matplotlib.pyplot as plt
def load_data_set(file_name):
"""
Load dataset from file.
Parameters:
file_name (str): The name of the file containing the dataset.
Returns:
data_matrix (list): A list of feature vectors.
label_matrix (list): A list of class labels corresponding to feature vectors.
"""
data_matrix = []
label_matrix = []
with open(file_name, 'r') as file:
for line in file.readlines():
line_array = line.strip().split('\t')
data_matrix.append([float(line_array[0]), float(line_array[1])])
label_matrix.append(float(line_array[2]))
return data_matrix, label_matrix
def select_random_j(i, m):
"""
Randomly select index j, such that j is not equal to i.
Parameters:
i (int): The first index.
m (int): The total number of alpha parameters.
Returns:
j (int): The second index, different from i.
"""
j = i
while j == i:
j = int(random.uniform(0, m))
return j
def clip_alpha(aj, h, l):
"""
Clip the alpha value within the range [L, H].
Parameters:
aj (float): The alpha value to clip.
h (float): The upper bound.
l (float): The lower bound.
Returns:
aj (float): The clipped alpha value.
"""
if aj > h:
aj = h
if l > aj:
aj = l
return aj
def simple_smo(data_matrix_in, class_labels, c, tolerance, max_iter):
"""
Simplified SMO algorithm for SVM training.
Parameters:
data_matrix_in (list): The data matrix.
class_labels (list): The class labels.
c (float): The slack variable.
tolerance (float): The tolerance value for stopping criterion.
max_iter (int): Maximum number of iterations.
Returns:
b (float): Threshold for solution.
alphas (np.array): Lagrange multipliers.
"""
data_matrix = np.mat(data_matrix_in)
label_matrix = np.mat(class_labels).transpose()
b = 0
m, n = np.shape(data_matrix)
alphas = np.mat(np.zeros((m, 1)))
iter_num = 0
while iter_num < max_iter:
alpha_pairs_changed = 0
for i in range(m):
fXi = float(np.multiply(alphas, label_matrix).T * (data_matrix * data_matrix[i, :].T)) + b
Ei = fXi - float(label_matrix[i])
# Check if the alpha pair violates the KKT conditions
if ((label_matrix[i] * Ei < -tolerance) and (alphas[i] < c)) or ((label_matrix[i] * Ei > tolerance) and (alphas[i] > 0)):
j = select_random_j(i, m)
fXj = float(np.multiply(alphas, label_matrix).T * (data_matrix * data_matrix[j, :].T)) + b
Ej = fXj - float(label_matrix[j])
# Save the old alphas
alpha_i_old = alphas[i].copy()
alpha_j_old = alphas[j].copy()
# Calculate the bounds L and H
if label_matrix[i] != label_matrix[j]:
L = max(0, alphas[j] - alphas[i])
H = min(c, c + alphas[j] - alphas[i])
else:
L = max(0, alphas[j] + alphas[i] - c)
H = min(c, alphas[j] + alphas[i])
if L == H:
print("L == H")
continue
# Calculate eta
eta = 2.0 * data_matrix[i, :] * data_matrix[j, :].T - data_matrix[i, :] * data_matrix[i, :].T - data_matrix[j, :] * data_matrix[j, :].T
if eta >= 0:
print("eta >= 0")
continue
# Update alpha_j
alphas[j] -= label_matrix[j] * (Ei - Ej) / eta
# Clip alpha_j
alphas[j] = clip_alpha(alphas[j], H, L)
if abs(alphas[j] - alpha_j_old) < 0.00001:
print("j not moving enough")
continue
# Update alpha_i
alphas[i] += label_matrix[j] * label_matrix[i] * (alpha_j_old - alphas[j])
# Update b
b1 = b - Ei - label_matrix[i] * (alphas[i] - alpha_i_old) * data_matrix[i, :] * data_matrix[i, :].T - label_matrix[j] * (alphas[j] - alpha_j_old) * data_matrix[i, :] * data_matrix[j, :].T
b2 = b - Ej - label_matrix[i] * (alphas[i] - alpha_i_old) * data_matrix[i, :] * data_matrix[j, :].T - label_matrix[j] * (alphas[j] - alpha_j_old) * data_matrix[j, :] * data_matrix[j, :].T
if 0 < alphas[i] < c:
b = b1
elif 0 < alphas[j] < c:
b = b2
else:
b = (b1 + b2) / 2.0
# Increment the number of alpha pairs changed
alpha_pairs_changed += 1
print(f"Iteration number: {iter_num}, sample: {i}, alpha pairs changed: {alpha_pairs_changed}")
if alpha_pairs_changed == 0:
iter_num += 1
else:
iter_num = 0
print(f"Number of iterations: {iter_num}")
return b, alphas
def calculate_w(data_matrix, label_matrix, alphas):
"""
Calculate the weights w.
Parameters:
data_matrix (list): The data matrix.
label_matrix (list): The class labels.
alphas (np.array): The Lagrange multipliers.
Returns:
w (list): The weight vector.
"""
alphas, data_matrix, label_matrix = np.array(alphas), np.array(data_matrix), np.array(label_matrix)
w = np.dot((np.tile(label_matrix.reshape(1, -1).T, (1, 2)) * data_matrix).T, alphas)
return w.tolist()
def visualize_classifier(data_matrix, w, b):
"""
Visualize the classification result.
Parameters:
data_matrix (list): The data matrix.
w (list): The weight vector.
b (float): The bias term.
"""
# Separate positive and negative samples
data_positive = [data_matrix[i] for i in range(len(data_matrix)) if label_matrix[i] > 0]
data_negative = [data_matrix[i] for i in range(len(data_matrix)) if label_matrix[i] <= 0]
data_positive = np.array(data_positive)
data_negative = np.array(data_negative)
# Plot positive samples
plt.scatter(data_positive[:, 0], data_positive[:, 1], s=30, alpha=0.7)
# Plot negative samples
plt.scatter(data_negative[:, 0], data_negative[:, 1], s=30, alpha=0.7)
# Plot the decision boundary
x1 = max(data_matrix)[0]
x2 = min(data_matrix)[0]
a1, a2 = w
b = float(b)
a1 = float(a1[0])
a2 = float(a2[0])
y1, y2 = (-b - a1 * x1) / a2, (-b - a1 * x2) / a2
plt.plot([x1, x2], [y1, y2])
# Highlight support vectors
for i, alpha in enumerate(alphas):
if abs(alpha) > 0:
x, y = data_matrix[i]
plt.scatter([x], [y], s=150, c='none', alpha=0.7, linewidth=1.5, edgecolor='red')
# Show the plot
plt.show()
data_matrix, label_matrix = load_data_set('testSet.txt')
b, alphas = simple_smo(data_matrix, label_matrix, 0.6, 0.001, 40)
w = calculate_w(data_matrix, label_matrix, alphas)
visualize_classifier(data_matrix, w, b)7.2 Original Logs
See in attachments.










