Course contents 09 / 27

09 / 27 · Linear Classification

Linear classifiers and surrogate losses

Separating two classes with a hyperplane: the geometry of a linear classifier and the distance to its boundary, the margin, why the number of errors cannot be minimized directly, the convex surrogate losses that bound it (logistic, hinge, exponential, squared hinge) and what each of them estimates, the perceptron as stochastic gradient descent, linear separability, and what a regularizer adds.

On this page 9

A system routes a request to one of two queues. It needs a class decision; predicting a number close to the encoded label is only one possible way to train it. The choice matters: two models can make the same decisions while their training losses strongly disagree.

Let x∈Rdx\in\mathbb R^d, y∈{−1,+1}y\in\{-1,+1\} and f(x)=wTx+bf(x)=w^Tx+b. Predict +1+1 when f(x)≥0f(x)\ge0 and −1-1 otherwise. We will keep this tie rule separate from the stricter training requirement that every signed score be positive. All finite coordinates, counts and traces below are teaching fixtures specified for this course with Codex assistance. They are not observations from a service or outputs of a published benchmark. The verification script uses only Python’s standard library.

Why not least squares on the labels?#

Consider a one-dimensional feature with negative examples at −4,−2-4,-2 and positive examples at 1,31,3. Fitting an intercept and a slope to labels ±1\pm1 gives

f(x)=10x+529.f(x)=\frac{10x+5}{29}.

Its boundary is −1/2-1/2 and all four signs are correct. Add a positive example at 4040. The least-squares solution becomes

f(x)=106x−1353353.f(x)=\frac{106x-135}{3353}.

The boundary moves to 135/106≈1.274135/106\approx1.274, making the example at 11 negative. Yet f(x)=x+1/2f(x)=x+1/2 still separates all five examples. The verifier calculates both fits using exact fractions, so this difference is not a numerical solver artifact.

For a label y=±1y=\pm1, squared error is (y−f)2=(1−yf)2(y-f)^2=(1-yf)^2. A correctly classified point with score much larger than its label keeps contributing error. Least squares spends its slope fitting that numerical target, even when this harms a nearby decision. This example shows a mismatch between objectives; it does not say that least-squares classification always fails.

A hyperplane splits the space#

For w≠0w\ne0, the decision boundary wTx+b=0w^Tx+b=0 is a hyperplane. Any displacement vv within it satisfies wTv=0w^Tv=0, so ww is normal to the boundary and points towards positive scores. Move a point along that normal until it reaches the boundary:

x⊥=x−f(x)∥w∥2w,r=f(x)∥w∥.x_\perp=x-\frac{f(x)}{\lVert w\rVert^2}w, \qquad r=\frac{f(x)}{\lVert w\rVert}.

Substitution gives f(x⊥)=0f(x_\perp)=0; rr is the signed distance. Multiplying both ww and bb by a positive constant changes the score but leaves this distance and the decisions unchanged. If w=0w=0, the score is constant and these distance formulas do not apply.

For the new geometry fixture, set w=(2,−1)w=(2,-1) and b=−1b=-1. Point E=(3,1)E=(3,1) has score 44, distance 4/5≈1.7894/\sqrt5\approx1.789 and projection (1.4,1.8)(1.4,1.8). Indeed, 2(1.4)−1.8−1=02(1.4)-1.8-1=0.

Figure

Seven specified points and one boundary

Normal and distance to a linePoints A–G have margins 4, 3, 1, 2, 4, −1, −3. Blue circles mark the positive class; red squares mark the negative class. A dashed line connects E=(3,1) to its projection (1.4,1.8).-2-101234-3-2-1012345ABCDEFGww = (2, −1), b = −1E = (3, 1), f(E) = 4Projection: (1.4, 1.8)Distance: 4/√5 ≈ 1.789● class +1 ■ class −1Normal and distance to a linePoints A–G have margins 4, 3, 1, 2, 4, −1, −3. Blue circles mark the positive class; red squares mark the negative class. A dashed line connects E=(3,1) to its projection (1.4,1.8).-2-101234-3-2-1012345ABCDEFGww = (2, −1), b = −1E = (3, 1), f(E) = 4Projection: (1.4, 1.8)Distance: 4/√5 ≈ 1.789● class +1 ■ class −1
The boundary 2x₁ − x₂ − 1 = 0 misclassifies F and G. The perpendicular from E has length 4/√5. Equal axis scales preserve angles. All coordinates are specified for this example.

