跳到正文

个人记录

Report on SVM with Kernal Trick Classifying MNIST Dataset

DarkMoon_Dragon约 125 分钟
原文
文章信息与版本

文章信息

发布
2023年8月29日
收录
2025年12月12日
更新
2026年11月10日
篇幅
约 125 分钟
获赞
2

版本

  1. v1当前

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 00 to 99. Each image is 2828 pixels in height and 2828 pixels in width, with a total of 784784 pixels. The pixel values range from 00 to 255255, where 00 represents the color white, and 255255 represents black.

  • Some MNIST images

    Some images in MNIST dataset. The whole dataset contains 70,000 28×28 ...

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 XX of dimensions N×dN \times d, where NN is the number of samples and d=784d=784 is the number of features (in this case, pixels). The covariance matrix of XX is given by:

C=1N∑i=1N(xi−μ)(xi−μ)⊤C = \frac{1}{N} \sum_{i=1}^{N} (\mathbf x_i - \mu)(\mathbf x_i - \mu)^\top

where xi\mathbf x_i is the ithi^{th} sample and μ\mu 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 CC, and the amount of variance they capture is represented by their corresponding eigenvalues. The principal components are sorted by their eigenvalues in decreasing order.

  • Projecting on the largest variance directions

    image-20230612215825996

In the study, PCA is applied to the MNIST dataset to reduce its dimensionality. The number of principal components is chosen such that 90%90\% of the total variance in the data is retained, which only 8787 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 A=UΣV⊤\mathbf A = \mathbf U\mathbf\Sigma \mathbf V^\top, thus we have:

A⊤A=(VΣ⊤U⊤)(UΣV⊤)=VΣ⊤ΣV⊤AA⊤=(UΣV⊤)(VΣ⊤U⊤)=UΣΣ⊤U⊤\begin{aligned} \mathbf A^\top \mathbf A &= (\mathbf V \mathbf \Sigma^\top \mathbf U^\top)(\mathbf U \mathbf \Sigma \mathbf V^\top) = \mathbf V \mathbf \Sigma^\top \mathbf \Sigma \mathbf V^\top\\ \mathbf A \mathbf A^\top &= (\mathbf U \mathbf \Sigma \mathbf V^\top)(\mathbf V \mathbf \Sigma^\top \mathbf U^\top) = \mathbf U \mathbf \Sigma \mathbf \Sigma^\top \mathbf U^\top \end{aligned}

Those two matrices are semi-definite, and are both of the shape QΛQ⊤\mathbf Q \mathbf \Lambda \mathbf Q^\top, where Σ2\mathbf \Sigma^2 is the eigenvalues of both A⊤A\mathbf A^\top \mathbf A and AA⊤\mathbf A \mathbf A^\top , i.e. σi=λi(AA⊤)=λi(A⊤A)\sigma_i = \lambda_i(\mathbf A \mathbf A^\top ) = \lambda_i (\mathbf A^\top \mathbf A). Note that V\mathbf V is exactly the eigenvectors of A⊤A\mathbf A^\top \mathbf A, and U\mathbf U is also exactly the eigenvectors of AA⊤\mathbf A \mathbf A^\top. Now consider the MNIST problem, mm is the dimention of samples, which is 784784, where nn is the number of samples which is much greater than m, i.e. m≪nm \ll n, which tells us (AA⊤)m×m(\mathbf A \mathbf A^\top)_{m\times m} is a small matrix. Consider:

A⊤=VΣU⊤  ⟹  A⊤uk=σkvk\mathbf A^\top = \mathbf V \mathbf \Sigma \mathbf U^\top \implies \mathbf A^\top \mathbf u_k = \sigma_k \mathbf v_k

Once U\mathbf U is calculated, we can derive V\mathbf V from the above equation, and then take the firsk kk entries of vi\mathbf v_i 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:

  1. 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:

    mij=∑x∑yxiyj⋅image(x,y)m_{ij} = \sum_x \sum_y x^i y^j \cdot image(x, y)

    where mijm_{ij} is the (i,j)(i,j)-th moment, and xx and yy are the spatial coordinates of the image.

  2. 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:

    A=[10α1],  α=Cov(X,Y)Var(X)A = \begin{bmatrix} 1 & 0 \\ \alpha & 1 \end{bmatrix} , \;\alpha = \frac{Cov(X,Y)}{Var(X)}

    Then, the image is transformed using this affine transform matrix.

  3. 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 D={(x1,y1),(x2,y2),…,(xN,yN)}\mathcal D = \{(\mathbf x_1,y_1),(\mathbf x_2,y_2),\ldots,(\mathbf x_N,y_N)\}, where xi∈RD\mathbf x_i \in \mathbb R^D and yi=±1y_i = \pm 1, 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 2d2d.

  • image-20230612232400219

