Logistic regression and discriminant analysis estimate class probabilities before making a decision. A support vector machine (SVM) approaches classification through the geometry of the decision boundary. If several lines separate the training classes, which one should we choose?
We start with the maximum-margin classifier for linearly separable data. We then introduce slack variables for overlapping classes. The next lecture uses the same idea to construct nonlinear boundaries with kernels.
Learning goals
By the end of this lecture, you should be able to:
connect the linear score, decision boundary, and geometric margin;
explain why only support vectors determine the fitted boundary;
interpret slack variables and the cost parameter ; and
choose using cross-validation with scaling fitted within each training fold.
Maximum-margin classifier
Suppose we observe training data , where contains predictors. For this lecture, code the two classes as . This changes the labels used in Week 6, but not the classification problem. The advantage is that multiplying a score by its label lets us describe both classes in one expression.
Consider the linear score
where contains the coefficients and is an intercept. Its decision rule is
Away from a tie at zero, a correct classification satisfies . The score tells us which side of the boundary contains ; it is not a class probability.
Letβs look at two small normal clouds with independent coordinates. Each coordinate has variance one, with mean zero in the negative class and mean three in the positive class. The R and Python simulations use the same data-generating process, with different random draws. Run the blocks in your chosen language in order.
There are many lines that perfectly separate these two classes. Training accuracy cannot distinguish them. The SVM chooses the line with the greatest distance to the closest observations on either side. This distance is the margin.
We use e1071::svm in R and SVC in Python. Both fit a soft-margin SVM, which has a cost parameter . For this separable example, is large enough to recover the hard-margin solution. We will explain the role of when the classes overlap.
The solid line is the decision boundary. The dotted lines touch the closest observations, shown with circles. These observations support the fitted boundary. Moving a point that is far outside the margin slightly will not change this solution.
Linearly separable SVM
The equation describes a hyperplane. Its normal vector is . To calculate the distance to it, take a point on the hyperplane, so , and project onto the unit vector :
The normal vector, a point on the separating hyperplane, and the projection used to calculate distance.
This is a signed distance: it is positive on one side and negative on the other. Its absolute value is the distance to the hyperplane. Multiplication by makes the distance positive when observation is on the correct side.
We want every observation to be on the correct side, at least a distance from the boundary:
Multiplying both and by a positive constant leaves the boundary and these distances unchanged. We can therefore choose the scale so that the smallest value of is one. Then , and maximizing is equivalent to the primal problem
This explains the lines at and in the figure. Each is from the decision boundary; the full width between them is .
From primal to dual
The primal problem has a constraint for every observation. The dual formulation gives a coefficient to each constraint and will explain why only some observations determine the fitted boundary. It will also show where a kernel can enter.
For a general constrained problem
introduce nonnegative multipliers and form the Lagrangian
For fixed , maximizing over makes any violated constraint infinitely costly. If the constraints hold, the maximum contribution from their terms is zero. Thus the primal can be written as . Reversing the order gives the dual, .
The dual optimum cannot exceed the primal optimum. For this separable SVM, the two optima agree: the objective is convex, the constraints are linear, and scaling a separating rule gives strict inequalities. We can solve the dual to recover the primal solution.
For the SVM, the Lagrangian is
First minimize over and . The derivatives give
Substituting these identities into the Lagrangian leaves
Therefore the dual problem is
The constraints now have a simple feasible starting point, . More importantly, the data enter only through inner products . We will return to this property for nonlinear classification.
At the solution, complementary slackness gives
If , observation must lie on a margin. These observations are the support vectors. Their coefficients determine
For the hard-margin solution, the intercept puts the boundary halfway between the closest projections from the two classes:
We then use the sign of to make the decision . This is the coefficient calculation used in the first example.
Reading the software output
The first R example obtains beta_hat from coefs, which contains for the support vectors, and SV, which contains their predictor values. The field index gives their row indices, and rho is the negative intercept.
In Python, coef_ contains the fitted coefficients, intercept_ contains the intercept, and support_ gives the support-vector row indices. The field dual_coef_ contains their values. These quantities connect the fitted software object to the dual representation above.
Linearly non-separable SVM with slack variables
When the two classes overlap, the hard-margin constraints cannot all hold. We introduce a nonnegative slack variable for each observation:
The new problem is
Here controls the cost of violating the margin. For fixed coefficients, the smallest feasible slack is . Since positive slack costs something, this is its value at the optimum.
If , the observation is correctly classified and lies on or beyond its margin.
If , it is correctly classified but lies inside the margin.
If , it lies on the decision boundary.
If , it is misclassified.
Observations on a margin, inside a margin, and on the wrong side of the decision boundary.
A larger makes slack more expensive relative to the coefficient norm. A smaller allows a wider margin while tolerating more total slack. This is a tradeoff in the objective, not a guarantee about how the number of classification errors changes.
Applying the same Lagrangian argument gives
The only change from the hard-margin dual is the upper bound . All observations with are support vectors. Those with lie on a margin. Those with can lie inside the margin or be misclassified.
For a support vector with , we can recover the intercept from :
Software handles the case where no such support vector is available. The hard-margin midpoint formula should not be applied to all observations when the classes overlap.
Letβs generate two closer normal clouds, again with independent coordinates of variance one. The coordinate means are zero in the negative class and in the positive class. We fit the same data with and . The circled points include all support vectors, not only those on a margin.
The smaller cost gives a smaller coefficient norm and a wider margin. More observations participate in the fit as support vectors. Neither plot by itself tells us which choice predicts new observations better. For that, we need validation data or cross-validation.
Example: SAheart data
We now return to the South African heart disease data used in the discriminant-analysis lecture. We fit a linear SVM using all nine predictors to classify chd. The supplied data and fold assignments let R and Python use the same observations and the same three repeats of 10-fold cross-validation.
For this example, the software accepts the original 0/1 labels and handles the internal two-class encoding. We do not need to recode them manually to and .
We compare 20 costs from 0.01 to 2. Predictor means and sample standard deviations are estimated separately within each training fold. Each validation fold uses those same transformations. Save the supplied files in the folders shown in the code and run from the folder containing data/.
library(caret)heart <-read.csv("data/classification/saheart.csv")heart$famhist <-factor(heart$famhist, levels =c("Absent", "Present"))heart$chd <-factor(heart$chd)folds <-as.matrix(read.csv("data/svm/saheart-cv-folds.csv")[, -1])# caret takes the training indices for each validation fold.index <-list()for (r in1:3) {for (k in1:10) { index[[paste0("Fold", k, ".Rep", r)]] <-which(folds[, r] != k) }}train_control <-trainControl(method ="repeatedcv", number =10,repeats =3, index = index)cost_grid <-expand.grid(cost =seq(0.01, 2, length.out =20))svm_fit <-train(chd ~ ., data = heart, method ="svmLinear2",preProcess =c("center", "scale"), scale =FALSE,trControl = train_control, tuneGrid = cost_grid,tolerance =1e-7)svm_fit$results[which.max(svm_fit$results$Accuracy), c("cost", "Accuracy")]
cost Accuracy
2 0.1147368 0.7220937
The method svmLinear2 uses e1071. The preProcess argument fits the transformation within each fold; scale = FALSE disables a second scaling step inside svm.
Show the reproducible code
heart = pd.read_csv("data/classification/saheart.csv")heart["famhist"] = heart["famhist"].eq("Present").astype(int)X = heart.drop(columns="chd").to_numpy(float)y = heart["chd"].to_numpy()folds = pd.read_csv("data/svm/saheart-cv-folds.csv").iloc[:, 1:].to_numpy()costs = np.linspace(0.01, 2, 20)accuracy = np.empty((30, len(costs)))for r inrange(3):for k inrange(1, 11): training = folds[:, r] != k center = X[training].mean(axis=0) scale = X[training].std(axis=0, ddof=1) X_train = (X[training] - center) / scale X_valid = (X[~training] - center) / scalefor j, cost inenumerate(costs): fit = SVC(kernel="linear", C=cost, tol=1e-7) fit.fit(X_train, y[training]) accuracy[10* r + k -1, j] = fit.score(X_valid, y[~training])mean_accuracy = accuracy.mean(axis=0)best = mean_accuracy.argmax()print(pd.DataFrame({"cost": [costs[best]], "Accuracy": [mean_accuracy[best]]}))
cost Accuracy
0 0.114737 0.722094
Show the reproducible code
# Refit the selected model using all available observations.center = X.mean(axis=0)scale = X.std(axis=0, ddof=1)svm_fit = SVC(kernel="linear", C=costs[best], tol=1e-7)svm_fit.fit((X - center) / scale, y)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
The sample standard deviation, ddof=1, matches Rβs preprocessing. Within each fold, the same transformation is reused for every cost. argmax selects the first cost when values tie, so this increasing grid favors the smaller cost.
For these folds, the best cost is approximately , with mean cross-validation accuracy . These values describe the stated comparison; a different set of folds can give a different selected cost. The reported accuracy is used for tuning, not a separate test-set estimate. The R train function also refits the selected model using all observations.
In practice, we could start with a wider cost grid and refine it where the results look promising. Changing the measurement units also changes the meaning of the margin, which is why scaling is useful in this example. The tiny simulated examples above use coordinates on the same scale so their geometry is easy to see.
Check your understanding
Why does multiplying every coefficient by the same positive constant leave the boundary unchanged?
What do slack values of zero, between zero and one, and greater than one tell us about an observation?
Why can a soft-margin support vector lie away from a margin line?
Why does the cross-validation accuracy used to choose differ from a final test-set assessment?
Key ideas
The maximum-margin classifier chooses a separating boundary using its distance from the closest training observations.
Slack variables allow overlap. The cost controls the balance between a small coefficient norm and margin violations.
Support vectors have positive dual coefficients. In the soft-margin case, they need not all lie on a margin.
Scale predictors when their units differ, and use cross-validation to choose .