The margin#

The functional margin is Mi=yif(xi)M_i=y_i f(x_i). A positive margin means the score is on the label’s side; a negative margin means an error. For w≠0w\ne0, Mi/∥w∥M_i/\lVert w\rVert is the signed geometric margin. A large functional margin alone is not a probability or an invariant confidence measure: rescaling the weights can make it arbitrarily large.

At zero score our prediction rule chooses +1+1. Thus a positive label on the boundary is classified correctly, although it has no positive margin. The conservative margin-error count

R^≤0=1n∑i[Mi≤0]\widehat R_{\le0}=\frac1n\sum_i[M_i\le0]

counts every boundary point as an error and upper-bounds the actual classification error under the stated tie rule. Away from zero they coincide. In the figure, margins A–G are 4,3,1,2,4,−1,−34,3,1,2,4,-1,-3, so both error rates equal 2/72/7.

Why the error count cannot be minimized directly#

Moving a boundary slightly usually leaves its predictions unchanged. The empirical error is therefore constant between crossings, with zero gradients on those regions and jumps when a point crosses. Ordinary gradient descent gets no direction from such an objective.

This is an optimization obstacle, not a claim that every finite instance is impossible. In one dimension we can test boundaries between sorted feature values. In unrestricted dimension, finding near-optimal halfspaces in nonseparable learning problems has computational hardness results; see Höffgen, Simon and Van Horn for their precise learning setting. For a finite strictly separable set, the linear constraints yi(wTxi+b)≥1y_i(w^Tx_i+b)\ge1 are feasible after rescaling a separator. Linear programming can find such a separator.

At the population level, let η(x)=P(y=+1∣x)\eta(x)=P(y=+1\mid x). With equal error costs, choosing the more probable class minimizes the conditional error. The remaining problem is to obtain useful training directions while keeping that decision target.

Surrogate losses: upper bounds that can be minimized#

A surrogate replaces the discontinuous margin penalty with a tractable function ϕ(M)\phi(M). For example,

ϕlog(M)=log⁡(1+e−M)log⁡2,ϕhinge(M)=max⁡(0,1−M),ϕexp(M)=e−M,ϕsqh(M)=max⁡(0,1−M)2.\begin{aligned} \phi_{\mathrm{log}}(M)&=\frac{\log(1+e^{-M})}{\log2},\\ \phi_{\mathrm{hinge}}(M)&=\max(0,1-M),\\ \phi_{\mathrm{exp}}(M)&=e^{-M},\\ \phi_{\mathrm{sqh}}(M)&=\max(0,1-M)^2. \end{aligned}

Each is nonnegative and at least 11 when M≤0M\le0. Therefore the average of each bounds R^≤0\widehat R_{\le0}. The usual natural-log logistic loss needs the displayed factor 1/log⁡21/\log2 for this particular unit upper bound; scaling changes neither an unregularized minimizer nor the sign of its gradient. With a fixed regularization coefficient, scaling only the data loss changes the tradeoff, so adjust the coefficient as well when comparing conventions.

Figure

One dataset, two upper bounds

PointMErrorLogisticHinge
A400.0260.000
B300.0700.000
C100.4520.000
D200.1830.000
E400.0260.000
F-111.8952.000
G-314.3984.000
Mean—0.2861.0070.857
Points from the preceding figure. The error fraction is 2/7 ≈ 0.286; mean losses are 1.007 and 0.857. An upper bound can exceed the actual error fraction and even one. Positive margins still contribute logistic loss.

