Vector Space Classification

Classifying documents by their position in the vector space of terms. The contiguity hypothesis, Rocchio classification with class centroids and its linear boundary derived, k nearest neighbors and its Voronoi regions, both worked on a two-dimensional example with an interactive demo, why Rocchio fails for diffuse classes, kNN's accuracy as k varies on Reuters, a comparison with Naive Bayes, linear classifiers, the support vector machine and its margin 2/‖w‖, and the bias-variance trade-off measured on simulated data.

Vector space classifiers assign a document by its position among term vectors, assuming each class occupies a contiguous region. Rocchio picks the nearest class centroid; its boundary is the hyperplane bisecting two centroids, so it fails for spread-out or multimodal classes. k nearest neighbors votes among the $k$ most similar training documents and follows boundaries of any shape, at the cost of variance. On ten Reuters-21578 categories, micro- and macro-F1 were 0.724 and 0.485 for Rocchio, 0.884 and 0.703 for Naive Bayes, and 0.894 and 0.745 for kNN with $k = 30$. The support vector machine takes the separating hyperplane of widest margin, $2/\lVert \vec{w} \rVert$. In simulation, Rocchio matched the best possible error where a line is the right boundary and erred on about a third of points where it is not.

The grain classifier of Naive Bayes classification decides by asking which class would most probably have generated a story's words. A different approach asks which training stories the new one most resembles. In the vector space model, every story is a weighted term vector, and cosine similarity measures how alike two stories are. If the stories most similar to a new one are about grain, the new one can be called a grain story too.

That is the idea of vector space classification: if documents of the same class lie near one another in the vector space, a new document can be classified by where it falls. It reuses the representation built for retrieval rather than a probabilistic model of text.

Here is the route. First we state the assumption the idea rests on. Then we build its two classic methods, Rocchio and k nearest neighbors, on a small example in two dimensions where their decision regions can be drawn. Next we compare both with Naive Bayes on ten Reuters categories. Finally we see that Rocchio and Naive Bayes are both linear classifiers, and meet a third, the support vector machine, with its margin. The bias-variance trade-off then explains when a flexible classifier beats them. Evaluating classifiers defines the micro- and macro-averaged F1 used throughout.

The contiguity hypothesis

When does it make sense to classify by position? Vector space classifiers rest on the contiguity hypothesis: documents in the same class form a contiguous region of the space, and regions of different classes do not overlap (Manning, Raghavan, and Schütze, 2008, ch. 14). Whether it holds depends on the representation. With TF-IDF vectors, documents about grain share vocabulary such as wheat, tonnes, and harvest, and so cluster together. A class defined by something other than topic, such as the author's gender or a document's date, may not form a region at all, and no vector space classifier will learn it well.

Real document vectors have thousands of dimensions, which cannot be drawn. The geometry of the two methods is the same in any number of dimensions, so this article illustrates them in a plane. In the example below, each point is a training document of class A (circles) or class B (squares). Class A forms one cloud in the middle. Class B forms two clouds, one on each side, as a class made of two distinct subtopics would. A new document, the star, sits at $(2.4, 5.8)$. The coordinates are in tools/experiments/reuters/toy2d.py, which computes every number quoted for the example.

Rocchio classification

The simplest way to summarize where a class lives is a single point in its middle. Rocchio classification represents each class by its centroid, the average of the vectors of its training documents,

$$\vec{\mu}(c) = \frac{1}{\lvert D_c \rvert} \sum_{d \in D_c} \vec{v}(d),$$

where $D_c$ is the set of training documents in class $c$. The decision rule assigns a new document $d$ to the class whose centroid is nearest in Euclidean distance,

$$\gamma(d) = \arg\min_{c} \; \lVert \vec{\mu}(c) - \vec{v}(d) \rVert$$

(Manning, Raghavan, and Schütze, 2008, Figure 14.4). The method adapts the centroid computation of Rocchio relevance feedback to classification. Training is a single pass to compute the centroids, and classification needs one distance or similarity per class. For normal classes with a shared covariance matrix, Linear Discriminant Analysis proves that the Bayes rule assigns each point to the nearest class mean in Mahalanobis distance, after a correction for class sizes. With equal priors and a covariance matrix that is a multiple of the identity, that rule is Rocchio's.

Its boundary is a hyperplane

What does the boundary between two classes look like? Here is the idea in one sentence. The points exactly as far from A's centroid as from B's form a hyperplane, the one that cuts the segment between the two centroids at its midpoint and at right angles (Manning, Raghavan, and Schütze, 2008, §14.2). Every point on A's side of it is closer to A's centroid.

So Rocchio is a linear classifier: a document $\vec{x}$ goes to A when $\vec{w} \cdot \vec{x} > b$, for a weight vector $\vec{w}$ pointing from B's centroid toward A's and a threshold $b$.

The formal version. By the decision rule, $\vec{x}$ goes to A when it is nearer to A's centroid. Distances are not negative, so comparing them is the same as comparing their squares:

$$\lVert \vec{x} - \vec{\mu}_A \rVert^2 < \lVert \vec{x} - \vec{\mu}_B \rVert^2.$$

Expand each side with $\lVert \vec{x} - \vec{\mu} \rVert^2 = \lVert \vec{x} \rVert^2 - 2\,\vec{\mu} \cdot \vec{x} + \lVert \vec{\mu} \rVert^2$:

$$\lVert \vec{x} \rVert^2 - 2\,\vec{\mu}_A \cdot \vec{x} + \lVert \vec{\mu}_A \rVert^2 < \lVert \vec{x} \rVert^2 - 2\,\vec{\mu}_B \cdot \vec{x} + \lVert \vec{\mu}_B \rVert^2.$$

