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.
Least squares · Stochastic and adaptive optimizers · Regularization
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 , and . Predict when and 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 and positive examples at . Fitting an intercept and a slope to labels gives
Its boundary is and all four signs are correct. Add a positive example at . The least-squares solution becomes
The boundary moves to , making the example at negative. Yet 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 , squared error is . 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 , the decision boundary is a hyperplane. Any displacement within it satisfies , so is normal to the boundary and points towards positive scores. Move a point along that normal until it reaches the boundary:
Substitution gives ; is the signed distance. Multiplying both and by a positive constant changes the score but leaves this distance and the decisions unchanged. If , the score is constant and these distance formulas do not apply.
For the new geometry fixture, set and . Point has score , distance and projection . Indeed, .
Seven specified points and one boundary
The margin#
The functional margin is . A positive margin means the score is on the label’s side; a negative margin means an error. For , 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 . Thus a positive label on the boundary is classified correctly, although it has no positive margin. The conservative margin-error count
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 , so both error rates equal .
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 are feasible after rescaling a separator. Linear programming can find such a separator.
At the population level, let . 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 . For example,
Each is nonnegative and at least when . Therefore the average of each bounds . The usual natural-log logistic loss needs the displayed factor 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.
One dataset, two upper bounds
| Point | M | Error | Logistic | Hinge |
|---|---|---|---|---|
| A | 4 | 0 | 0.026 | 0.000 |
| B | 3 | 0 | 0.070 | 0.000 |
| C | 1 | 0 | 0.452 | 0.000 |
| D | 2 | 0 | 0.183 | 0.000 |
| E | 4 | 0 | 0.026 | 0.000 |
| F | -1 | 1 | 1.895 | 2.000 |
| G | -3 | 1 | 4.398 | 4.000 |
| Mean | — | 0.286 | 1.007 | 0.857 |
For our seven points, the average logistic upper bound is and the hinge bound is , while the actual error fraction is . The bound need not be tight or lie below . Squared error 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 . 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
For natural-log logistic loss, differentiation gives , where . For , the unique pointwise optimum is . Base-two scaling preserves this optimum. At or , 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 . Imagine eight possible requests at each value, with respectively positive labels. These counts define a finite fictional distribution, not estimates from collected data. Independent scores can use . Their mean base-two logistic risk is , and their decision error is .
A linear score cannot put the middle point above both endpoints. For this symmetric distribution its logistic optimum is , : the predicted probability is the pooled positive share . Grouped by its single probability prediction, this constant model is calibrated, but it loses the feature-dependent probabilities. To check optimality, sum the residuals and their products with ; both sums are zero. Positive conditional class probabilities and the full-rank design make the logistic Hessian positive definite. The resulting risk is and error . Giving the model more data from this same distribution cannot remove its linear restriction. A feature can represent the three pointwise log-odds exactly.
Other losses preserve different information. On , conditional hinge risk is ; its optimum is the endpoint with the majority sign when and . At , every score in minimizes it, so no unique probability can be read from that optimum. The exponential derivative vanishes when . For squared error, expanding gives , minimized at ; 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 , 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:
This is an incremental subgradient step for , choosing the nonzero endpoint subgradient at . The loss is convex but is not a unit upper bound on . 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: positive, negative, positive and negative. Starting from , the updates are:
| Pass and point | Margin before | Parameters after |
|---|---|---|
| 1, point 1 | ||
| 1, point 4 | ||
| 2, point 2 |
All other visits leave the parameters unchanged. Final margins are ; 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 to each feature vector and include the bias in a parameter vector . Suppose a unit vector satisfies in this augmented space and . After each update, progress along grows by at least , while the squared norm grows by at most , because the previous margin was nonpositive. After updates,
This is the Block–Novikoff mistake bound, stated with its proof in Freund and Schapire, Theorem 1. In our fixture, , , and give a bound of . 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 cannot be separated by a single threshold, but 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 points in affine general position in and independently fair binary labels, Cover’s function-counting result gives
General position matters: it requires affine independence of every subset of at most points. The formula is for and at . It concerns random label assignments, not an accuracy guarantee for real future examples.
We can verify a small case exactly. Take points for distinct integer . No three are collinear, and a linear score on these points is a quadratic in . 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 separable assignments out of for six points and out of 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:
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 does not by itself prove uniqueness or even existence in . 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 subject to maximizes the smallest geometric margin. The usual hard-margin SVM leaves out of the norm. Penalizing 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 gives distance only for .
- 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#
- Peter L. Bartlett, Michael I. Jordan and Jon D. McAuliffe. Convexity, Classification, and Risk Bounds. JASA, 101(473), 138–156, 2006. Section 2, Theorem 2: classification calibration of nonnegative convex margin losses. Mathematical reference; the paper’s loss plot is not reproduced.
- Yoav Freund and Robert E. Schapire. Large Margin Classification Using the Perceptron Algorithm. Machine Learning, 37, 277–296, 1999. Sections 2 and 3.1: update rule and the Block–Novikoff mistake bound. Checked against the 14 December 1998 preprint; no digit data, paper experiments or voted-perceptron implementation are reused.
- Thomas M. Cover. Geometrical and Statistical Properties of Systems of Linear Inequalities with Applications in Pattern Recognition. IEEE Transactions on Electronic Computers, EC-14(3), 326–334, 1965. Function-counting theorem and affine augmentation; the parabola enumeration here is an independently specified calculation.
- Klaus-Uwe Höffgen, Hans Ulrich Simon and Kevin S. Van Horn. Robust Trainability of Single Neurons. JCSS, 50(1), 114–125, 1995. Computational hardness in its nonseparable learning setting; no reduction or training data reproduced.
- Frank Rosenblatt. The Perceptron: A Probabilistic Model for Information Storage and Organization in the Brain. Psychological Review, 65(6), 386–408, 1958. Historical attribution for the perceptron.
- Trevor Hastie, Robert Tibshirani and Jerome Friedman. The Elements of Statistical Learning, 2nd ed., 2009. Sections 4.5, 10.6 and 12.3.2: prior conceptual references for margins and losses. The source table and its presentation are not used in the current worked examples.
- E. A. Sokolov. HSE Machine Learning, lecture 4 and lecture 5, 2025. Prior conceptual references for margins and classification losses; no permission to adapt their code, figures or examples is inferred.