For our seven points, the average logistic upper bound is 1.0071.007 and the hinge bound is 0.8570.857, while the actual error fraction is 0.2860.286. The bound need not be tight or lie below 11. Squared error (1−M)2(1-M)^2 also bounds the conservative margin penalty; its failure in the opening example is not a failure of this inequality.

All four surrogate objectives are convex in the linear parameters. This rules out nonglobal local minima, but it does not ensure that a finite minimizer exists or that an arbitrary step schedule converges. Logistic and exponential losses are smooth; hinge needs a subgradient at its kink; squared hinge has a continuous first derivative and a discontinuous second derivative at M=1M=1. We return to existence below.

The losses react differently to negative margins. Hinge and logistic grow linearly far to the left, exponential grows exponentially, and squared hinge grows quadratically. They cease increasing as a correct margin grows. This reduces the pressure to fit already-correct numerical labels. It does not make the estimator immune to outliers: the parameter gradient also contains the feature vector, which can have a large norm.

What each surrogate estimates#

Hold the feature value fixed. Its conditional surrogate risk is

Cη(f)=ηϕ(f)+(1−η)ϕ(−f).C_\eta(f)=\eta\phi(f)+(1-\eta)\phi(-f).

For natural-log logistic loss, differentiation gives Cη′(f)=σ(f)−ηC'_\eta(f)=\sigma(f)-\eta, where σ(f)=1/(1+e−f)\sigma(f)=1/(1+e^{-f}). For 0<η<10<\eta<1, the unique pointwise optimum is f∗=log⁡(η/(1−η))f^*=\log(\eta/(1-\eta)). Base-two scaling preserves this optimum. At η=0\eta=0 or 11, the infimum is approached only at an infinite score.

To see why this does not guarantee recovery of the feature-conditional probabilities, specify three equally likely feature values x=−1,0,1x=-1,0,1. Imagine eight possible requests at each value, with respectively 1,7,11,7,1 positive labels. These counts define a finite fictional distribution, not estimates from collected data. Independent scores can use −log⁡7,+log⁡7,−log⁡7-\log7,+\log7,-\log7. Their mean base-two logistic risk is 0.5440.544, and their decision error is 3/24=0.1253/24=0.125.

A linear score wx+bwx+b cannot put the middle point above both endpoints. For this symmetric distribution its logistic optimum is w=0w=0, b=log⁡(3/5)b=\log(3/5): the predicted probability is the pooled positive share 9/24=3/89/24=3/8. Grouped by its single probability prediction, this constant model is calibrated, but it loses the feature-dependent probabilities. To check optimality, sum the residuals σ(b)−η(x)\sigma(b)-\eta(x) and their products with xx; both sums are zero. Positive conditional class probabilities and the full-rank design make the logistic Hessian positive definite. The resulting risk is 0.9540.954 and error 9/24=0.3759/24=0.375. Giving the model more data from this same distribution cannot remove its linear restriction. A feature x2x^2 can represent the three pointwise log-odds exactly.

Other losses preserve different information. On −1≤f≤1-1\le f\le1, conditional hinge risk is 1+(1−2η)f1+(1-2\eta)f; its optimum is the endpoint with the majority sign when η≠1/2\eta\ne1/2 and 0<η<10<\eta<1. At η=1/2\eta=1/2, every score in [−1,1][-1,1] minimizes it, so no unique probability can be read from that optimum. The exponential derivative vanishes when e2f=η/(1−η)e^{2f}=\eta/(1-\eta). For squared error, expanding Cη(f)C_\eta(f) gives 1+f2+2(1−2η)f1+f^2+2(1-2\eta)f, minimized at 2η−12\eta-1; squared hinge has that same unique optimum for interior probabilities. At the endpoints, squared hinge has a whole half-line of minimizers.

These calculations concern unrestricted pointwise risk. The relevant population property is classification calibration: for η≠1/2\eta\ne1/2, minimizing conditional surrogate risk prefers the majority sign. Bartlett, Jordan and McAuliffe characterize a nonnegative convex surrogate by differentiability at zero and a negative derivative there. The property does not remove approximation error from a restricted model, estimation error from a finite sample, or error from unfinished optimization. At equal class probabilities, either class decision has the same Bayes error.

