Classification: logistic regression, kNN, SVM
Predicting categories with three classic methods: logistic regression (sigmoid + cross-entropy), k-nearest neighbours (vote of the closest examples) and support vector machines (maximum margin + kernels) — and how C, k and γ shape the decision boundary.
[[classification|Classification]] predicts a category: spam or not, fraud or legit, which of 10 digits, which disease. Under the hood, every classifier carves the feature space into regions, one per class; the border between regions is the decision boundary. The three methods in this lesson carve that space in very different ways, and understanding them gives you intuition for every classifier that came after[1].
Logistic regression
Despite its name, [[logistic-regression|logistic regression]] is a classifier. It computes a linear score z = wᵀx + b (like linear regression) and squashes it through the [[sigmoid]] function into a probability between 0 and 1. The score z is the log-odds: z = 0 means 50/50, each +1 in z multiplies the odds by e ≈ 2.72[2].
- z
- the linear score (logit), any real number
- wᵀx
- dot product of the weights and the Feature vector: w₁x₁ + … + wₙxₙ
- b
- bias (intercept)
- p(y=1 | x)
- probability that the class is 1 (e.g. “spam”), given the features x
- σ(z)
- the Sigmoid (logistic function) function applied to z
- e^(−z)
- e ≈ 2.718 to the power −z: huge for negative z, tiny for positive z
- log
- natural logarithm (base e), the inverse of e^
- p / (1−p)
- the odds: probability of class 1 divided by probability of class 0 (0.75 → odds 3, “3 to 1”)
- p
- short for p(y=1 | x)
▸Worked example
| z | −4 | −2 | 0 | 2 | 4 |
|---|---|---|---|---|---|
| σ(z) | 0.018 | 0.119 | 0.500 | 0.881 | 0.982 |
Training minimises binary [[cross-entropy]] (log loss): when the true label is 1 the loss is −log p, which is 0.105 if p = 0.9 but 2.3 if p = 0.1 — confident wrong answers are punished hard. To predict a class you compare p to a [[threshold]] (0.5 by default). For more than two classes, softmax (multinomial) logistic regression produces one probability per class.
- BCE
- binary Cross-entropy (log loss) (log loss), the loss for two-class problems
- −(1/n)
- minus the average over n examples. The minus makes the loss positive, because log of a probability is ≤ 0
- Σᵢ
- sum over all examples i
- yᵢ
- true label of example i: 0 or 1. Acts as a switch between the two terms
- log(pᵢ)
- natural log of the predicted probability of class 1 — used when yᵢ = 1
- pᵢ
- predicted probability that example i is class 1 (output of the sigmoid)
- (1 − yᵢ)
- 1 when the true label is 0, otherwise 0: switches the second term on
- log(1 − pᵢ)
- log of the predicted probability of class 0 — used when yᵢ = 0
▸Worked example
- What it is
- Inverse regularisation strength in scikit-learn: the L2 penalty is scaled by 1/C. Large C = weak regularisation.
- ↑ If you increase it
- Weights may grow larger; the model fits the training data more tightly and becomes more confident. Too large → overfitting, and on perfectly separable data weights head toward infinity.
- ↓ If you decrease it
- Stronger shrinkage of weights; probabilities move toward 0.5 and the boundary becomes simpler. Too small → underfitting.
- Typical values
- Default 1.0. Search 0.001–1000 on a log scale with cross-validation (
LogisticRegressionCV). Scale features first.
- What it is
- The probability above which an example is labelled positive. Not learned — chosen after training based on the cost of mistakes.
- ↑ If you increase it
- Fewer positives predicted: higher Precision (fewer false alarms), lower Recall (more misses).
- ↓ If you decrease it
- More positives predicted: higher recall, lower precision. Useful for screening where a miss is expensive (cancer, fraud).
- Typical values
- 0.5 by default; tune on validation data with a precision-recall curve (see the classification-metrics lesson). scikit-learn ≥ 1.5 has
TunedThresholdClassifierCV.
k-nearest neighbours (kNN)
[[knn|kNN]] has no training phase at all — it simply stores the data (a ‘lazy’ learner). To classify a new point it measures the distance to every stored example, takes the k closest, and lets them vote. It can draw any shape of boundary, and with enough data its error is provably at most twice the best achievable (Bayes) error for k = 1[5]. The price: prediction is slow on big datasets, and distances become less meaningful in high dimensions (the ‘curse of dimensionality’)[6].
- d(a, b)
- distance between points a and b (e.g. the new point and one stored example)
- √
- square root
- Σᵢ
- sum over all features i
- aᵢ
- value of feature i for point a
- bᵢ
- value of feature i for point b
- ²
- squared difference: large gaps in one feature dominate — hence the need for scaling
- ŷ
- the predicted class
- k
- how many neighbours vote, a Hyperparameter (often 3–15, odd to avoid ties)
▸Worked example
- What it is
- How many nearest neighbours vote on each prediction.
- ↑ If you increase it
- Smoother boundary, less sensitive to noisy points (lower variance, higher bias). At k = N every prediction is just the majority class.
- ↓ If you decrease it
- Jagged boundary that follows individual points. k = 1 gets 100% training accuracy (each point is its own neighbour) but overfits noise.
- Typical values
- Default 5. Try odd values 3–31 with cross-validation;
weights="distance"lets closer neighbours count more.
Support vector machines (SVM)
A linear [[svm|SVM]] looks for the separating line (hyperplane) with the widest margin — the largest gap to the nearest points of each class. Only those nearest points, the support vectors, determine the boundary; moving any other point changes nothing. Real data overlap, so the soft-margin SVM of Cortes & Vapnik allows some violations, paying a penalty C for each[4].
- minimise
- find the w, b and ξ that make the expression as small as possible
- ½‖w‖²
- half the squared length of the weight vector. Margin width = 2/‖w‖, so minimising this widens the margin
- C
- penalty per unit of violation, a Hyperparameter: large C = few violations, narrow margin; small C = wide, tolerant margin
- Σᵢ
- sum over all training points i
- ξᵢ
- xi — slack of point i: 0 = fine, between 0 and 1 = inside the margin, > 1 = misclassified
- subject to
- “while obeying these constraints”
- yᵢ
- label of point i, coded as +1 or −1
- wᵀxᵢ
- dot product of the weights with point i's features
- b
- bias: shifts the boundary
- ≥
- greater than or equal to
▸Worked example
The kernel trick makes SVMs non-linear: instead of explicitly mapping data to a higher-dimensional space, the algorithm only needs similarities K(x, x′) between pairs of points. The popular RBF (Gaussian) kernel treats points as similar when they are close, allowing curved, island-shaped boundaries[3].
- K_RBF(x, x′)
- the RBF (Gaussian) kernel: a similarity score between points x and x′, from 0 to 1
- exp
- exponential function: exp(a) = e^a, with e ≈ 2.718. exp(0) = 1
- γ
- gamma — kernel width Hyperparameter: large γ = narrow influence (risk of Overfitting), small γ = smooth boundary
- ‖x − x′‖²
- squared Euclidean distance between the two points
- x
- a data point (feature vector)
- x′
- “x prime”: another data point
▸Worked example
- What it is
- Penalty for margin violations / misclassified training points.
- ↑ If you increase it
- Violations become expensive: narrower margin, boundary bends to classify every training point correctly → risk of overfitting; more support vectors become ‘hard’.
- ↓ If you decrease it
- Wider, more tolerant margin that ignores some points; smoother boundary, more regularised → may underfit.
- Typical values
- Default 1.0; search 0.01–1000 on a log grid, jointly with γ.
- What it is
- How far the influence of a single training point reaches. γ is the inverse of the kernel's radius.
- ↑ If you increase it
- Each point influences only a tiny neighbourhood: very wiggly boundaries, islands around single points → overfitting.
- ↓ If you decrease it
- Each point influences a wide area: the boundary becomes smooth, almost linear → underfitting if the true boundary is complex.
- Typical values
- scikit-learn default
gamma="scale"= 1 / (n_features · Var(X)). Search 10⁻⁴–10 on a log grid together with C.
| Logistic regression | kNN | SVM (RBF) | |
|---|---|---|---|
| Boundary | linear (unless you add features) | any shape | smooth non-linear |
| Training cost | low | none (stores data) | high: roughly O(n²)–O(n³) |
| Prediction cost | very low | high (distances to all points) | medium (support vectors) |
| Probabilities | yes, well calibrated | rough (vote fractions) | only via extra calibration |
| Needs scaling | yes (for regularisation/solver) | yes, essential | yes, essential |
| Interpretability | high (weights = log-odds) | medium (show the neighbours) | low |
from sklearn.datasets import make_moons
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
X, y = make_moons(n_samples=500, noise=0.25, random_state=0) # two curved half-moons
models = {
"logistic": LogisticRegression(C=1.0),
"kNN (k=15)": KNeighborsClassifier(n_neighbors=15),
"SVM rbf": SVC(kernel="rbf", C=1.0, gamma="scale"),
}
for name, clf in models.items():
pipe = make_pipeline(StandardScaler(), clf) # scaling inside the pipeline
acc = cross_val_score(pipe, X, y, cv=5).mean()
print(f"{name:12s} accuracy = {acc:.3f}")
# Expect: logistic regression lower (its boundary is a straight line),
# kNN and RBF-SVM higher (they can curve around the moons).probability=True) come from an extra internal cross-validated calibration: slow and occasionally inconsistent with predict. kNN on huge data is slow at prediction time; use approximate nearest-neighbour libraries.▸Go deeper: why cross-entropy and not MSE for classification?
Plugging the sigmoid into MSE gives a non-convex loss whose gradient vanishes when the model is confidently wrong (the sigmoid is flat there), so learning stalls exactly when it should be fastest. Cross-entropy cancels the sigmoid's flatness: its gradient with respect to z is simply (p − y), large when the prediction is badly wrong, and the loss is convex in w. Cross-entropy is also the negative log-likelihood of a Bernoulli model, so minimising it is maximum likelihood estimation.
SVMs use the hinge loss max(0, 1 − y·z) instead: zero for points safely beyond the margin, which is why only support vectors matter. Logistic regression's loss is never exactly zero, so every point has a little influence.
Quiz
References
- [1]An Introduction to Statistical Learning (2nd ed.) — Ch. 4 Classification, Ch. 9 Support Vector MachinesBookJames, Witten, Hastie & Tibshirani2021statlearning.com
- [2]scikit-learn User Guide — Logistic regressionDocsscikit-learn developersscikit-learn.org
- [3]scikit-learn User Guide — Support Vector MachinesDocsscikit-learn developersscikit-learn.org
- [4]Support-Vector NetworksPaperCortes & Vapnik1995doi.org
- [5]Nearest Neighbor Pattern ClassificationPaperCover & Hart1967doi.org
- [6]scikit-learn User Guide — Nearest NeighborsDocsscikit-learn developersscikit-learn.org