The distance from sample xi\mathbf x_i to the boundary is ri=∣w⊤xi+b∣∣∣w∣∣r_i = \dfrac{|\mathbf w^\top \mathbf x_i + b|}{||\mathbf w||}. 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 2d2d. 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:

ri=∣w⊤xi+b∣∣∣w∣∣≥d  ⟺  yi(w⊤xi+b)∣∣w∣∣≥dr_i = \dfrac{|\mathbf w^\top \mathbf x_i + b|}{||\mathbf w||} \ge d \iff \dfrac{y_i(\mathbf w^\top \mathbf x_i + b)}{||\mathbf w||} \ge d

For every support vector xs\mathbf x_s, the inequality turns into an equality, and in such cases, rsr_s should be:

rs=ys(w⊤xs+b)∣∣w∣∣=1∣∣w∣∣r_s = \dfrac{y_s(\mathbf w^\top \mathbf x_s + b)}{||\mathbf w||} = \frac{1}{||\mathbf w||}

As we should only focus on the support vectors, the margin can be expressed as:

2d=2∣∣w∣∣2d = \frac{2}{||\mathbf w||}

We can then formulate a quadratic optimization problem as:

arg⁡max⁡w,b  2∣∣w∣∣subject to yi(w⊤xi+b)≥1,  i=1,2,…,N\mathop{\arg \max}_{\mathbf w, b} \; \frac{2}{||\mathbf w||} \\\text{subject to } y_i(\mathbf w^\top \mathbf x_i+b) \ge 1, \; i=1,2,\ldots,N

This is equivalent to:

arg⁡max⁡w,b  ∣∣w∣∣22subject to yi(w⊤xi+b)≥1,  i=1,2,…,N\mathop{\arg \max}_{\mathbf w, b} \; \frac{||\mathbf w||^2}{2}\\\text{subject to } y_i(\mathbf w^\top \mathbf x_i+b) \ge 1, \; i=1,2,\ldots,N

We construct the Lagrangian corresponding to the problem above:

L(w,b,α,x)=∣∣w∣∣22+∑i=1Nαi(1−yi(w⊤xi+b)),where w,x∈Rd,b∈R,α∈R+N\mathcal L (\mathbf w, b, \alpha, \mathbf x) = \frac{||\mathbf w||^2}{2} + \sum_{i=1}^N \alpha_i \left(1-y_i(\mathbf w^\top \mathbf x_i + b)\right), \\\text{where } \mathbf w,\mathbf x \in \mathbb R^d, b\in \mathbb R , \alpha \in \mathbb R_+^{N}

We then calculate the derivatives of the Lagrange function for min⁡w,bL\min_{\mathbf w,b} \mathcal L:

{∂L∂w=0  ⟹  w=∑i=1Nαiyixi∂L∂b=0  ⟹  ∑i=1Nαiyi=0\begin{cases} \begin{aligned} \frac{\partial \mathcal L}{\partial \mathbf w}&=0 \implies \mathbf w = \sum_{i=1}^N \alpha_i y_i \mathbf x_i \\ \frac{\partial \mathcal L}{\partial b}&=0 \implies \sum_{i=1}^N \alpha_i y_i=0 \\ \end{aligned} \end{cases}

Substituting into L\mathcal L:

min⁡w,b  Lα,x,y(w,b)=−12∣∣w∣∣2+∑i=1Nαi=−12∑i=1N∑j=1Nαiαjyiyj(xi⊤xj)+∑i=1Nαisubject to ∑i=1Nαi⋅yi=0,  αi≥0  (i=1,2,…,N)\begin{aligned} \mathop{\min}_{\mathbf w, b}\; &\mathcal L_{\alpha,\mathbf x, y} (\mathbf w, b) = -\frac{1}{2} ||\mathbf w||^2 + \sum_{i=1}^N \alpha_i \\ &= - \frac{1}{2} \sum_{i=1}^N \sum_{j=1}^N \alpha_i \alpha_j y_i y_j (\mathbf x_i^\top \mathbf x_j) + \sum_{i=1}^N \alpha_i \\ \text{subject to } & \sum_{i=1}^N \alpha_i \cdot y_i = 0, \; \alpha_i \ge 0 \; (i=1,2,\ldots,N) \end{aligned}

We have thus constructed the dual form of the primal problem:

max⁡αi≥0  qx,y(α)=(−12∑i=1N∑j=1Nαiαjyiyj(xi⊤xj)+∑i=1Nαi)subject to ∑i=1Nαi⋅yi=0,  αi≥0  (i=1,2,…,N)\mathop{\max}_{\alpha_i \ge 0}\; q_{\mathbf x, y}(\alpha) = \left(- \frac{1}{2} \sum_{i=1}^N \sum_{j=1}^N \alpha_i \alpha_j y_i y_j (\mathbf x_i^\top \mathbf x_j) + \sum_{i=1}^N \alpha_i\right) \\ \text{subject to } \sum_{i=1}^N \alpha_i \cdot y_i = 0, \; \alpha_i \ge 0 \; (i=1,2,\ldots,N)

Let α∗=(α1∗,α2∗,…,αN∗)\alpha^* = (\alpha_1^*, \alpha_2^*, \ldots, \alpha_N^*) be the optimal solution of the dual problem. The solution to the primal problem is then given by:

w∗=∑i=1Nαi∗yixi\mathbf w^* = \sum_{i=1}^{N} \alpha_i^* y_i \mathbf x_i
  • The optimal coefficient is a linear combination of the samples.

However, deriving the optimal b∗b^* is not straightforward. It is verified that this problem satisfies the Karush-Kuhn-Tucker conditions, which indicate that:

αi∗(1−yi(w⊤xi∗+b∗))=0,  i=1,2,…,N\alpha_i^* \left( 1-y_i (\mathbf w^\top \mathbf x_i^* + b^*) \right) = 0, \;i=1,2,\ldots,N

As we are maximizing q(α)q(\alpha), if yi(w⊤xi∗+b∗)≥1y_i(\mathbf w^\top \mathbf x_i^* + b^*) \ge 1, then αi\alpha_i must be zero. This implies that those samples are distant from the decision boundary. The samples for which yi(w⊤xi∗+b∗)=1y_i(\mathbf w^\top \mathbf x_i^* + b^*)=1, making αi\alpha_i 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 b∗b^* values for which αi∗\alpha_i^* is greater than zero and take the average. Therefore:

b∗=Eαj∗>0[yj−∑i=1Nαi∗yi(xi⊤xj)]b^* = E _{\alpha_j^* >0}\left[ y_j - \sum_{i=1}^N \alpha_i^* y_i (\mathbf x_i^\top \mathbf x_j) \right]

We can find the optimal αi∗\alpha_i^* using the Sequential Minimal Optimization (SMO) Algorithm. This, in turn, allows us to determine the solutions for w∗\mathbf w^* and b∗b^*.

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 ξ\xi and a regularization parameter CC, leading to the following constraint:

yi(w⊤xi+b)≥1−ζi,  i=1,2,…,Ny_i (\mathbf w^\top \mathbf x_i + b) \ge 1 - \zeta_i, \;i=1,2,\ldots,N

The objective then becomes minimizing ∣∣w∣∣2/2+C∑ζi||\mathbf w||^2/2 + C\sum \zeta_i, 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., K(xi,xj)=xi⊤xjK(\mathbf x_i, \mathbf x_j) = \mathbf x_i^\top \mathbf x_j. 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 CC set to 1.01.0 and employs L2L_2 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:

min⁡w,b,ζ12w⊤w+C∑i=1nζisubject to yiw⊤ϕ(xi)+b)≥1−ζi,ζi≥0,i=1,2,...,n\min_ {\mathbf w, b, \zeta} \frac{1}{2} \mathbf w^\top \mathbf w + C \sum_{i=1}^{n} \zeta_i\\ \begin{split} \textrm {subject to } & y_i \mathbf w^\top \phi (\mathbf x_i) + b) \geq 1 - \zeta_i,\\ & \zeta_i \geq 0, i=1,2, ..., n \end{split}