The perceptron: stochastic gradient descent at zero margin#

The perceptron updates after a nonpositive margin:

w←w+yixi,b←b+yi.w\leftarrow w+y_i x_i,\qquad b\leftarrow b+y_i.

This is an incremental subgradient step for max⁡(0,−M)\max(0,-M), choosing the nonzero endpoint subgradient at M=0M=0. The loss is convex but is not a unit upper bound on [M≤0][M\le0]. In particular, the zero parameter vector has zero perceptron loss; the specified update at the kink prevents the algorithm from simply staying there. A fixed cyclic presentation is incremental training; randomly sampling examples gives the usual stochastic interpretation. A fixed positive step size from zero only rescales the entire sequence.

Use four newly specified points in this order: (2,−1)(2,-1) positive, (−1,2)(-1,2) negative, (3,1)(3,1) positive and (0,−3)(0,-3) negative. Starting from (w1,w2,b)=(0,0,0)(w_1,w_2,b)=(0,0,0), the updates are:

Pass and pointMargin beforeParameters after
1, point 100(2,−1,1)(2,-1,1)
1, point 4−4-4(2,2,0)(2,2,0)
2, point 2−2-2(3,0,−1)(3,0,-1)

All other visits leave the parameters unchanged. Final margins are 5,4,8,15,4,8,1; a complete pass without updates confirms separation. The count of three updates is specific to these points and this order.

For the convergence argument, append a constant 11 to each feature vector and include the bias in a parameter vector vv. Suppose a unit vector uu satisfies yiuTxi≥γ>0y_i u^T x_i\ge\gamma>0 in this augmented space and ∥xi∥≤R\lVert x_i\rVert\le R. After each update, progress along uu grows by at least γ\gamma, while the squared norm grows by at most R2R^2, because the previous margin was nonpositive. After kk updates,

kγ≤vkTu≤∥vk∥≤kR,k≤R2/γ2.k\gamma\le v_k^Tu\le\lVert v_k\rVert\le\sqrt{k}R, \qquad k\le R^2/\gamma^2.

This is the Block–Novikoff mistake bound, stated with its proof in Freund and Schapire, Theorem 1. In our fixture, u=(2,0,−1)/5u=(2,0,-1)/\sqrt5, R2=11R^2=11, and γ2=1/5\gamma^2=1/5 give a bound of 5555. It bounds updates, not passes or generalization error. If a fixed dataset is inseparable, cycling through it cannot reach a pass with every margin positive; a practical implementation needs a stopping rule.

Linear separability#

A set is strictly linearly separable when some linear score gives every label a positive margin. The deterministic pattern negative–positive–negative at x=−1,0,1x=-1,0,1 cannot be separated by a single threshold, but 1−2x21-2x^2 separates it after adding a quadratic feature. In two dimensions XOR gives another obstruction: the two class convex hulls meet at the centre of the square. Adding interactions changes the representation, as kernels and neural networks develop.

The opposite issue is fitting arbitrary labels with enough dimensions. For nn points in affine general position in Rd\mathbb R^d and independently fair binary labels, Cover’s function-counting result gives

P(n,d)=21−n∑k=0min⁡(d,n−1)(n−1k).P(n,d)=2^{1-n}\sum_{k=0}^{\min(d,n-1)}\binom{n-1}{k}.

General position matters: it requires affine independence of every subset of at most d+1d+1 points. The formula is 11 for n≤d+1n\le d+1 and 1/21/2 at n=2(d+1)n=2(d+1). It concerns random label assignments, not an accuracy guarantee for real future examples.

We can verify a small case exactly. Take points (t,t2)(t,t^2) for distinct integer tt. No three are collinear, and a linear score on these points is a quadratic in tt. Its strict signs can change at most twice along the sorted points. Conversely, any sign sequence with at most two changes is realized by placing polynomial roots between the changes. Enumerating all labelings gives 3232 separable assignments out of 6464 for six points and 4444 out of 128128 for seven. This is exhaustive finite counting; no Monte Carlo estimates or solver tolerances enter it.