The term $\lVert \vec{x} \rVert^2$ cancels, which is what makes the rule linear in $\vec{x}$. Collecting the terms with $\vec{x}$ on the left,

$$2(\vec{\mu}_A - \vec{\mu}_B) \cdot \vec{x} > \lVert \vec{\mu}_A \rVert^2 - \lVert \vec{\mu}_B \rVert^2, \qquad\text{so}\qquad \vec{w} = 2(\vec{\mu}_A - \vec{\mu}_B), \quad b = \lVert \vec{\mu}_A \rVert^2 - \lVert \vec{\mu}_B \rVert^2.$$

Dividing both by 2 gives the form in the course text, $\vec{w} = \vec{\mu}_A - \vec{\mu}_B$ and $b = \tfrac{1}{2}(\lVert \vec{\mu}_A \rVert^2 - \lVert \vec{\mu}_B \rVert^2)$, which describes the same hyperplane (§14.4). The boundary $\vec{w} \cdot \vec{x} = b$ is the perpendicular bisector promised above. Its normal vector $\vec{w}$ lies along $\vec{\mu}_A - \vec{\mu}_B$, the direction of the segment between the centroids. And the segment's midpoint $\vec{m} = \tfrac{1}{2}(\vec{\mu}_A + \vec{\mu}_B)$ lies on it, since $\vec{w} \cdot \vec{m} = (\vec{\mu}_A - \vec{\mu}_B) \cdot (\vec{\mu}_A + \vec{\mu}_B) = \lVert \vec{\mu}_A \rVert^2 - \lVert \vec{\mu}_B \rVert^2 = b$.

The cosine version. The course text also gives the rule with cosine similarity in place of distance: assign $d$ to the class whose centroid has the largest cosine with $\vec{v}(d)$ (§14.2). For length-normalized documents the cosine with a centroid is the dot product with the centroid scaled to length 1, $\hat{\mu}$, and A wins when $\vec{x} \cdot \hat{\mu}_A > \vec{x} \cdot \hat{\mu}_B$. The Reuters experiment below uses this form. Moving everything to the left gives $(\hat{\mu}_A - \hat{\mu}_B) \cdot \vec{x} > 0$, which is linear with $\vec{w} = \hat{\mu}_A - \hat{\mu}_B$ and $b = 0$. For unit vectors this is the distance rule again, because $\lVert \vec{x} - \hat{\mu} \rVert^2 = 1 - 2\,\vec{x} \cdot \hat{\mu} + 1 = 2 - 2\,\vec{x} \cdot \hat{\mu}$: the nearest normalized centroid is the one with the largest cosine. The two rules can disagree when the centroids are left unnormalized, since an average of unit vectors is in general shorter than 1, by different amounts for different classes.

On the example

The six A points have centroid $(5.000, 6.117)$ and the eight B points $(5.025, 4.975)$. The B centroid lies in the middle of the picture, between B's two clouds and near none of its points.

Example (the star goes to the wrong class). Rocchio assigns the star at $(2.4, 5.8)$ to class A, although it sits inside B's left-hand cloud. Its distance to A's centroid (2.619) is a little less than to B's (2.752), even though every one of its three nearest training points is a B point. B's centroid has been pulled to the middle by B's right-hand cloud.

The linear form agrees. The weights are $\vec{w} = 2\big((5.000, 6.117) - (5.025, 4.975)\big) = (-0.050, 2.283)$ and $b = 12.412$. The boundary is the almost horizontal line $-0.050\,x + 2.283\,y = 12.412$, or $y \approx 5.44 + 0.022\,x$. Everything above it is assigned to A, and the star lies above it: $\vec{w} \cdot (2.4, 5.8) = 13.123 > 12.412$. The midpoint of the two centroids, $(5.0125, 5.546)$, gives $\vec{w} \cdot \vec{m} = 12.412 = b$, as the derivation requires.

That line is a poor separator for these classes. Rocchio misclassifies 4 of the 14 training points it was built from:

  • two A points just below the line, $(4.6, 5.2)$ and $(5.4, 5.4)$;
  • two B points above it, $(2.0, 6.4)$ and $(7.6, 5.8)$.

Its weakness is the assumption that one point can represent a class. That works when a class's documents form one roughly spherical cloud. It fails when a class is spread out or made of several separate groups, as B is here. In a binary setup for text, the "not in class" side is exactly that kind of class. The centroid of all non-grain stories averages together earnings reports, acquisitions, currency news, and everything else, and lies near none of them (Manning, Raghavan, and Schütze, 2008, §14.2). On Reuters, the length-normalized centroid of the grain stories and that of all other stories have a cosine of 0.448 with each other.

k nearest neighbors

If one point per class is too crude, why not keep all of them? k nearest neighbors (kNN) keeps every training document and classifies a new document by looking at the $k$ training documents most similar to it. In its simplest form, the class held by the majority of the neighbors wins. The share of the $k$ neighbors in a class then serves as an estimate of the probability that the document belongs to it. A common refinement weights each neighbor's vote by its similarity, so closer neighbors count more. Writing $S_k(d)$ for the set of the $k$ nearest neighbors of $d$, and $I_c(d') = 1$ if $d'$ is in class $c$ and 0 otherwise, the class's score is