The dual problem to the primal is:

min⁡α12α⊤Qα−e⊤αsubject to y⊤α=00≤αi≤C,i=1,2...,n\min_{\alpha} \frac{1}{2} \alpha^\top Q \alpha - \mathbf e^\top \alpha\\ \begin{split} \textrm {subject to } & \mathbf y^\top \alpha = 0\\ & 0 \leq \alpha_i \leq C, i=1,2 ..., n \end{split}

where e\mathbf e is the vector of all ones, and QQ is an nn by nn positive semidefinite matrix, Qij≡yiyjK(xi,xj)Q_{ij} \equiv y_i y_j K(\mathbf x_i, \mathbf x_j), where K(xi,xj)=ϕ(xi)⊤ϕ(xj)K(\mathbf x_i, \mathbf x_j) = \phi (\mathbf x_i)^\top \phi (\mathbf x_j) is the kernel. The terms αi\alpha_i are called the dual coefficients, and they are upper-bounded by CC. 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 x\mathbf x becomes:

∑i∈SVyiαi⋅K(xi,x)+b\sum_{i\in SV} y_i \alpha_i \cdot K(\mathbf x_i, \mathbf x) + b

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 αi\alpha_i are zero for the other samples.

  • Note: In Scikit Library, These parameters can be accessed through the attributes dual_coef_ which holds the product, support_vectors_ which holds the support vectors, and intercept_ 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 O(nfeatures×nsamples2)\mathcal O(n_{\text{features}} \times n_{\text{samples}}^2) and O(nfeatures×nsamples3)\mathcal O(n_{\text{features}} \times n_{\text{samples}}^3) 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:

K(x,y)=x⊤yK(\mathbf x, \mathbf y) = \mathbf x^\top \mathbf y

Polynomial:

The polynomial kernel is another kernel function defined as:

K(x,y)=(γ⋅x⊤y+r)dK(\mathbf x, \mathbf y) = \left(\gamma \cdot \mathbf x^\top \mathbf y + r\right)^d

where γ\gamma is a scale factor, rr is the coefficient term (coef0), and dd 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:

K(x,y)=exp⁡(−γ⋅∣∣x−y∣∣2)K(\mathbf x, \mathbf y) = \exp\left(-\gamma \cdot||\mathbf x- \mathbf y||^2 \right)

where γ\gamma 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:

![image-20230613184330526](Report English Version.assets/image-20230613184330526.png)

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:

    Accuracy=True Positives + True NegativesTrue Positives + False Positives + True Negatives + False Negatives\text{Accuracy} = \frac{\text{True Positives + True Negatives}} { \text{True Positives + False Positives + True Negatives + False Negatives}}
  • 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:

    F1 Score=2⋅Precision×RecallPrecision + Recall\text{F1 Score} = 2 \cdot \frac{\text{Precision} \times \text{Recall}} {\text{Precision + Recall}}

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:

LibraryVersionDescription
python3.9.16The programming language used for implementing the machine learning models and data processing.
numpy1.23.5A library for Python that adds support for large, multi-dimensional arrays and matrices.
scikit-learn1.2.2A machine learning library for Python. It features various classification, regression and clustering algorithms including support vector machines.
matplotlib3.7.1A 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.

![image-20230613184330526](Report English Version.assets/image-20230613184330526.png)

![image-20230613184243752](Report English Version.assets/image-20230613184243752.png)

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

![svm_performance](Report English Version.assets/svm_performance.svg)

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:

170958643

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

  1. 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.
  2. Parameter Tuning: The analysis relied on a select range of values for the hyperparameters such as C and gamma. 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.
  3. 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.
  4. 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 :(

  1. Platt, J. “Probabilistic outputs for SVMs and comparisons to regularized likehood methods.” Advances in Large Margin Classifiers. MIT Press, 1999.
  2. 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).
  3. Smola, Alex J., and Bernhard Schölkopf. “A tutorial on support vector regression.” Statistics and computing 14 (2004): 199-222.
  4. 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.
  5. https://scikit-learn.org/stable/modules/svm.html#complexity
  6. https://www.csie.ntu.edu.tw/~cjlin/libsvm/

7. Appendices

7.1 Python Code

main.py

Python
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

Python
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, clf

initialization.py

Python
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

Python
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.

原文