What a regularizer adds#

On separable data, scaling a separator sends logistic and exponential losses towards zero without reaching zero at finite weights. Hinge and squared hinge reach zero once all margins are at least one, leaving many possible separators.

A direct way to ensure a unique finite solution for any of these continuous convex losses is to penalize all linear parameters:

1n∑iϕ(yi(wTxi+b))+λ(∥w∥2+b2),λ>0.\frac1n\sum_i\phi\big(y_i(w^Tx_i+b)\big)+\lambda(\lVert w\rVert^2+b^2),\qquad\lambda>0.

The objective is strongly convex and grows without bound as the full parameter norm grows. Hence it attains a unique minimum. Many implementations leave the bias unpenalized. That is a different convention: a penalty only on ww does not by itself prove uniqueness or even existence in bb. For example, with one class only, logistic loss can keep decreasing as an unpenalized bias diverges; hinge can have an interval of optimal biases.

For a strictly separable dataset containing both classes, minimizing ∥w∥\lVert w\rVert subject to yi(wTxi+b)≥1y_i(w^Tx_i+b)\ge1 maximizes the smallest geometric margin. The usual hard-margin SVM leaves bb out of the norm. Penalizing bb changes that geometry, so the existence argument above is not a definition of the standard SVM. The SVM note treats that optimization separately.

What changed#

The opening least-squares model tried to reproduce encoded numerical labels and moved a useful boundary. A margin surrogate supplies a different training objective and a usable direction. Pointwise conditional risk explains what a loss prefers; the three-group example shows why a linear model may still fail to express it. Regularization controls a further issue: which finite parameter vector training can select.

Limitations#

The fixtures isolate mechanisms and do not measure performance on real requests. The surrogate bound can be loose, and its scale depends on normalization. Class imbalance or unequal error costs can require a different decision threshold. Functional margins depend on parameter scale, while geometric margins depend on the feature representation. Neither a large margin nor a small training loss establishes out-of-sample calibration. Use the validation methods and classification metrics appropriate to the application.

What you should remember#

  • The score defines a boundary; dividing by ∥w∥\lVert w\rVert gives distance only for w≠0w\ne0.
  • A margin combines a score and a label. State what happens at zero.
  • Convex surrogate loss gives training directions and may bound errors; existence of a minimum still needs checking.
  • Pointwise calibration does not eliminate a linear model’s approximation error.
  • The perceptron bound requires separation and controls updates on the presented examples.
  • Name which parameters a regularizer penalizes before claiming uniqueness.

Code#

This small standard-library example checks the new conditional-risk fixture. The full verification script also checks exact least-squares coefficients, geometry, the perceptron trace and exhaustive separability counts. Run it from the repository with python3 scripts/notes/linear-classifiers-renewal.py; it compares fresh calculations with saved JSON. No downloads are needed.

from math import exp, log, log1p

probabilities = [1 / 8, 7 / 8, 1 / 8]
scores = [log(p / (1 - p)) for p in probabilities]
pooled = sum(probabilities) / len(probabilities)
linear_score = log(pooled / (1 - pooled))

def loss(m):
    return (max(0, -m) + log1p(exp(-abs(m)))) / log(2)

def risk(p, score):
    return p * loss(score) + (1 - p) * loss(-score)

flexible = sum(risk(p, s) for p, s in zip(probabilities, scores)) / 3
linear = sum(risk(p, linear_score) for p in probabilities) / 3
print('flexible scores:', [round(s, 6) for s in scores])
print('linear score:', round(linear_score, 6))
print('mean losses:', round(flexible, 6), round(linear, 6))
print('decision errors:', 3 / 24, 9 / 24)
flexible scores: [-1.94591, 1.94591, -1.94591]
linear score: -0.510826
mean losses: 0.543564 0.954434
decision errors: 0.125 0.375

Next#

The logistic optimum has a probability interpretation. The next note derives the same loss from the label likelihood, separates fitting from calibration and explains when a probability threshold should move away from one half.

References#