$$\mathrm{score}(c, d) = \sum_{d' \in S_k(d)} I_c(d') \, \cos\big(\vec{v}(d'), \vec{v}(d)\big),$$

and the document goes to the class with the highest score (Manning, Raghavan, and Schütze, 2008, §14.3). kNN needs no training at all, and it can represent classes of any shape, since a class is just the set of regions where its examples lie. It is not a linear classifier. The library's k-nearest neighbors treats the method outside text: other distances, the scaling of inputs, and regression.

With $k = 1$, every training point claims the region of the plane that is closer to it than to any other training point. These regions are the cells of the Voronoi tessellation of the training set. The decision boundary is made of the cell edges that separate points of different classes (Manning, Raghavan, and Schütze, 2008, §14.3). It is piecewise linear, and as complicated as the data.

Back to the star. Its three nearest neighbors are all B points, at distances 0.721, 0.825, and 1.342, and kNN assigns it to B for every odd $k$ from 1 to 7. kNN follows B's two clouds where Rocchio's single line cannot:

Notice the star: inside B's left cloud, it is assigned to A by Rocchio and to B by kNN. The panels show the same fourteen training points, class A as circles and class B as squares, with the regions each classifier assigns to A (blue) and B (orange). Rocchio's boundary is a nearly horizontal line between the two centroids (plus and cross), which cuts through both classes. kNN with k = 1 follows the Voronoi cells of the points and gives every training point its own class. With k = 5 and k = 7 the boundary is smoother.
Notice the star: inside B's left cloud, it is assigned to A by Rocchio and to B by kNN. The panels show the same fourteen training points, class A as circles and class B as squares, with the regions each classifier assigns to A (blue) and B (orange). Rocchio's boundary is a nearly horizontal line between the two centroids (plus and cross), which cuts through both classes. kNN with k = 1 follows the Voronoi cells of the points and gives every training point its own class. With k = 5 and k = 7 the boundary is smoother.

The choice of $k$ matters. With $k = 1$, the classifier copies the label of the single most similar document, which makes it sensitive to noise and to mislabeled training examples. A natural thought is that more neighbors always make a more reliable vote. Larger values do smooth over noise. But if $k$ is too large, the neighborhood takes in documents from other classes, and the classifier drifts toward predicting the most common classes.

Example (too many neighbors). With $k = 7$, kNN misclassifies all eight B points in the leave-one-out test, in which each training point is classified from the other thirteen. With $k = 1$, 3, or 5 it makes no errors. Each of B's clouds has four points. Once one B point is held out, its seven nearest neighbors are the three remaining points of its own cloud and then four A points, which are nearer than the far cloud. So A wins the vote, 4 to 3. Rocchio, refitted without each held-out point, makes 9 leave-one-out errors. Small odd values such as 3 or 5 are common, and values from 10 to 100 are also used for text.

Drag any training point or the star, or focus one with Tab and move it with the arrow keys. The shading shows the regions of the chosen classifier, the dashed line is always Rocchio's boundary, and the readout counts Rocchio's training errors and kNN's leave-one-out errors. Notice that moving B's right-hand cloud toward A drags B's centroid with it and swings Rocchio's line, while kNN's regions change only near the points that moved.

kNN's cost falls at classification time, when the new document must be compared with the training documents. With an inverted index over the training set, only training documents sharing a term with the new one are compared. The accumulation is the same as in computing vector scores. In effect, kNN classification is a search with the new document as the query. Dense vectors, with no zero entries to skip, give the inverted index nothing to exploit: Nearest Neighbor Search in High Dimensions shows that even a k-d tree examines 97% of 399,000 word vectors of 100 dimensions, proves the concentration of distances usually given as the reason, and turns to approximate search.

The course text's cost figures set the three classifiers of this unit side by side (Manning, Raghavan, and Schütze, 2008, Tables 13.2, 14.2 and 14.3). Here $\lvert \mathbb{D} \rvert$ is the number of training documents, $L_{\text{ave}}$ their average length in tokens and $M_{\text{ave}}$ their average number of distinct terms. $L_a$ and $M_a$ are the number of tokens and of distinct terms in the document being classified, $\lvert \mathbb{C} \rvert$ is the number of classes and $\lvert V \rvert$ the vocabulary size.

Classifier Training Classifying one document
Naive Bayes $\Theta(\lvert \mathbb{D} \rvert L_{\text{ave}} + \lvert \mathbb{C} \rvert \lvert V \rvert)$ $\Theta(L_a + \lvert \mathbb{C} \rvert M_a)$
Rocchio $\Theta(\lvert \mathbb{D} \rvert L_{\text{ave}} + \lvert \mathbb{C} \rvert \lvert V \rvert)$ $\Theta(L_a + \lvert \mathbb{C} \rvert M_a)$
kNN, training documents preprocessed $\Theta(\lvert \mathbb{D} \rvert L_{\text{ave}})$ $\Theta(L_a + \lvert \mathbb{D} \rvert M_{\text{ave}} M_a)$

Naive Bayes and Rocchio compare a document with one parameter vector per class. kNN compares it with every training document, so its classification time grows with the training set and does not depend on the number of classes.

How good can a single neighbor be? The Bayes error rate of a problem is the error rate of the best possible classifier for it. Cover and Hart (1967) proved that as the training set grows without limit, the error rate of the 1-nearest-neighbor rule approaches a limit between the Bayes error rate and twice it, for any number of classes, provided the class distributions are smooth enough. The course text states the bound in §14.3.1. The library's k-nearest neighbors states the sharper bound $2R^*(1 - R^*)$ for two classes, where $R^*$ is the Bayes error rate, derives it, and checks it by simulation. The bound is about unlimited training data and says nothing about a small training set. In the simulation later in this article, with only 20 training points per class in two dimensions, a single neighbor's median error on the one-cloud problem is 0.188 against a Bayes error of 0.130, which is inside twice the Bayes error, 0.261.

A comparison on Reuters

The toy example favors kNN by design. On real news kNN also comes out ahead once it has enough neighbors, while Rocchio trails. The three classifiers were run on ten Reuters-21578 categories, with the same training and test stories and the same text processing as in Naive Bayes classification. The categories are not the ten largest used elsewhere in this unit. They are the two largest, earn and acq, the running example grain, and the seven categories ranked 11th to 17th by training size: money-supply, dlr, sugar, oilseed, coffee, gnp, and gold, with 94 to 140 training stories each. That mixes very large categories with small ones, and some of the small ones overlap larger categories: 60 of the 124 oilseed training stories are also labeled grain. One binary classifier was built per category, and Naive Bayes was retrained and evaluated on the same ten categories. The details:

  • Representation. For the vector space methods, documents were length-normalized TF-IDF vectors with logarithmic term frequency.
  • Rocchio. A story's cosine similarity was compared with two length-normalized centroids, one for the category's training stories and one for all other training stories.
  • kNN. Each neighbor's vote was weighted by its cosine similarity. The category was assigned when the neighbors in it held more than half the total weight.

Example (the method the diffuse class hurts). Rocchio does worst of the three, as the example with diffuse classes predicts: its "not in category" centroid averages every other kind of story. The results:

Classifier Micro-F1 Macro-F1
Rocchio 0.724 0.485
kNN, $k = 1$ 0.752 0.678
kNN, $k = 5$ 0.829 0.749
kNN, $k = 10$ 0.859 0.755
Multinomial Naive Bayes 0.884 0.703
kNN, $k = 30$ 0.894 0.745

Rocchio did worst, as the diffuse "not in category" class predicts, and by a wide margin on macro-F1. With a single neighbor, kNN was noisy and fell below Naive Bayes on both averages. With 5 neighbors it passed Naive Bayes on macro-F1 but not yet on micro-F1, and with 30 it was the best of the three on both. Its macro-F1 of 0.745 at $k = 30$, against 0.703 for Naive Bayes, suggests that its advantage is larger on the small categories, which carry more weight in the macro average. A plausible reason is that kNN can follow the shape of a small class's region rather than averaging the class away. The experiment does not test that explanation.

How kNN depends on k

Thirty neighbors beat ten, but a hundred do not beat thirty: micro-F1 stays level and macro-F1 falls. Sweeping $k$ from 1 to 100 shows the trade-off between noise and over-smoothing on real data (computed by tools/experiments/reuters/reuters_knn.py, which reproduces the table above):

Notice that the two curves part company for large k. This is micro- and macro-averaged F1 of similarity-weighted kNN on the Reuters test stories as k grows from 1 to 100 (log scale), with Naive Bayes (dashed) and Rocchio (dotted) for reference. Both measures rise steeply up to about k = 7. Micro-F1 then keeps rising more slowly, to 0.898 at k = 75; macro-F1 peaks at 0.758 at k = 7, stays near 0.75 up to k = 30, and then falls, to 0.641 at k = 100, well below Naive Bayes.
Notice that the two curves part company for large k. This is micro- and macro-averaged F1 of similarity-weighted kNN on the Reuters test stories as k grows from 1 to 100 (log scale), with Naive Bayes (dashed) and Rocchio (dotted) for reference. Both measures rise steeply up to about k = 7. Micro-F1 then keeps rising more slowly, to 0.898 at k = 75; macro-F1 peaks at 0.758 at k = 7, stays near 0.75 up to k = 30, and then falls, to 0.641 at k = 100, well below Naive Bayes.

For micro-F1, dominated by the large categories, 100 neighbors are as good as 30: it stays between 0.894 and 0.898 over that range. Macro-F1 falls much faster, because the decision rule requires more than half of the neighbors' similarity weight to lie in the category. Take oilseed, with 124 training stories out of 7,769. Pooled over the oilseed test stories, 49 percent of their 5 nearest neighbors are labeled oilseed, but only 24 percent of their 100 nearest, while half of those 100 are labeled grain. Its F1 falls from 0.568 with 5 neighbors to 0.118 with 100. The neighborhood grows past the size of the class's region, which is the failure the example showed with $k = 7$. A per-category threshold, or $k$ chosen on held-out data, would soften it.

The per-category results show where the methods differ:

Category Rocchio F1 kNN, $k = 30$, F1 Naive Bayes F1
earn 0.949 0.962 0.948
acq 0.907 0.863 0.953
grain 0.599 0.818 0.710
money-supply 0.307 0.737 0.698
dlr 0.335 0.648 0.476
sugar 0.270 0.746 0.619
oilseed 0.285 0.413 0.512
coffee 0.418 0.857 0.807
gnp 0.188 0.759 0.643
gold 0.589 0.653 0.667

Rocchio is competitive only on the two largest categories, and on acq it beats kNN. Those categories hold 58 percent of the training stories between them. So they are well described by their own centroid, and the "everything else" centroid of each is less diffuse than for a small category. On the seven small categories Rocchio's F1 is below 0.6 throughout, and on money-supply, sugar, coffee, and gnp it is less than half of kNN's. kNN beats Naive Bayes on five of the seven small categories. It loses narrowly on gold and clearly on oilseed, the category whose neighborhoods fill with grain stories.

These results agree with the broader literature. In Yang and Liu's (1999) comparison on Reuters, support vector machines (introduced in the next section) and kNN were the strongest of the five methods tested. Naive Bayes was the weakest on the pooled decisions and, with a neural network, on the per-category averages. The largest differences were on categories with few training examples. The comparison here has limits:

  • Naive Bayes was not tuned.
  • Rocchio's negative centroid could be improved.
  • kNN's threshold could be adjusted per category.

Linear classifiers and the bias-variance trade-off

A classifier that stores every example beat two that learn a model. The reason lies in what the two models have in common. Rocchio and Naive Bayes are both linear classifiers. A linear classifier for two classes computes a weighted sum of the document's features and compares it with a threshold. It assigns $\vec{x}$ to the class when $\vec{w} \cdot \vec{x} > b$ (Manning, Raghavan, and Schütze, 2008, §14.4). The points with $\vec{w} \cdot \vec{x} = b$ form a hyperplane, and documents are assigned according to which side they fall on. Rocchio and Naive Bayes differ only in how they choose the hyperplane. Rocchio takes it from the two centroids, as derived above, and Naive Bayes from the log ratios of term probabilities, as derived in Naive Bayes classification, where the threshold is minus the prior log odds.

Other linear methods choose the hyperplane more directly. Logistic regression chooses it to maximize the likelihood of the training labels. Naive Bayes and logistic regression are therefore the same linear form fitted in two ways. Naive Bayes models how each class produces documents and reads the weights off that model. Logistic regression fits the weights to the labels directly. Ng and Jordan (2002) compared the pair. They found that logistic regression has the lower error given enough training data, while Naive Bayes can approach its own, higher, limiting error with far fewer training examples. Logistic regression's probabilities can also satisfy a condition that Naive Bayes's need not. When the model has an intercept and is fitted by unpenalized maximum likelihood, the equation for the intercept forces its fitted probabilities to sum to the number of positive training documents, as the library's logistic regression derives. Naive Bayes's probabilities are under no such constraint. The probabilities of Naive Bayes on Reuters are far from calibrated, as the Bernoulli model and why Naive Bayes works measured.

The support vector machine and its margin

Support vector machines (SVMs) choose the hyperplane by a geometric criterion. Among the hyperplanes that separate the two classes of training documents, they take the one farthest from the nearest document (Cortes and Vapnik, 1995; Manning, Raghavan, and Schütze, 2008, §15.1). The library's support vector machines derives the distance formula, the margin and the optimization problem stated here; this section keeps to the results the course uses.

The SVM literature writes the threshold as an intercept on the left: the classifier is $f(\vec{x}) = \operatorname{sign}(\vec{w} \cdot \vec{x} + b)$, and the training documents are points $\vec{x}_i$ with labels $y_i = \pm 1$. The signed distance from a point to the hyperplane is $(\vec{w} \cdot \vec{x} + b)/\lVert \vec{w} \rVert$. Scaling $\vec{w}$ and $b$ together changes no distance, so the scale is fixed by requiring $y_i(\vec{w} \cdot \vec{x}_i + b) = 1$ at the nearest training point. The hyperplanes $\vec{w} \cdot \vec{x} + b = \pm 1$ then lie $1/\lVert \vec{w} \rVert$ on either side of the boundary, with no training point strictly between them. That empty band is the margin, of width $\rho = 2/\lVert \vec{w} \rVert$. The widest margin has the shortest $\vec{w}$, so the SVM is the solution of

$$\text{minimize } \tfrac{1}{2}\,\vec{w} \cdot \vec{w} \quad\text{subject to}\quad y_i(\vec{w} \cdot \vec{x}_i + b) \ge 1 \text{ for every training point.}$$

At the solution, at least one point of each class satisfies the constraint with equality. To see why, suppose the smallest value of $y_i(\vec{w} \cdot \vec{x}_i + b)$ is $1 + \delta_+$ over the positive class and $1 + \delta_-$ over the negative class, with $\delta_+ + \delta_- > 0$. Adding $(\delta_- - \delta_+)/2$ to $b$ makes both smallest values $1 + \delta$, with $\delta = (\delta_+ + \delta_-)/2 > 0$. Dividing $\vec{w}$ and $b$ by $1 + \delta$ then satisfies every constraint with a shorter $\vec{w}$, so the original was not the minimum. The points that satisfy the constraint with equality are the support vectors. They alone determine the hyperplane. Remove the constraints of all the other points. The original solution still satisfies the constraints that remain. Suppose some other $(\vec{w}', b')$ satisfied them with a smaller $\vec{w}' \cdot \vec{w}'$. The constraints are linear and the objective is convex, so every point on the segment from the original solution toward $(\vec{w}', b')$ would satisfy the remaining constraints and have a smaller objective than the original. The points of the segment close enough to the original would also satisfy the removed constraints, since those held strictly there. That contradicts the original being the minimum. So any other point can be moved, as long as it stays strictly outside the band on its own side, without changing the solution (Manning, Raghavan, and Schütze, 2008, §15.1). Problem 4 below solves a three-point case exactly.

Soft margin and dual. When no hyperplane separates the classes, each point is given a slack variable $\xi_i \ge 0$, the amount by which it falls short of its margin, charged at a rate $C > 0$. The problem becomes to minimize $\tfrac{1}{2}\,\vec{w} \cdot \vec{w} + C \sum_i \xi_i$ subject to $y_i(\vec{w} \cdot \vec{x}_i + b) \ge 1 - \xi_i$ (Cortes and Vapnik, 1995; Manning, Raghavan, and Schütze, 2008, §15.2.1). A large $C$ makes violations expensive and the band narrow. The ranking SVM of the next article is this problem applied to pairs of documents. Both problems are usually solved through a dual problem with one multiplier $\alpha_i \ge 0$ per training point: maximize $\sum_i \alpha_i - \tfrac{1}{2} \sum_i \sum_j \alpha_i \alpha_j y_i y_j \, \vec{x}_i \cdot \vec{x}_j$ subject to $\sum_i \alpha_i y_i = 0$. Its solution gives $\vec{w} = \sum_i \alpha_i y_i \vec{x}_i$, the points with $\alpha_i > 0$ are the support vectors, and in the soft-margin form each multiplier is capped, $\alpha_i \le C$ (§15.1 and §15.2.1). This article does not derive the dual. The library page derives the dual of the separable problem from the Lagrangian and solves a small case by hand. It derives the soft-margin dual in a worked problem, and it continues to kernels.

For text. Joachims (1998) argued that SVMs suit text well: the feature space is very large, few features are irrelevant, document vectors are sparse, and most text categorization problems are linearly separable. He found that they substantially outperformed the methods then standard for text, and they remained the strongest text classifiers for many years. In a space with one dimension per vocabulary term, the hyperplanes have a VC dimension of the vocabulary size plus one (The VC Dimension), so guarantees that do not grow with the vocabulary have to come from other quantities, such as the margin. This unit ran no SVM on Reuters; its measured comparisons are Naive Bayes, Rocchio and kNN.

Bias and variance

The comparison between linear classifiers and kNN illustrates the bias-variance trade-off (Manning, Raghavan, and Schütze, 2008, §14.6). The library's bias-variance tradeoff derives the decomposition of expected error into bias, variance and noise. In outline:

  • A linear classifier has high bias. It can only draw a flat boundary, and it errs consistently where the true boundary is curved. In exchange it has low variance, since small changes in the training data move the boundary little.
  • kNN has low bias, since it can follow any boundary. It has high variance, since its decisions depend on exactly which training documents lie nearby.

Measured on simulated data

Which effect wins depends on the shape of the true boundary, and the trade-off can be measured where the true distribution is known. Two two-dimensional problems were simulated, each with class A a round Gaussian cloud centered at $(5, 6)$ with standard deviation 0.8:

  • One cloud. Class B is a similar cloud centered at $(5, 4.2)$. The best possible boundary is the straight line $y = 5.1$, halfway between the centers, and even it misclassifies 13.0 percent of points, because the clouds overlap.
  • Two clouds. Class B is split evenly between clouds at $(1.8, 5.2)$ and $(8.2, 5.2)$, like the example above. No straight line separates it from A.

For each problem, 30 training sets of 20 points per class were drawn with seeds 0 to 29. Each classifier was trained on each set, and its error was measured on the same 4,000 fresh points (2,000 per class).

Example (variance on the one-cloud problem). On the one-cloud problem, where a straight line is the right shape, kNN with one neighbor errs more than Rocchio, because its boundary chases the particular training points it was given. The table gives the median test error over the 30 runs, with the interquartile range:

Classifier One cloud, median (IQR) Two clouds, median (IQR)
Rocchio 0.129 (0.127–0.136) 0.356 (0.335–0.373)
kNN, $k = 1$ 0.188 (0.174–0.204) 0.054 (0.047–0.069)
kNN, $k = 5$ 0.146 (0.139–0.158) 0.043 (0.039–0.048)
kNN, $k = 15$ 0.135 (0.131–0.143) 0.072 (0.060–0.110)

On the one-cloud problem, Rocchio is essentially optimal. Its median error of 0.129 matches the best possible 0.130 (the difference is sampling noise in the test points), and its interquartile range is the narrowest in the table. kNN with one neighbor errs half again as often.

On the two-clouds problem the roles reverse. Rocchio's bias dominates, and it misclassifies about a third of the points. No straight line separates the classes, so more data would not cure that. Meanwhile kNN with five neighbors errs on 4.3 percent. With 15 neighbors and only 20 points per class, about 10 in each of B's clouds, error rises again. A plausible reason is the one the fourteen-point example showed with $k = 7$: the neighborhoods are larger than a cloud and reach across into A. The simulation records the error rates only, so this reading is an inference from the example and not a separate measurement.

The figure shows the variance directly, for the one-cloud problem:

Notice that the Rocchio lines barely move while the 1NN boundaries wander. These are decision boundaries learned from five different training sets of 20 points per class, drawn from the same one-cloud distribution, for Rocchio (left) and 1NN (right). The dotted gray line is the best possible boundary. The five Rocchio lines stay straight and near it, tilting a little from one training set to the next. The five 1NN boundaries each follow their own training points.
Notice that the Rocchio lines barely move while the 1NN boundaries wander. These are decision boundaries learned from five different training sets of 20 points per class, drawn from the same one-cloud distribution, for Rocchio (left) and 1NN (right). The dotted gray line is the best possible boundary. The five Rocchio lines stay straight and near it, tilting a little from one training set to the next. The five 1NN boundaries each follow their own training points.

With a single neighbor, the variance dominates. Raising $k$ trades some of that variance for bias. On Reuters the trade improved macro-F1 up to about $k = 7$ and micro-F1 up to about $k = 40$, with little change after that (its peak, 0.898 at $k = 75$, is 0.001 higher). Which side of the trade-off wins depends on the data. Here, kNN's flexibility beat the two linear classifiers. A better-chosen hyperplane can reverse that. In Joachims's (1998) experiments on Reuters a support vector machine outperformed kNN. A linear classifier also classifies far faster, as the cost table shows. Fine-tuned neural language models have since set the state of the art: BERT reported new best results on eleven language tasks, sentence classification among them (Devlin, Chang, Lee, and Toutanova, 2019). Such models learn a nonlinear representation of the text on which a simple final layer, itself a linear classifier, can separate the classes.

Worked problems

Problems 1, 2 and 3 are Exercises 14.6, 14.2 and 14.3 of the course text (Manning, Raghavan, and Schütze, 2008), restated in our own words; Problems 2 and 3 are answered on this article's fourteen-point example. Problem 4 is the text's Example 15.1 together with its Exercises 15.1 and 15.2. The derivation of the Rocchio hyperplane above answers the text's Exercise 14.15. The script tools/experiments/reuters/toy2d.py recomputes every number.

Problem 1. Let $\vec{x} = (2, 2)$, $\vec{a} = (0.5, 1.5)$, $\vec{b} = (4, 4)$ and $\vec{c} = (8, 6)$. Which of $\vec{a}$, $\vec{b}$, $\vec{c}$ is (i) most similar to $\vec{x}$ by dot product, (ii) most similar to $\vec{x}$ by cosine similarity, (iii) closest to $\vec{x}$ in Euclidean distance?

Solution. The lengths are $\lVert \vec{x} \rVert = \sqrt{8} = 2.828$, $\lVert \vec{a} \rVert = \sqrt{2.5} = 1.581$, $\lVert \vec{b} \rVert = \sqrt{32} = 5.657$ and $\lVert \vec{c} \rVert = 10$.

Vector Dot product with $\vec{x}$ Cosine with $\vec{x}$ Distance from $\vec{x}$
$\vec{a}$ $1 + 3 = 4$ $4/(1.581 \times 2.828) = 0.894$ $\sqrt{1.5^2 + 0.5^2} = 1.581$
$\vec{b}$ $8 + 8 = 16$ $16/(5.657 \times 2.828) = 1.000$ $\sqrt{2^2 + 2^2} = 2.828$
$\vec{c}$ $16 + 12 = 28$ $28/(10 \times 2.828) = 0.990$ $\sqrt{6^2 + 4^2} = 7.211$

(i) $\vec{c}$, with dot product 28. (ii) $\vec{b}$, with cosine 1: it points in exactly the direction of $\vec{x}$. (iii) $\vec{a}$, at distance 1.581. The three measures give three different answers, because the dot product rewards length, the cosine ignores it, and distance penalizes a difference in length. For vectors of length 1 the three always agree, since then the cosine is the dot product and $\lVert \vec{x} - \vec{y} \rVert^2 = 2 - 2\,\vec{x} \cdot \vec{y}$, as in the cosine version of Rocchio above. That is one reason document vectors are length-normalized before classification. Similarity Measures for Embeddings proves the converse as well: the three measures rank alike for every query exactly when all the stored vectors have one length.

Problem 2. Show that Rocchio classification can assign a training document a label different from its label in the training set.

Solution. The fourteen-point example is a case. The training point $(4.6, 5.2)$ is labeled A. Its distance to A's centroid $(5.000, 6.117)$ is $\sqrt{0.4^2 + 0.917^2} = 1.000$, and its distance to B's centroid $(5.025, 4.975)$ is $\sqrt{0.425^2 + 0.225^2} = 0.481$. It is nearer to B's centroid, so Rocchio assigns it to B. In all, Rocchio relabels 4 of its 14 training points, as listed above. The reason is general: Rocchio keeps only the centroids, and a training document can lie nearer to another class's centroid than to its own whenever its class is spread out or the classes overlap. A 1-nearest-neighbor classifier cannot do this unless two training documents with different labels have identical vectors, since each training document is its own nearest neighbor, at distance zero.

Problem 3. Explain why kNN handles multimodal classes better than Rocchio.

Solution. A class is multimodal when its documents form several separate groups, as class B does in the example. Rocchio represents the class by one point, the centroid, which for a multimodal class lies between the groups and may be near none of them. In the example every B point is at least 2.425 from B's centroid, while five of the six A points are closer to B's centroid than that, the nearest at 0.481. The region Rocchio gives to B is the half-plane on B's side of the bisector. It contains two A points and leaves two B points outside, and the star inside B's left cloud is assigned to A. By contrast, kNN never forms a summary of the class. It decides from the training points nearest the new document, so each group of a multimodal class speaks for its own neighborhood. The star's three nearest neighbors are all B points, and kNN assigns it to B for $k = 1, 3, 5$ and 7. The condition for kNN to work is local, that near each document most training points share its class. It fails when $k$ exceeds what a group can supply, as the leave-one-out test with $k = 7$ showed.

Problem 4. The training set has three points: $(1, 1)$ and $(2, 0)$ in the class $y = -1$, and $(2, 3)$ in the class $y = +1$. (i) Find the maximum margin hyperplane and its margin, and prove that no separating hyperplane has a wider margin. (ii) What is the smallest number of support vectors a training set with both classes can have? (iii) Write the classifier in the dual form $f(\vec{x}) = \operatorname{sign}\big(\sum_i \alpha_i y_i \, \vec{x}_i \cdot \vec{x} + b\big)$.

Solution. (i) The two closest points of opposite classes are $(1, 1)$ and $(2, 3)$, at distance $\sqrt{1^2 + 2^2} = \sqrt{5}$. Try the hyperplane that bisects the segment between them at right angles. Its normal vector is along $(2, 3) - (1, 1) = (1, 2)$, so $\vec{w} = (a, 2a)$ for some $a > 0$. Requiring the two points to be support vectors gives

$$a + 2a + b = -1, \qquad 2a + 6a + b = +1.$$

Subtracting, $5a = 2$, so $a = 2/5$ and $b = -1 - 3a = -11/5$. The candidate is $\vec{w} = (2/5, 4/5)$, $b = -11/5$, that is, the line $x_1 + 2x_2 = 5.5$. Check the third point: $\vec{w} \cdot (2, 0) + b = 4/5 - 11/5 = -7/5 \le -1$, so its constraint holds, with room to spare. All three constraints hold, and the margin is

$$\rho = \frac{2}{\lVert \vec{w} \rVert} = \frac{2}{\sqrt{4/25 + 16/25}} = \frac{2}{2/\sqrt{5}} = \sqrt{5} = 2.236.$$

No hyperplane does better. Let $(\vec{w}, b)$ satisfy all the constraints. The constraints of $(2, 3)$ and $(1, 1)$ read $\vec{w} \cdot (2, 3) + b \ge 1$ and $\vec{w} \cdot (1, 1) + b \le -1$. Subtracting the second from the first, $\vec{w} \cdot (1, 2) \ge 2$. By the Cauchy-Schwarz inequality $\vec{w} \cdot (1, 2) \le \lVert \vec{w} \rVert \sqrt{5}$, so $\lVert \vec{w} \rVert \ge 2/\sqrt{5}$ and the margin $2/\lVert \vec{w} \rVert$ is at most $\sqrt{5}$. The candidate attains that bound, so it is the maximum margin hyperplane. This is the course text's answer. The margin equals the distance between the two closest points of opposite classes, which is as wide as any band between the classes can be.

(ii) Two. The argument in the body showed that at the solution at least one point of each class satisfies its constraint with equality, so there are at least two support vectors, one from each class. This example has exactly two, $(1, 1)$ and $(2, 3)$; the point $(2, 0)$ is not one, since its constraint holds strictly.

(iii) Only support vectors have nonzero multipliers, so $\vec{w} = \alpha_1 y_1 \vec{x}_1 + \alpha_3 y_3 \vec{x}_3 = -\alpha_1 (1, 1) + \alpha_3 (2, 3)$, where the subscripts follow the order in which the points were listed. The dual constraint $\sum_i \alpha_i y_i = 0$ gives $-\alpha_1 + \alpha_3 = 0$, so $\alpha_1 = \alpha_3 = \alpha$ and $\vec{w} = \alpha\,(1, 2)$. Matching $\vec{w} = (2/5, 4/5)$ gives $\alpha = 2/5$. So

$$f(\vec{x}) = \operatorname{sign}\Big( \tfrac{2}{5}\,(2, 3) \cdot \vec{x} - \tfrac{2}{5}\,(1, 1) \cdot \vec{x} - \tfrac{11}{5} \Big).$$

The training points enter only through dot products with $\vec{x}$. As a check, the dual objective is $\sum_i \alpha_i - \tfrac{1}{2} \lVert \vec{w} \rVert^2 = \tfrac{4}{5} - \tfrac{1}{2} \cdot \tfrac{4}{5} = \tfrac{2}{5}$, equal to the primal objective $\tfrac{1}{2} \lVert \vec{w} \rVert^2 = \tfrac{2}{5}$.

What we have learned

Vector space classification places documents in the space retrieval already built and classifies them by position. Rocchio summarizes each class by its centroid, which gives a linear boundary, the perpendicular bisector between two centroids. That fails for diffuse classes, as the star in B's left cloud and the "not in category" side of every Reuters category show. kNN keeps every training document and votes among the nearest. It follows classes of any shape, at the cost of variance and a choice of $k$. Rocchio and Naive Bayes are linear classifiers, and so is the support vector machine, which chooses the separating hyperplane with the widest margin, $2/\lVert \vec{w} \rVert$. On ten Reuters categories, kNN with 30 neighbors reached 0.894 micro-F1 and 0.745 macro-F1, ahead of Naive Bayes at 0.884 and 0.703, and Rocchio trailed both.

Every method so far has assigned classes to documents. A ranking function can be learned from labeled examples in the same way, with judged query-document pairs in place of documents and an ordering in place of a class. Learning to rank closes the unit with that application.

References

  • Cortes, C., and Vapnik, V. (1995). Support-vector networks. Machine Learning, 20(3), 273–297. record · 4 pages
  • Cover, T. M., and Hart, P. E. (1967). Nearest neighbor pattern classification. IEEE Transactions on Information Theory, 13(1), 21–27. record · 3 pages
  • Devlin, J., Chang, M.-W., Lee, K., and Toutanova, K. (2019). BERT: Pre-training of deep bidirectional transformers for language understanding. In Proceedings of NAACL-HLT 2019, 4171–4186. record · 5 pages
  • Joachims, T. (1998). Text categorization with support vector machines: Learning with many relevant features. In Proceedings of ECML 1998, 137–142. record
  • Manning, C. D., Raghavan, P., and Schütze, H. (2008). Introduction to Information Retrieval, chapter 14 and sections 15.1 and 15.2.1. Cambridge University Press. record · 102 pages
  • Ng, A. Y., and Jordan, M. I. (2002). On discriminative vs. generative classifiers: A comparison of logistic regression and naive Bayes. In Advances in Neural Information Processing Systems 14 (NIPS 2001), 841–848. record
  • Yang, Y., and Liu, X. (1999). A re-examination of text categorization methods. In Proceedings of SIGIR 1999, 42–49. record · 2 pages

Reviewed: verified, 16 Nov 2026 · checked against sources, 23 Nov 2026 · citations checked, 16 Nov 2026 · editorial review, 23 Nov 2026 · 15 revisions