{
  "id": "svm-knn",
  "module": "math-ml",
  "level": 2,
  "minutes": 40,
  "audiences": [
    "developer",
    "researcher"
  ],
  "software": [],
  "text": {
    "en": {
      "title": "Linear Models, Support Vector Machines and Nearest Neighbours: The Perceptron, Margins, the Kernel Trick and kNN",
      "description": "Linear classifiers and nearest-neighbour methods for machine-learning practice: the perceptron and linear separability, Ridge and Lasso regularisation, maximum-margin and soft-margin support vector machines, the kernel trick (especially the RBF kernel and gamma), when naive Bayes is appropriate, and the link between k-nearest neighbours and approximate vector search. The lesson follows the original papers and official documentation from scikit-learn, LIBSVM, Faiss, CS229 and ISLP, and reports a reproducible comparison of accuracy and prediction time on handwritten digits.",
      "updated": "2026-11-30",
      "takeaways": [
        "The perceptron updates its weights when a training point is misclassified and, if the training set is linearly separable, reaches a separating hyperplane in a finite number of steps. If the data are not linearly separable, the procedure does not settle on a separator, so implementations impose a limit on the number of iterations. On a linearly separable two-dimensional toy set in this lesson, Perceptron reached training accuracy 1.0 in 11 iterations; on concentric circles the training accuracy was 0.50.",
        "Ridge adds an ℓ₂ penalty on the coefficients to squared error, shrinking them and reducing sensitivity to collinearity. Lasso uses an ℓ₁ penalty, which can set some coefficients exactly to zero and thereby select features. The role of regularisation is discussed in the lesson on overfitting and generalisation. On the same handwritten-digit split, L2 logistic regression had 40 zero coefficients (from four constant pixels) and L1 logistic regression had 281.",
        "A support vector machine finds a separating hyperplane with the largest margin; the decision function depends only on the support vectors. When the data are not strictly linearly separable, the soft-margin formulation uses slack variables and a penalty C to allow some points to lie inside the margin or to be misclassified. Smaller C means stronger regularisation and a smoother decision surface.",
        "The kernel trick evaluates inner products in a feature space through a kernel, without forming the feature map explicitly. The RBF kernel is exp(−γ‖x−x′‖²). If γ is too large, the region of influence of a support vector shrinks to the vector itself, and regularisation through C cannot prevent overfitting. On standardised digits, the default γ='scale' (about 0.01667) had test accuracy 0.9861; at γ=1 the training accuracy was 1.0000 and the test accuracy fell to 0.1222.",
        "k-nearest neighbours assigns a query the majority label among its k closest training points. Training mostly stores the data; prediction computes distances. Cover and Hart (1967) proved that, in the large-sample limit, the error of the nearest-neighbour rule is at most twice the Bayes error. On the same split, a linear-kernel SVM, an RBF-kernel SVM and 5-NN had test accuracies 0.9778, 0.9861 and 0.9806; mean prediction times for the 360 test points were 2.425 ms, 10.632 ms and 87.119 ms."
      ],
      "faq": [
        {
          "q": "Which training points determine an SVM’s decision boundary?",
          "a": "The support vectors: the training points that lie on the margin boundary or inside the margin. Dual coefficients are zero for the remaining points, so the decision function is a sum over support vectors only. On the standardised digits split in this lesson, the linear-kernel SVM had 437 support vectors and the RBF-kernel SVM (γ='scale') had 710."
        },
        {
          "q": "What are the training and prediction costs of kNN, and how did prediction times compare in this lesson?",
          "a": "Training is little more than storing the samples (the mean of five fits in this lesson was about 0.49 ms). Prediction must compute distances to the training set, or query a KD-tree or ball-tree index. Over 100 repeats on the 360 test points, mean prediction time was 2.425 ms for the linear-kernel SVM, 10.632 ms for the RBF-kernel SVM, and 87.119 ms for 5-NN."
        },
        {
          "q": "What happens if the RBF kernel’s gamma is too large?",
          "a": "The official scikit-learn example on RBF parameters states that if γ is too large, the radius of influence of each support vector includes only the vector itself, and no amount of regularisation with C will prevent overfitting. In this lesson, γ=1 gave training accuracy 1.0000 and test accuracy 0.1222, with 1437 support vectors (the entire training set); at γ=10 the test accuracy was 0.1028, close to the 0.1 accuracy of uniform guessing among ten classes."
        },
        {
          "q": "How do the Ridge and Lasso penalties differ, and why can Lasso select features?",
          "a": "Ridge minimises ‖Xw−y‖₂²+α‖w‖₂², shrinking coefficients towards zero but generally not setting them exactly to zero. Lasso replaces the penalty with α‖w‖₁, which can drive some coefficients to zero and yield a sparse solution. On the same split, L2 logistic regression had 40 zero coefficients (four constant pixels times ten classes) and L1 logistic regression had 281."
        },
        {
          "q": "What is the “naive” assumption in naive Bayes, and when is the method still useful?",
          "a": "Conditional independence of the features given the class. The assumption is rarely true, but naive Bayes remains common for document classification and spam filtering, because each class-conditional distribution can be estimated separately and both training and prediction are fast. On standardised digits in this lesson, GaussianNB had test accuracy 0.7750, below the SVMs and kNN: neighbouring pixels are not independent, and a product of univariate Gaussians is a poor model of an image."
        }
      ],
      "sources": [
        {
          "title": "scikit-learn user guide: 1.4 Support Vector Machines (margins, support vectors, soft margin, kernels, C and scaling)",
          "url": "https://scikit-learn.org/stable/modules/svm.html"
        },
        {
          "title": "scikit-learn example: RBF SVM parameters (C and gamma)",
          "url": "https://scikit-learn.org/stable/auto_examples/svm/plot_rbf_parameters.html"
        },
        {
          "title": "scikit-learn example: SVM kernels and decision boundaries",
          "url": "https://scikit-learn.org/stable/auto_examples/svm/plot_svm_kernels.html"
        },
        {
          "title": "scikit-learn user guide: 1.1 Linear Models (Ridge, Lasso)",
          "url": "https://scikit-learn.org/stable/modules/linear_model.html"
        },
        {
          "title": "scikit-learn example: Lasso path using coordinate descent",
          "url": "https://scikit-learn.org/stable/auto_examples/linear_model/plot_lasso_coordinate_descent_path.html"
        },
        {
          "title": "scikit-learn API: Perceptron",
          "url": "https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.Perceptron.html"
        },
        {
          "title": "scikit-learn user guide: 1.9 Naive Bayes",
          "url": "https://scikit-learn.org/stable/modules/naive_bayes.html"
        },
        {
          "title": "scikit-learn user guide: 1.6 Nearest Neighbors",
          "url": "https://scikit-learn.org/stable/modules/neighbors.html"
        },
        {
          "title": "scikit-learn example: nearest-neighbours classification",
          "url": "https://scikit-learn.org/stable/auto_examples/neighbors/plot_classification.html"
        },
        {
          "title": "scikit-learn example gallery",
          "url": "https://scikit-learn.org/stable/auto_examples/index.html"
        },
        {
          "title": "scikit-learn API: load_digits",
          "url": "https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html"
        },
        {
          "title": "scikit-learn API: StandardScaler",
          "url": "https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html"
        },
        {
          "title": "scikit-learn API: SVC",
          "url": "https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html"
        },
        {
          "title": "scikit-learn API: KNeighborsClassifier",
          "url": "https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html"
        },
        {
          "title": "Cortes and Vapnik (1995), Support-vector networks, Machine Learning (DOI 10.1007/BF00994018)",
          "url": "https://link.springer.com/article/10.1007/BF00994018"
        },
        {
          "title": "Cover and Hart (1967), Nearest neighbor pattern classification, IEEE Transactions on Information Theory (author PDF, Stanford ISL)",
          "url": "https://isl.stanford.edu/~cover/papers/transIT/0021cove.pdf"
        },
        {
          "title": "Rosenblatt (1958), The perceptron: A probabilistic model for information storage and organization in the brain., Psychological Review (DOI 10.1037/h0042519)",
          "url": "https://doi.org/10.1037/h0042519"
        },
        {
          "title": "Tibshirani, The Lasso Page (author page, citing the 1996 JRSS-B paper)",
          "url": "https://tibshirani.su.domains/lasso.html"
        },
        {
          "title": "Domingos and Pazzani (1997), On the Optimality of the Simple Bayesian Classifier under Zero-One Loss, Machine Learning (author PDF)",
          "url": "https://homes.cs.washington.edu/~pedrod/papers/mlj97.pdf"
        },
        {
          "title": "Domingos and Pazzani (1997), Machine Learning journal page (DOI 10.1023/A:1007413511361)",
          "url": "https://link.springer.com/article/10.1023/A:1007413511361"
        },
        {
          "title": "Douze et al., The Faiss library, arXiv:2401.08281",
          "url": "https://arxiv.org/abs/2401.08281"
        },
        {
          "title": "facebookresearch/faiss (official repository)",
          "url": "https://github.com/facebookresearch/faiss"
        },
        {
          "title": "LIBSVM home page (Chang and Lin)",
          "url": "https://www.csie.ntu.edu.tw/~cjlin/libsvm/"
        },
        {
          "title": "cjlin1/libsvm (official LIBSVM GitHub repository)",
          "url": "https://github.com/cjlin1/libsvm"
        },
        {
          "title": "Stanford CS229 Machine Learning",
          "url": "https://cs229.stanford.edu/"
        },
        {
          "title": "Stanford CS229 course notes (PDF)",
          "url": "https://cs229.stanford.edu/main_notes.pdf"
        },
        {
          "title": "An Introduction to Statistical Learning (ISLP, free textbook)",
          "url": "https://www.statlearning.com/"
        },
        {
          "title": "ISLP official Python resources and labs",
          "url": "https://www.statlearning.com/resources-python"
        },
        {
          "title": "intro-stat-learning/ISLP_labs (official Python lab repository, stable branch)",
          "url": "https://github.com/intro-stat-learning/ISLP_labs/tree/stable"
        }
      ],
      "url": "https://aimap.page/en/learn/math-ml/svm-knn/",
      "markdown": "**Overview.** Linear models score examples with a hyperplane; nearest-neighbour methods query the training set directly. This lesson proceeds from the perceptron and linear separability, through Ridge and Lasso regularisation, maximum-margin and soft-margin support vector machines, the kernel trick, naive Bayes, and k-nearest neighbours and vector search, to a comparison on handwritten digits. Every experimental figure comes from the runnable example at the end of the lesson, run with scikit-learn 1.9.1, NumPy 2.5.4 and Python 3.13.5, with random seed 0.\n\nThe lesson belongs to the unit [Linear Models, SVM and Nearest Neighbours](/learn/unit/u22-svm-knn). Recommended preparation is [Overfitting, Generalisation and Data Splits](/learn/generalization) and [Linear Algebra for AI](/learn/linear-algebra), together with the discussion of losses and parameter updates in [How Machines Learn: Loss Functions and Gradient Descent](/learn/ml-basics). Related algorithm cards: [Perceptron](/learn/algorithms/perceptron), [Support Vector Machine](/learn/algorithms/svm), [k-Nearest Neighbors](/learn/algorithms/knn), [Regularised Regression (Lasso / Ridge)](/learn/algorithms/lasso) and [Naive Bayes](/learn/algorithms/naive-bayes).\n\n## The perceptron and linear separability\n\nRosenblatt (1958) published the perceptron in *Psychological Review*: a weighted sum of features is compared with a threshold to make a binary decision, an early model of an artificial neuron. The error-driven update taught today can be described as follows. If the current parameters misclassify a training point, that point’s feature vector is added to (or subtracted from) the weight vector, moving the decision surface in a direction that corrects the mistake.\n\nIf the training data are linearly separable—if some hyperplane places the two classes on opposite sides—this update finds a separating hyperplane in a finite number of steps. If the data are not linearly separable, the updates do not settle on a separator, which is why scikit-learn’s `Perceptron` imposes a stopping condition such as `max_iter`. In this lesson, `make_classification` was used to draw 40 two-dimensional points with a large class separation (`random_state=0`); `Perceptron` reached training accuracy 1.0 in 11 iterations. `make_circles` was then used to draw 200 noisy concentric circles (`noise=0.08`, `factor=0.4`, `random_state=0`). On that training set the perceptron had accuracy 0.50, a linear-kernel SVM had accuracy 0.62, and an RBF-kernel SVM had accuracy 1.00. These last figures are training accuracies on a toy set, with no held-out split; they illustrate that a linear surface cannot cut two nested classes apart, whereas a kernel method can separate them in a feature space.\n\nThe perceptron’s separator need not be the one that stays as far as possible from both classes. The next section reviews regularisation in linear models, and the following section turns to support vector machines, which take the maximum margin as their objective.\n\n## Linear models, Lasso and Ridge\n\nLinear regression minimises the residual sum of squares. When features are collinear, or when the number of features is comparable to the number of samples, ordinary least-squares coefficients can become large and sensitive to perturbations. The lesson on [overfitting, generalisation and data splits](/learn/generalization) treats regularisation as a family of devices that limit a model’s effective complexity and reduce variance.\n\nRidge regression, introduced by Hoerl and Kennard (1970)—title and authors verified via Crossref on the day this lesson was written, DOI 10.1080/00401706.1970.10488634; the publisher’s page returned HTTP 403 to automated requests, so the formula below follows the scikit-learn user guide—adds an ℓ₂ penalty on the coefficients to squared error:\n\n\\[\\min_{w}\\ \\|Xw-y\\|_2^2 + \\alpha \\|w\\|_2^2.\\]\n\nThe complexity parameter \\(\\alpha \\ge 0\\) controls the amount of shrinkage: larger \\(\\alpha\\) pulls the coefficients towards zero and makes them more robust to collinearity. An ℓ₂ penalty shrinks coefficients but does not, in general, set them exactly to zero.\n\nThe Lasso (least absolute shrinkage and selection operator), proposed by Tibshirani (1996), replaces that penalty with the sum of absolute values. The author’s page defines the method as minimising the usual sum of squared errors subject to a bound on the sum of the absolute values of the coefficients. The equivalent objective in scikit-learn is\n\n\\[\\min_{w}\\ \\frac{1}{2n}\\|Xw-y\\|_2^2 + \\alpha \\|w\\|_1.\\]\n\nThe user guide states that the Lasso can set some coefficients exactly to zero, so that the solution depends on fewer features and performs feature selection. Coordinate descent is one standard algorithm; an official example plots the coefficient path as \\(\\alpha\\) varies.\n\nThe same ℓ₁ and ℓ₂ penalties can be added to linear classifiers such as logistic regression. On the standardised digits split used later in this lesson, `LogisticRegression` was run as a supplementary comparison (not the required unit project): with an L2 penalty the test accuracy was 0.9667 and 40 of the 640 coefficients were zero, matching the four constant pixels in this training split (indices 0, 24, 32 and 39) times ten classes; with an L1 penalty (`solver='saga'`, `C=1.0`) the test accuracy was 0.9694 and the number of zero coefficients rose to 281. On the same split, `RidgeClassifier` had test accuracy 0.9361 and `Perceptron` had test accuracy 0.9306.\n\nThe strength of regularisation is itself a hyperparameter and should be chosen with a validation set or with cross-validation, as discussed in the generalisation lesson. A linear model still produces a single global hyperplane. Choosing the *widest* such plane, in the sense of the margin, is the subject of support vector machines.\n\n## Margins, support vectors and soft-margin SVMs\n\nThe scikit-learn user guide describes a support vector machine (SVM) as constructing a hyperplane, or a set of hyperplanes, in a feature space so that the distance to the nearest training points of any class—the margin—is as large as possible. A larger margin is associated with a lower generalisation error. Training points that lie on the margin boundaries are called support vectors; when the problem is not strictly linearly separable, the support vectors also include points that lie *inside* the margin.\n\nCortes and Vapnik (1995), in *Support-vector networks*, formulated the soft-margin SVM that allows training errors, and used kernel functions in that setting. The primal problem solved by `SVC` in scikit-learn is\n\n\\[\n\\min_{w,b,\\zeta}\\ \\frac{1}{2}w^\\top w + C\\sum_{i=1}^{n}\\zeta_i\n\\quad\\text{s.t.}\\quad\ny_i\\bigl(w^\\top\\phi(x_i)+b\\bigr)\\ge 1-\\zeta_i,\\ \\zeta_i\\ge 0.\n\\]\n\nThe first term minimises \\(\\|w\\|^2\\) and is equivalent to maximising the margin. The slack variables \\(\\zeta_i\\) allow a point to lie on the wrong side of its margin boundary, or to be misclassified. The penalty \\(C\\) weights that cost and acts as an inverse regularisation parameter: smaller \\(C\\) means stronger regularisation and a smoother decision surface; larger \\(C\\) pushes the model towards classifying every training point correctly. The guide notes that the default \\(C=1\\) is a reasonable starting point, and that \\(C\\) should be decreased when the observations are noisy.\n\nIn the dual, the decision function is\n\n\\[\n\\sum_{i\\in\\mathrm{SV}} y_i\\alpha_i K(x_i,x)+b,\n\\]\n\na sum only over the support vectors; the remaining dual coefficients are zero. The decision boundary is therefore determined by the support vectors, not by every training point equally.\n\nFor a problem with \\(K\\) classes, `SVC` uses a one-versus-one strategy and trains \\(K(K-1)/2\\) binary classifiers. Handwritten digits have ten classes, so this produces 45 binary SVMs. The guide also stresses that SVM algorithms are not scale invariant: each feature should be scaled to a comparable range, and the transformation estimated on the training set must be applied to the test set, typically by wrapping `StandardScaler` and `SVC` in a `Pipeline`. scikit-learn’s `SVC` calls LIBSVM (Chang and Lin) internally.\n\nBoser, Guyon and Vapnik (1992) published *A training algorithm for optimal margin classifiers* at COLT (title, authors and year verified via Crossref, DOI 10.1145/130385.130401; the ACM page returned HTTP 403 to automated requests on the day this lesson was written). The 1995 soft-margin paper is the primary source cited here.\n\n## The kernel trick\n\nIf the two classes cannot be separated by a hyperplane in the input space, the points can be mapped into a higher-dimensional feature space and separated linearly there. The kernel trick applies whenever an algorithm depends on the data only through inner products: a kernel \\(K(x,x')=\\langle\\phi(x),\\phi(x')\\rangle\\) evaluates those inner products without forming \\(\\phi(x)\\) explicitly. The kernels provided by scikit-learn include:\n\n- the linear kernel \\(K(x,x')=\\langle x,x'\\rangle\\);\n- the polynomial kernel \\(K(x,x')=(\\gamma\\langle x,x'\\rangle+r)^d\\);\n- the radial basis function (RBF) kernel \\(K(x,x')=\\exp(-\\gamma\\|x-x'\\|^2)\\), with \\(\\gamma>0\\);\n- the sigmoid kernel \\(K(x,x')=\\tanh(\\gamma\\langle x,x'\\rangle+r)\\).\n\nThe RBF kernel is the nonlinear kernel most often used in practice. The guide states that \\(\\gamma\\) controls how far the influence of a single training example reaches: the larger \\(\\gamma\\), the closer another point must be in order to be affected. \\(C\\) and \\(\\gamma\\) should be chosen together, commonly with a grid of values spaced on a logarithmic scale. The official example *RBF SVM parameters* adds that if \\(\\gamma\\) is too large, the radius of the area of influence of the support vectors includes only the support vector itself, and no amount of regularisation with \\(C\\) will prevent overfitting; if \\(\\gamma\\) is very small, the model is too constrained and behaves like a linear model whose hyperplanes separate the high-density centres of each pair of classes.\n\nThis lesson fixed \\(C=1\\) on the standardised digits and varied \\(\\gamma\\). The default `gamma='scale'` equals \\(1/(n_{\\text{features}}\\cdot\\mathrm{Var}(X))\\) in scikit-learn; on this standardised training set that value is \\(0.01666\\ldots\\), because four constant features leave the overall variance at 0.9375 rather than 1.\n\n| γ | Training accuracy | Test accuracy | Support vectors |\n|---|---|---|---|\n| 0.001 | 0.9610 | 0.9417 | 1127 |\n| 0.01 | 0.9937 | 0.9806 | 713 |\n| scale (≈0.01667) | 0.9951 | 0.9861 | 710 |\n| 0.1 | 1.0000 | 0.9389 | 1194 |\n| 1.0 | 1.0000 | 0.1222 | 1437 |\n| 10 | 1.0000 | 0.1028 | 1437 |\n\nAt γ=1 and γ=10 the training accuracy is 1.0000, but the test accuracy falls to 0.1222 and 0.1028, and every one of the 1,437 training points is a support vector: the model is in effect memorising the training set and is close to guessing at random on unseen points (uniform guessing among ten classes has accuracy 0.1). That matches the official example’s account of overfitting when γ is too large. The default `gamma='scale'` had the highest test accuracy on this split (0.9861).\n\n## When naive Bayes is appropriate\n\nNaive Bayes applies Bayes’ theorem to the class posterior, together with the “naive” assumption that the features are conditionally independent given the class. This yields\n\n\\[\n\\hat y=\\arg\\max_y\\ P(y)\\prod_{i=1}^{n}P(x_i\\mid y).\n\\]\n\nThe variants differ mainly in the family used for \\(P(x_i\\mid y)\\): `GaussianNB` assumes a Gaussian distribution for each continuous feature in each class, `MultinomialNB` is intended for count features such as term frequencies or TF-IDF, and `BernoulliNB` is intended for binary features. The scikit-learn user guide notes that, despite the plainly over-simplified assumption, naive Bayes has worked well in many real applications, famously document classification and spam filtering. It needs relatively little data to estimate its parameters, and because each class-conditional distribution can be estimated as a one-dimensional distribution, training and prediction are fast and the method helps to alleviate difficulties that come with high dimension. The same guide warns that naive Bayes is a decent classifier but a poor probability estimator, so `predict_proba` should not be treated as a calibrated probability.\n\nDomingos and Pazzani (1997) published *On the Optimality of the Simple Bayesian Classifier under Zero-One Loss* (title, authors and year verified via Crossref; the author PDF and the journal page returned HTTP 200). The paper addresses optimality of the simple Bayesian classifier under zero-one loss; this lesson does not restate intermediate theorems that were not checked line by line in a machine-readable abstract.\n\nNaive Bayes is a good fit when the features can reasonably be modelled separately given the class, especially bag-of-words or n-gram counts. Images whose neighbouring pixels are strongly dependent are not a typical setting for Gaussian naive Bayes. On the same standardised digits split, `GaussianNB` had training accuracy 0.8135 and test accuracy 0.7750, below the SVMs and kNN reported below. For text, see the official 20 Newsgroups document-classification example.\n\n## k-nearest neighbours, distance, dimension and vector search\n\nk-nearest neighbours (kNN) is a non-parametric method: a query \\(x\\) is assigned the majority label among the \\(k\\) closest training points. Euclidean distance is the default; scikit-learn also allows votes to be weighted by the inverse of the distance. The user guide notes that, despite its simplicity, nearest neighbours has been successful on tasks including handwritten digits and satellite scenes, and is often effective when the decision boundary is highly irregular.\n\nCover and Hart (1967) analysed the nearest-neighbour rule (the case \\(k=1\\)). The abstract of the author PDF states that the rule does not depend on the underlying joint distribution of the points and their labels, so its error \\(R\\) cannot be smaller than the Bayes error \\(R^*\\); in a large-sample analysis, for any number of classes, the error of the nearest-neighbour rule is bounded above by twice the Bayes probability of error. The paper also points to earlier work by Fix and Hodges on a rule of the \\(k\\)-nearest-neighbour type. The bound is a large-sample theoretical result; it should not be read as a claim that the error on the 360 test points in this lesson is already twice the Bayes error.\n\nkNN has almost no training stage apart from storing the data, optionally in a KD-tree or a ball tree. Prediction must compute distances to many training points, or search those trees. As the dimension grows, distances become less discriminative; the guide also mentions the “curse of dimensionality” when discussing radius-neighbour rules in high-dimensional parameter spaces. For moderate sample sizes and moderate dimension, brute force, a KD-tree or a ball tree is usually enough. When the objects are large collections of vectors, such as embeddings, an approximate nearest neighbour (ANN) index is used instead. The Faiss library (Douze et al., arXiv:2401.08281) is a toolkit for vector similarity search: it indexes, clusters, compresses and transforms vectors in the setting of a vector database. That is the same nearest-neighbour idea at a different scale, not a drop-in replacement for scikit-learn’s `KNeighborsClassifier`.\n\n## A reproducible comparison on handwritten digits\n\nThe unit project is to classify handwritten digits with a linear-kernel SVM, an RBF-kernel SVM and kNN, and to compare accuracy and prediction speed. This lesson uses scikit-learn’s `load_digits`: 1,797 greyscale 8×8 images of digits, pixel values from 0 to 16, 64 features and 10 classes. The split is `train_test_split(..., test_size=0.2, random_state=0, stratify=y)`, giving 1,437 training points and 360 test points. A `StandardScaler` is fitted on the training set (zero mean, unit variance) and the same transformation is applied to the test set. The classifiers and their hyperparameters are:\n\n- `SVC(kernel='linear', C=1.0, random_state=0)`\n- `SVC(kernel='rbf', C=1.0, gamma='scale', random_state=0)`\n- `KNeighborsClassifier(n_neighbors=5, algorithm='auto', n_jobs=1)`\n\nPrediction time is the mean of 100 calls to `predict` on all 360 test points, after five warm-up calls. The software is scikit-learn 1.9.1, NumPy 2.5.4 and Python 3.13.5. Wall-clock times depend on the machine; accuracies should be reproducible with the same seed and the same software versions.\n\n| Model | Training accuracy | Test accuracy | Mean prediction time | Support vectors |\n|---|---|---|---|---|\n| Linear-kernel SVM | 1.0000 (1,437/1,437) | 0.9778 (352/360) | 2.425 ms | 437 |\n| RBF-kernel SVM | 0.9951 (1,430/1,437) | 0.9861 (355/360) | 10.632 ms | 710 |\n| kNN (k=5) | 0.9847 (1,415/1,437) | 0.9806 (353/360) | 87.119 ms | — |\n\nOn this split the RBF kernel has the highest test accuracy (0.9861), then kNN (0.9806), then the linear kernel (0.9778). For prediction, the linear kernel is the fastest; the RBF kernel takes about 4.4 times as long (10.632/2.425), and kNN about 35.9 times as long (87.119/2.425). The mean of five fits was 0.49 ms for kNN, 15.66 ms for the linear-kernel SVM and 26.77 ms for the RBF-kernel SVM, consistent with nearest-neighbour methods deferring almost all of the computation until prediction. Without standardisation, the test accuracies were 0.9722, 0.9833 and 0.9778, all slightly lower than after scaling, which agrees with the advice that SVMs are sensitive to feature scale and that distance-based methods are affected by the units of each coordinate.\n\nThese figures correspond only to the hyperparameters and the split above. They should not be read as “an RBF kernel is always more accurate than a linear kernel” or “kNN is always slower”. A different data set, or a different \\(C\\), \\(\\gamma\\) or \\(k\\), can change the ranking. In an application, hyperparameters should be chosen on a validation set, and an independent test set should be used only once.\n\n## Runnable example\n\n```python\nimport time\nimport numpy as np\nfrom sklearn.datasets import load_digits\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.svm import SVC\n\ndigits = load_digits()\nX_tr, X_te, y_tr, y_te = train_test_split(\n    digits.data, digits.target, test_size=0.2, random_state=0, stratify=digits.target\n)\nscaler = StandardScaler()\nX_tr = scaler.fit_transform(X_tr)\nX_te = scaler.transform(X_te)\n\nmodels = {\n    \"linear\": SVC(kernel=\"linear\", C=1.0, random_state=0),\n    \"rbf\": SVC(kernel=\"rbf\", C=1.0, gamma=\"scale\", random_state=0),\n    \"knn\": KNeighborsClassifier(n_neighbors=5, algorithm=\"auto\", n_jobs=1),\n}\nfor name, clf in models.items():\n    clf.fit(X_tr, y_tr)\n    train_acc = (clf.predict(X_tr) == y_tr).mean()\n    test_acc = (clf.predict(X_te) == y_te).mean()\n    for _ in range(5):\n        clf.predict(X_te)\n    times = []\n    for _ in range(100):\n        t0 = time.perf_counter()\n        clf.predict(X_te)\n        times.append(time.perf_counter() - t0)\n    n_sv = int(clf.n_support_.sum()) if hasattr(clf, \"n_support_\") else None\n    print(name, \"train\", round(train_acc, 4), \"test\", round(test_acc, 4),\n          \"pred_ms\", round(np.mean(times) * 1000, 3), \"n_sv\", n_sv)\n\nfor gamma in [0.001, 0.01, \"scale\", 0.1, 1.0, 10.0]:\n    clf = SVC(kernel=\"rbf\", C=1.0, gamma=gamma, random_state=0).fit(X_tr, y_tr)\n    print(\"gamma\", gamma, \"train\", round((clf.predict(X_tr) == y_tr).mean(), 4),\n          \"test\", round((clf.predict(X_te) == y_te).mean(), 4),\n          \"n_sv\", int(clf.n_support_.sum()))\n```\n\nThe measured figures of interest are: linear kernel, test accuracy 0.9778, prediction 2.425 ms, 437 support vectors; RBF kernel (`gamma='scale'`), test accuracy 0.9861, prediction 10.632 ms, 710 support vectors; kNN, test accuracy 0.9806, prediction 87.119 ms. At γ=1 the training accuracy was 1.0000, the test accuracy 0.1222 and the number of support vectors 1,437. Prediction times vary with the machine; the accuracies should be reproducible.\n\n## Exercises\n\n1. **Unit project.** Classify handwritten digits with SVMs (linear and RBF kernels) and with kNN, and compare accuracy and prediction speed. You may reuse the `load_digits` split and the standardisation in this lesson, or vary `C`, `gamma` or `n_neighbors` and select them on a validation set. Fix the random seed and record the software versions and every hyperparameter.\n2. Run the official scikit-learn examples on [SVM kernels](https://scikit-learn.org/stable/auto_examples/svm/plot_svm_kernels.html), [nearest-neighbours classification](https://scikit-learn.org/stable/auto_examples/neighbors/plot_classification.html) and the [Lasso coordinate-descent path](https://scikit-learn.org/stable/auto_examples/linear_model/plot_lasso_coordinate_descent_path.html), from the [example gallery](https://scikit-learn.org/stable/auto_examples/index.html). Change the kernel parameters, \\(k\\) or \\(\\alpha\\), and watch how the decision surface or the coefficient path changes. The example on [RBF values of C and gamma](https://scikit-learn.org/stable/auto_examples/svm/plot_rbf_parameters.html) is also useful.\n3. From the [ISLP Python resources page](https://www.statlearning.com/resources-python), or directly from the official repository [ISLP_labs (stable branch)](https://github.com/intro-stat-learning/ISLP_labs/tree/stable), complete the Python labs in the chapters on linear models, regularisation, support vector machines and nearest neighbours.\n\n## Suggested reading order\n\nStart with Ridge and Lasso in the [scikit-learn guide to linear models](https://scikit-learn.org/stable/modules/linear_model.html) and with the regularisation section of [Overfitting, Generalisation and Data Splits](/learn/generalization). Then read the practical advice, the RBF parameters and the mathematical formulation in the [support vector machines guide](https://scikit-learn.org/stable/modules/svm.html). For neighbours and retrieval, read the [nearest-neighbours guide](https://scikit-learn.org/stable/modules/neighbors.html) and the abstract of Cover and Hart (1967); for large-scale vector search continue to the [Faiss repository](https://github.com/facebookresearch/faiss) and Douze et al. (arXiv:2401.08281). A statistical-learning narrative is given in the free textbook [An Introduction to Statistical Learning](https://www.statlearning.com/) and in the [CS229 notes](https://cs229.stanford.edu/main_notes.pdf). Implementation details are in [LIBSVM](https://www.csie.ntu.edu.tw/~cjlin/libsvm/). From here one can continue to [Trees and Ensembles](/learn/tree-ensembles) or [Unsupervised Learning: Clustering, Dimensionality Reduction and EM](/learn/unsupervised-learning) in the same stage."
    },
    "zh-hans": {
      "title": "线性模型、支持向量机与近邻：感知机、间隔、核技巧与 kNN",
      "description": "面向机器学习实践的线性分类与近邻方法：感知机与线性可分、Ridge 与 Lasso 正则化、最大间隔与软间隔支持向量机、核技巧（尤其 RBF 与 gamma）、朴素贝叶斯的适用场景，以及 k 近邻与近似最近邻检索的联系。依据原始论文与 scikit-learn、LIBSVM、Faiss、CS229、ISLP 等官方资料，并在手写数字数据集上给出可复现的精度与预测耗时对比。",
      "updated": "2026-11-30",
      "takeaways": [
        "感知机对线性可分的训练样本做误差驱动的参数更新，可在有限步内找到一条分界超平面；数据线性不可分时，该过程不会稳定在一个分隔面上，实现中需要限制迭代次数。本课在一个可分的二维玩具数据上，11 次迭代后训练精度为 1.0；在同心圆数据上，感知机的训练精度为 0.50。",
        "Ridge 在平方误差上加入系数的 ℓ₂ 惩罚，使系数收缩并减轻共线性的影响；Lasso 改用 ℓ₁ 惩罚，可以把部分系数精确变成 0，从而选择特征。正则化的作用与选择方法见过拟合与泛化一课。本课在同一手写数字划分上，L2 逻辑回归有 40 个零系数（来自 4 个常数像素），L1 逻辑回归有 281 个零系数。",
        "支持向量机寻找间隔最大的分界超平面，决策函数只依赖支持向量。数据不能严格线性可分时，软间隔用松弛变量与惩罚系数 C 允许部分样本落入间隔之内或被分错。C 越小，正则越强，分界面越平滑。",
        "核技巧用核函数在特征空间中计算内积，而不显式写出映射。RBF 核为 exp(−γ‖x−x′‖²)。γ 过大时，单个支持向量的影响半径几乎只覆盖它自己，即使增大 C 也难以避免过拟合。本课在标准化后的手写数字上，默认 γ='scale'（约为 0.01667）的测试精度为 0.9861；γ=1 时训练精度为 1.0000，测试精度降至 0.1222。",
        "k 近邻把查询点判为最近 k 个训练样本中的多数类，训练几乎只是保存数据，预测需要计算距离。Cover 与 Hart（1967）证明，在大样本下最近邻规则的误差至多是贝叶斯误差的两倍。本课同一划分上，线性核 SVM、RBF 核 SVM 与 k=5 的 kNN 测试精度分别为 0.9778、0.9861 与 0.9806；360 个测试样本的预测耗时均值分别为 2.425 ms、10.632 ms 与 87.119 ms。"
      ],
      "faq": [
        {
          "q": "支持向量机的决策边界由哪些训练样本决定？",
          "a": "由支持向量决定，也就是落在间隔边界上或间隔之内的训练样本。对偶系数对其余样本为零，决策函数只需对支持向量求和。本课在标准化后的手写数字划分上，线性核 SVM 的支持向量共 437 个，RBF 核（γ='scale'）为 710 个。"
        },
        {
          "q": "k 近邻的训练成本与预测成本分别如何？本课测到的预测耗时如何比较？",
          "a": "训练几乎只是保存样本（本课中 5 次拟合的均值约为 0.49 ms）。预测需要对查询点与训练集计算距离，或查询 KD 树、球树等索引。本课对 360 个测试样本做 100 次重复，预测耗时均值：线性核 SVM 为 2.425 ms，RBF 核 SVM 为 10.632 ms，k=5 的 kNN 为 87.119 ms。"
        },
        {
          "q": "RBF 核的 gamma 过大会怎样？",
          "a": "scikit-learn 的 RBF 参数示例写明：γ 过大时，支持向量的影响半径几乎只覆盖它自己，用 C 做正则也无法防止过拟合。本课中 γ=1 时训练精度为 1.0000，测试精度降至 0.1222，支持向量数等于全部 1437 个训练样本；γ=10 时测试精度为 0.1028，接近十类均匀猜测的 0.1。"
        },
        {
          "q": "Ridge 与 Lasso 的惩罚有何不同？Lasso 为何能做特征选择？",
          "a": "Ridge 最小化 ‖Xw−y‖₂²+α‖w‖₂²，把系数向零收缩，一般不会把它们精确置零。Lasso 把惩罚改成 α‖w‖₁，在几何上更容易把部分系数推到坐标轴上，从而得到稀疏解并选择特征。本课同一划分上，L2 逻辑回归的零系数为 40 个（4 个常数像素乘以 10 个类别），L1 逻辑回归为 281 个。"
        },
        {
          "q": "朴素贝叶斯的“朴素”假设是什么？它在什么场景仍然常用？",
          "a": "在给定类别的条件下，特征之间条件独立。尽管这一假设在多数数据上并不成立，它对文档分类和垃圾邮件过滤等任务仍然常用，因为各类条件分布可以分别估计，训练和预测都很快。本课在标准化手写数字上，高斯朴素贝叶斯的测试精度为 0.7750，低于 SVM 与 kNN：相邻像素并不独立，也不适合用各维独立的高斯来描述。"
        }
      ],
      "sources": [
        {
          "title": "scikit-learn 用户指南：1.4 Support Vector Machines（间隔、支持向量、软间隔、核函数、C 与尺度）",
          "url": "https://scikit-learn.org/stable/modules/svm.html"
        },
        {
          "title": "scikit-learn 官方示例：RBF SVM 的 C 与 gamma",
          "url": "https://scikit-learn.org/stable/auto_examples/svm/plot_rbf_parameters.html"
        },
        {
          "title": "scikit-learn 官方示例：不同 SVM 核函数的决策边界",
          "url": "https://scikit-learn.org/stable/auto_examples/svm/plot_svm_kernels.html"
        },
        {
          "title": "scikit-learn 用户指南：1.1 Linear Models（Ridge、Lasso）",
          "url": "https://scikit-learn.org/stable/modules/linear_model.html"
        },
        {
          "title": "scikit-learn 官方示例：Lasso 坐标下降路径",
          "url": "https://scikit-learn.org/stable/auto_examples/linear_model/plot_lasso_coordinate_descent_path.html"
        },
        {
          "title": "scikit-learn API：Perceptron",
          "url": "https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.Perceptron.html"
        },
        {
          "title": "scikit-learn 用户指南：1.9 Naive Bayes",
          "url": "https://scikit-learn.org/stable/modules/naive_bayes.html"
        },
        {
          "title": "scikit-learn 用户指南：1.6 Nearest Neighbors",
          "url": "https://scikit-learn.org/stable/modules/neighbors.html"
        },
        {
          "title": "scikit-learn 官方示例：k 近邻分类的决策边界",
          "url": "https://scikit-learn.org/stable/auto_examples/neighbors/plot_classification.html"
        },
        {
          "title": "scikit-learn 官方示例库",
          "url": "https://scikit-learn.org/stable/auto_examples/index.html"
        },
        {
          "title": "scikit-learn API：load_digits",
          "url": "https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html"
        },
        {
          "title": "scikit-learn API：StandardScaler",
          "url": "https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html"
        },
        {
          "title": "scikit-learn API：SVC",
          "url": "https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html"
        },
        {
          "title": "scikit-learn API：KNeighborsClassifier",
          "url": "https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html"
        },
        {
          "title": "Cortes、Vapnik（1995），Support-vector networks，Machine Learning（DOI 10.1007/BF00994018）",
          "url": "https://link.springer.com/article/10.1007/BF00994018"
        },
        {
          "title": "Cover、Hart（1967），Nearest neighbor pattern classification，IEEE Transactions on Information Theory（作者页 PDF，Stanford ISL）",
          "url": "https://isl.stanford.edu/~cover/papers/transIT/0021cove.pdf"
        },
        {
          "title": "Rosenblatt（1958），The perceptron: A probabilistic model for information storage and organization in the brain.，Psychological Review（DOI 10.1037/h0042519）",
          "url": "https://doi.org/10.1037/h0042519"
        },
        {
          "title": "Tibshirani：The Lasso Page（作者页，著录 1996 年 JRSS-B 原文）",
          "url": "https://tibshirani.su.domains/lasso.html"
        },
        {
          "title": "Domingos、Pazzani（1997），On the Optimality of the Simple Bayesian Classifier under Zero-One Loss，Machine Learning（作者公开 PDF）",
          "url": "https://homes.cs.washington.edu/~pedrod/papers/mlj97.pdf"
        },
        {
          "title": "Domingos、Pazzani（1997），Machine Learning 期刊页面（DOI 10.1023/A:1007413511361）",
          "url": "https://link.springer.com/article/10.1023/A:1007413511361"
        },
        {
          "title": "Douze 等，The Faiss library，arXiv:2401.08281",
          "url": "https://arxiv.org/abs/2401.08281"
        },
        {
          "title": "facebookresearch/faiss（官方仓库）",
          "url": "https://github.com/facebookresearch/faiss"
        },
        {
          "title": "LIBSVM 官方主页（Chang & Lin）",
          "url": "https://www.csie.ntu.edu.tw/~cjlin/libsvm/"
        },
        {
          "title": "cjlin1/libsvm（LIBSVM 官方 GitHub 仓库）",
          "url": "https://github.com/cjlin1/libsvm"
        },
        {
          "title": "Stanford CS229 机器学习",
          "url": "https://cs229.stanford.edu/"
        },
        {
          "title": "Stanford CS229 课程讲义（PDF）",
          "url": "https://cs229.stanford.edu/main_notes.pdf"
        },
        {
          "title": "An Introduction to Statistical Learning（ISLP，免费教材）",
          "url": "https://www.statlearning.com/"
        },
        {
          "title": "ISLP 官方 Python 资源与实验",
          "url": "https://www.statlearning.com/resources-python"
        },
        {
          "title": "intro-stat-learning/ISLP_labs（官方 Python Lab 仓库，stable 分支）",
          "url": "https://github.com/intro-stat-learning/ISLP_labs/tree/stable"
        }
      ],
      "url": "https://aimap.page/zh-hans/learn/math-ml/svm-knn/",
      "markdown": "**概要**：线性模型用超平面给样本打分，近邻方法则直接查询训练样本。本课按“感知机与线性可分 → Ridge 与 Lasso 正则化 → 最大间隔与软间隔支持向量机 → 核技巧 → 朴素贝叶斯 → k 近邻与向量检索 → 手写数字上的对比实验”展开。文中实验数字均来自文末可运行示例，环境为 scikit-learn 1.9.1、NumPy 2.5.4、Python 3.13.5，随机种子 0。\n\n本课属于[线性模型、SVM 与近邻](/learn/unit/u22-svm-knn)单元，前置为[过拟合、泛化与数据划分](/learn/generalization)和[AI 中的线性代数](/learn/linear-algebra)，并与[机器学习中的损失与梯度下降](/learn/ml-basics)中的损失和参数更新相衔接。相关算法卡：[感知机](/learn/algorithms/perceptron)、[支持向量机](/learn/algorithms/svm)、[K 近邻](/learn/algorithms/knn)、[正则化回归（Lasso / Ridge）](/learn/algorithms/lasso)、[朴素贝叶斯](/learn/algorithms/naive-bayes)。\n\n## 感知机与线性可分\n\nRosenblatt（1958）在 *Psychological Review* 发表了感知机（perceptron）：用特征的加权和与一个阈值做二分类，这是早期的人工神经元模型。今天常用的误差驱动更新可以这样理解：若当前参数把一个训练样本分错，就把该样本的特征向量加到权重上（或从权重中减去），使分界面朝纠正这次错误的方向移动。\n\n如果训练数据是线性可分（linearly separable）的，即存在一个超平面把两类完全分开，那么上述更新在有限步内可以找到一个分隔超平面。如果数据不是线性可分的，更新不会稳定在一个分隔面上，因此 scikit-learn 的 `Perceptron` 需要 `max_iter` 这类停止条件。本课用 `make_classification` 生成 40 个二维、类别间隔较大的可分样本（`random_state=0`），`Perceptron` 在 11 次迭代后训练精度为 1.0；再用 `make_circles` 生成 200 个带噪声的同心圆（`noise=0.08`，`factor=0.4`，`random_state=0`），感知机在该训练集上的精度为 0.50，线性核 SVM 为 0.62，RBF 核 SVM 为 1.00。后一组数字是玩具集上的训练精度，未做持出划分，用来说明：线性分界面无法切开套在一起的两类，而核方法可以在特征空间里分开它们。\n\n感知机找到的分隔面不必是“离两类都尽量远”的那一条。下一节先看线性模型中的正则化，再进入以最大间隔为目标的支持向量机。\n\n## 线性模型与 Lasso、Ridge\n\n线性回归最小化残差平方和。特征共线或特征数接近样本数时，普通最小二乘的系数会变得很大、对扰动很敏感。[过拟合、泛化与数据划分](/learn/generalization)一课把正则化（regularization）解释为限制模型有效复杂度、降低方差的手段。\n\nHoerl 与 Kennard（1970）提出的岭回归（Ridge regression；题名与作者当天用 Crossref 核实，DOI 10.1080/00401706.1970.10488634；出版商页面当天对自动抓取返回 403，公式以 scikit-learn 用户指南为准）在平方误差上加入系数的 ℓ₂ 惩罚：\n\n\\[\\min_{w}\\ \\|Xw-y\\|_2^2 + \\alpha \\|w\\|_2^2.\\]\n\n\\(\\alpha \\ge 0\\) 控制收缩程度：\\(\\alpha\\) 越大，系数越被拉向零，对共线性也更稳健。ℓ₂ 惩罚会缩小系数，但通常不会把它们精确变成 0。\n\nTibshirani（1996）提出的 Lasso（least absolute shrinkage and selection operator）把惩罚改成系数绝对值之和。作者页的定义是：在普通平方误差之上，对系数绝对值之和加以约束。scikit-learn 中的等价目标为\n\n\\[\\min_{w}\\ \\frac{1}{2n}\\|Xw-y\\|_2^2 + \\alpha \\|w\\|_1.\\]\n\n用户指南写明：Lasso 能够把部分系数精确变成 0，从而依赖更少的特征，起到特征选择的作用。坐标下降是其中一种常用算法；官方示例给出了随 \\(\\alpha\\) 变化的系数路径。\n\n分类问题里，同样的 ℓ₁ / ℓ₂ 惩罚可以加在逻辑回归等线性分类器上。本课在标准化后的手写数字同一划分上，用 `LogisticRegression` 做了一个对照（不是单元项目的主结果）：L2 惩罚下测试精度为 0.9667，640 个系数中有 40 个为零，与本次训练集中 4 个常数像素（下标 0、24、32、39）乘以 10 个类别一致；L1 惩罚（`solver='saga'`，`C=1.0`）测试精度为 0.9694，零系数增加到 281 个。同一划分上，`RidgeClassifier` 的测试精度为 0.9361，`Perceptron` 为 0.9306。\n\n正则化强度本身是超参数，要用验证集或交叉验证来选，详见泛化一课。线性模型给出的是一个全局的超平面；要在间隔意义上选择“最宽”的那一条，需要支持向量机。\n\n## 间隔、支持向量与软间隔 SVM\n\nscikit-learn 用户指南对支持向量机（support vector machine, SVM）的几何直观是：在特征空间中构造超平面，使它到各类最近训练点的距离（间隔，margin）尽可能大；间隔更大的分界面，往往有更低的泛化误差。落在间隔边界上的训练样本称为支持向量（support vectors）；当数据不能严格线性可分时，支持向量还包括间隔之内的样本。\n\nCortes 与 Vapnik（1995）的 *Support-vector networks* 给出了允许训练误差的软间隔（soft-margin）支持向量机，并在此框架下使用核函数。scikit-learn 中 `SVC` 求解的原问题是\n\n\\[\n\\min_{w,b,\\zeta}\\ \\frac{1}{2}w^\\top w + C\\sum_{i=1}^{n}\\zeta_i\n\\quad\\text{s.t.}\\quad\ny_i\\bigl(w^\\top\\phi(x_i)+b\\bigr)\\ge 1-\\zeta_i,\\ \\zeta_i\\ge 0.\n\\]\n\n第一项最小化 \\(\\|w\\|^2\\)，等价于最大化间隔；松弛变量 \\(\\zeta_i\\) 允许样本落在正确的间隔边界之内，或被分错。惩罚系数 \\(C\\) 是这一代价的权重，作用相当于正则化系数的倒数：\\(C\\) 越小，正则越强，分界面越平滑；\\(C\\) 越大，模型越倾向于把训练样本全部分对。指南建议默认 \\(C=1\\) 通常可用；噪声较多时可减小 \\(C\\)。\n\n对偶形式下，决策函数为\n\n\\[\n\\sum_{i\\in\\mathrm{SV}} y_i\\alpha_i K(x_i,x)+b,\n\\]\n\n只需对支持向量求和，其余训练样本的对偶系数为 0。因此 SVM 的决策边界由支持向量决定，而不是由全部训练点同等决定。\n\n多类问题中，`SVC` 采用一对一（one-versus-one）策略：对 \\(K\\) 类训练 \\(K(K-1)/2\\) 个二分类器。手写数字有 10 类，即 45 个二分类 SVM。指南还强调：SVM 对特征尺度敏感，应把各维标准化到相近范围，并且必须把训练集上估计的变换用到测试集，通常用 `Pipeline` 包装 `StandardScaler` 与 `SVC`。scikit-learn 的 `SVC` 内部调用 LIBSVM（Chang 与 Lin）。\n\nBoser、Guyon 与 Vapnik（1992）在 COLT 发表了题为 *A training algorithm for optimal margin classifiers* 的论文（题名、作者与年份当天用 Crossref 核实，DOI 10.1145/130385.130401；ACM 页面当天对自动抓取返回 403）。1995 年的软间隔论文是本课引用的主要原文。\n\n## 核技巧\n\n若在输入空间里不能用超平面分开两类，可以把样本映射到更高维的特征空间再做线性划分。核技巧（kernel trick）的要点是：只要算法只依赖内积，就可以用核函数 \\(K(x,x')=\\langle\\phi(x),\\phi(x')\\rangle\\) 直接计算，而不必写出 \\(\\phi(x)\\)。scikit-learn 提供的常用核包括：\n\n- 线性核：\\(K(x,x')=\\langle x,x'\\rangle\\)；\n- 多项式核：\\(K(x,x')=(\\gamma\\langle x,x'\\rangle+r)^d\\)；\n- 径向基（RBF）核：\\(K(x,x')=\\exp(-\\gamma\\|x-x'\\|^2)\\)，其中 \\(\\gamma>0\\)；\n- sigmoid 核：\\(K(x,x')=\\tanh(\\gamma\\langle x,x'\\rangle+r)\\)。\n\nRBF 核是实践中最常见的非线性核。指南说明：\\(\\gamma\\) 控制单个训练样本的影响范围，\\(\\gamma\\) 越大，必须离得更近才会受到影响。\\(C\\) 与 \\(\\gamma\\) 需要一起选择，常用对数间隔的网格搜索。官方示例 *RBF SVM parameters* 进一步写明：若 \\(\\gamma\\) 过大，支持向量的影响半径几乎只覆盖它自己，此时即使用 \\(C\\) 做正则，也无法防止过拟合；若 \\(\\gamma\\) 过小，模型过于受限，行为会接近用超平面分隔两类密集中心的线性模型。\n\n本课在标准化后的手写数字上固定 \\(C=1\\)、改变 \\(\\gamma\\)，结果如下。`gamma='scale'` 按 scikit-learn 的定义取值 \\(1/(n_{\\text{features}}\\cdot\\mathrm{Var}(X))\\)，在本次标准化训练集上等于 \\(0.01666\\ldots\\)（因有 4 个常数特征，标准化后整体方差为 0.9375，而不是 1）。\n\n| γ | 训练精度 | 测试精度 | 支持向量数 |\n|---|---|---|---|\n| 0.001 | 0.9610 | 0.9417 | 1127 |\n| 0.01 | 0.9937 | 0.9806 | 713 |\n| scale（≈0.01667） | 0.9951 | 0.9861 | 710 |\n| 0.1 | 1.0000 | 0.9389 | 1194 |\n| 1.0 | 1.0000 | 0.1222 | 1437 |\n| 10 | 1.0000 | 0.1028 | 1437 |\n\nγ=1 与 γ=10 时，训练精度达到 1.0000，但测试精度分别降到 0.1222 与 0.1028，支持向量数等于全部 1437 个训练样本：模型几乎在“记住”每一个训练点，对未见样本接近乱猜（十类均匀猜测的精度为 0.1）。这与官方示例中“γ 过大则过拟合”的说明一致。默认的 `gamma='scale'` 在本划分上测试精度最高（0.9861）。\n\n## 朴素贝叶斯的适用场景\n\n朴素贝叶斯（naive Bayes）用贝叶斯定理估计后验类别，并加上“朴素”假设：在给定类别的条件下，特征之间条件独立。于是\n\n\\[\n\\hat y=\\arg\\max_y\\ P(y)\\prod_{i=1}^{n}P(x_i\\mid y).\n\\]\n\n不同变体的差别主要在 \\(P(x_i\\mid y)\\) 的分布：`GaussianNB` 假设连续特征在各类中为高斯分布，`MultinomialNB` 面向词频或 TF-IDF 一类计数特征，`BernoulliNB` 面向二值特征。scikit-learn 用户指南指出：尽管假设明显简化，朴素贝叶斯在文档分类和垃圾邮件过滤等任务上仍然常用；它只需要较少的样本来估计参数，并且可以把每个特征的类条件分布单独估计，因而训练和预测都很快，也有助于缓解维数带来的困难。另一方面，它通常是不错的分类器，但不是好的概率估计器，`predict_proba` 不宜直接当作校准后的概率。\n\nDomingos 与 Pazzani（1997）的论文题为 *On the Optimality of the Simple Bayesian Classifier under Zero-One Loss*（题名、作者与年份当天用 Crossref 核实；作者公开 PDF 与期刊页面当天 HTTP 200）。该文从 0-1 损失的角度讨论简单贝叶斯分类器的最优性；本课不转述其未在可检索摘要中逐句核对的中间定理。\n\n朴素贝叶斯适合特征在给定类别下近似可分开建模的问题，尤其是词袋或 n-gram 计数。相邻像素高度相关的图像，并不是高斯朴素贝叶斯的典型适用场景。本课在同一标准化手写数字划分上，`GaussianNB` 的训练精度为 0.8135，测试精度为 0.7750，低于后文的 SVM 与 kNN。文本分类可参考 scikit-learn 的 20 新闻组文档分类示例。\n\n## k 近邻、距离、维数与向量检索\n\nk 近邻（k-nearest neighbors, kNN）是一种非参数方法：把查询点 \\(x\\) 判为训练集中距离最近的 \\(k\\) 个样本里出现最多的类别。默认可用欧氏距离；scikit-learn 还支持按距离的倒数加权投票。指南写明：尽管规则简单，近邻方法在手写数字和卫星图像等任务上仍然有效，尤其在决策边界不规则时。\n\nCover 与 Hart（1967）分析了最近邻规则（即 \\(k=1\\)）。作者页 PDF 的摘要写明：该规则不依赖样本与类别的联合分布，因此其误差 \\(R\\) 不会低于贝叶斯误差 \\(R^*\\)；在大样本分析中，对任意类别数，最近邻规则的误差以两倍贝叶斯误差为上界。文中并追溯到 Fix 与 Hodges 更早提出的 \\(k\\) 近邻型规则。需要强调的是，这一上界是大样本下的理论结果，不能直接读成“本课 360 个测试样本上的误差已经是贝叶斯误差的两倍”。\n\nkNN 几乎没有独立于数据的“训练”：拟合阶段主要是保存样本，并可选择建立 KD 树或球树。预测时则要计算查询点与大量训练样本的距离，或在这些树上搜索。当维度升高时，距离对比变得不那么有分辨力，指南在讨论半径近邻时也提到高维空间中的“维数灾难”（curse of dimensionality）。对中等规模、中等维度的数据，暴力搜索、KD 树或球树通常足够；当样本是大规模向量（例如嵌入）时，需要近似最近邻（approximate nearest neighbor, ANN）索引。Faiss 库（Douze 等，arXiv:2401.08281）的定位就是向量相似度检索：在向量数据库中对嵌入做搜索、聚类、压缩与变换。它与本课的 kNN 是同一问题在不同规模下的延伸，而不是 scikit-learn `KNeighborsClassifier` 的替代实现。\n\n## 手写数字上的可复现对比\n\n单元项目要求：用线性核 SVM、RBF 核 SVM 和 kNN 分类手写数字，比较精度与预测速度。本课使用 scikit-learn 的 `load_digits`：1797 张 8×8 灰度数字图像，像素取值 0 到 16，64 维特征，10 个类别。划分方式为 `train_test_split(..., test_size=0.2, random_state=0, stratify=y)`，得到 1437 个训练样本与 360 个测试样本。特征在训练集上拟合 `StandardScaler`（均值为 0、方差为 1），再把同一变换应用到测试集。分类器与默认超参数为：\n\n- `SVC(kernel='linear', C=1.0, random_state=0)`\n- `SVC(kernel='rbf', C=1.0, gamma='scale', random_state=0)`\n- `KNeighborsClassifier(n_neighbors=5, algorithm='auto', n_jobs=1)`\n\n预测耗时是对全部 360 个测试样本先做 5 次预热，再重复 100 次 `predict`，取均值。环境为 scikit-learn 1.9.1、NumPy 2.5.4、Python 3.13.5。耗时与机器有关，精度在固定种子与相同软件版本下应可复现。\n\n| 模型 | 训练精度 | 测试精度 | 预测耗时均值 | 支持向量数 |\n|---|---|---|---|---|\n| 线性核 SVM | 1.0000（1437/1437） | 0.9778（352/360） | 2.425 ms | 437 |\n| RBF 核 SVM | 0.9951（1430/1437） | 0.9861（355/360） | 10.632 ms | 710 |\n| kNN（k=5） | 0.9847（1415/1437） | 0.9806（353/360） | 87.119 ms | — |\n\n在本划分上，RBF 核的测试精度最高（0.9861），kNN 次之（0.9806），线性核为 0.9778。预测方面，线性核最快，RBF 核约为其 4.4 倍（10.632/2.425），kNN 约为线性核的 35.9 倍（87.119/2.425）。kNN 的 5 次拟合均值为 0.49 ms，线性核 SVM 为 15.66 ms，RBF 核 SVM 为 26.77 ms，与“近邻方法把计算留到预测阶段”一致。若不对特征做标准化，三者的测试精度分别为 0.9722、0.9833 与 0.9778，均略低于标准化后的结果，这也与“SVM 对尺度敏感、距离方法同样受各维量纲影响”相符。\n\n这些数字只对应上述超参数与这一次划分，不能外推为“RBF 核总是比线性核更准”或“kNN 总是更慢”。换数据、换 \\(C\\)、\\(\\gamma\\) 或 \\(k\\)，排序都可能改变；应用中应在验证集上选择超参数，并用独立测试集只评估一次。\n\n## 可运行示例\n\n```python\nimport time\nimport numpy as np\nfrom sklearn.datasets import load_digits\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.svm import SVC\n\ndigits = load_digits()\nX_tr, X_te, y_tr, y_te = train_test_split(\n    digits.data, digits.target, test_size=0.2, random_state=0, stratify=digits.target\n)\nscaler = StandardScaler()\nX_tr = scaler.fit_transform(X_tr)\nX_te = scaler.transform(X_te)\n\nmodels = {\n    \"linear\": SVC(kernel=\"linear\", C=1.0, random_state=0),\n    \"rbf\": SVC(kernel=\"rbf\", C=1.0, gamma=\"scale\", random_state=0),\n    \"knn\": KNeighborsClassifier(n_neighbors=5, algorithm=\"auto\", n_jobs=1),\n}\nfor name, clf in models.items():\n    clf.fit(X_tr, y_tr)\n    train_acc = (clf.predict(X_tr) == y_tr).mean()\n    test_acc = (clf.predict(X_te) == y_te).mean()\n    for _ in range(5):\n        clf.predict(X_te)\n    times = []\n    for _ in range(100):\n        t0 = time.perf_counter()\n        clf.predict(X_te)\n        times.append(time.perf_counter() - t0)\n    n_sv = int(clf.n_support_.sum()) if hasattr(clf, \"n_support_\") else None\n    print(name, \"train\", round(train_acc, 4), \"test\", round(test_acc, 4),\n          \"pred_ms\", round(np.mean(times) * 1000, 3), \"n_sv\", n_sv)\n\nfor gamma in [0.001, 0.01, \"scale\", 0.1, 1.0, 10.0]:\n    clf = SVC(kernel=\"rbf\", C=1.0, gamma=gamma, random_state=0).fit(X_tr, y_tr)\n    print(\"gamma\", gamma, \"train\", round((clf.predict(X_tr) == y_tr).mean(), 4),\n          \"test\", round((clf.predict(X_te) == y_te).mean(), 4),\n          \"n_sv\", int(clf.n_support_.sum()))\n```\n\n实测输出要点：线性核测试精度 0.9778、预测 2.425 ms、支持向量 437；RBF 核（`gamma='scale'`）测试精度 0.9861、预测 10.632 ms、支持向量 710；kNN 测试精度 0.9806、预测 87.119 ms。γ=1 时训练精度 1.0000、测试精度 0.1222、支持向量 1437。预测耗时随机器而变，精度应可复现。\n\n## 动手练习\n\n1. **单元项目**：用 SVM（线性核与 RBF 核）和 kNN 分类手写数字，比较精度与预测速度。可以沿用本课的 `load_digits` 划分与标准化，也可以改 `C`、`gamma` 或 `n_neighbors` 并在验证集上选择；请固定随机种子，并写明软件版本与全部超参数。\n2. 运行 [scikit-learn 官方示例库](https://scikit-learn.org/stable/auto_examples/index.html)中的 [SVM 核函数](https://scikit-learn.org/stable/auto_examples/svm/plot_svm_kernels.html)、[k 近邻分类](https://scikit-learn.org/stable/auto_examples/neighbors/plot_classification.html)和 [Lasso 坐标下降路径](https://scikit-learn.org/stable/auto_examples/linear_model/plot_lasso_coordinate_descent_path.html)，改动核参数、\\(k\\) 或 \\(\\alpha\\)，观察分界面或系数路径如何变化。也可对照 [RBF 的 C 与 gamma 示例](https://scikit-learn.org/stable/auto_examples/svm/plot_rbf_parameters.html)。\n3. 在 [ISLP 官方 Python 资源页](https://www.statlearning.com/resources-python)进入配套实验，或直接使用官方仓库 [ISLP_labs（stable 分支）](https://github.com/intro-stat-learning/ISLP_labs/tree/stable)，完成教材中与线性模型、正则化、支持向量机和近邻对应章节的 Python Lab。\n\n## 推荐学习顺序\n\n先读 [scikit-learn 线性模型指南](https://scikit-learn.org/stable/modules/linear_model.html)中的 Ridge 与 Lasso，以及[过拟合、泛化与数据划分](/learn/generalization)中的正则化一节，再读[支持向量机指南](https://scikit-learn.org/stable/modules/svm.html)中的实用建议、RBF 参数与数学表述。近邻与检索读[最近邻指南](https://scikit-learn.org/stable/modules/neighbors.html)和 Cover、Hart（1967）的摘要；大规模向量检索可继续看 [Faiss 仓库](https://github.com/facebookresearch/faiss)与 Douze 等（arXiv:2401.08281）。统计学习的叙述见免费教材 [An Introduction to Statistical Learning](https://www.statlearning.com/) 与 [CS229 讲义](https://cs229.stanford.edu/main_notes.pdf)。实现细节见 [LIBSVM](https://www.csie.ntu.edu.tw/~cjlin/libsvm/)。随后可进入同一阶段的[树模型与集成学习](/learn/tree-ensembles)或[无监督学习：聚类、降维与 EM](/learn/unsupervised-learning)。"
    }
  }
}