AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
∿Classical Machine Learning
  1. Linear regression
  2. Gradient descent
  3. Classification: logistic regression, kNN, SVM
  4. Decision trees and ensembles
  5. Clustering and PCA
  6. Overfitting and the bias-variance trade-off
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/Classical Machine Learning

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.

Beginner~26 min·6 references
Key terms
ClassificationLogistic regressionk-nearest neighbours (kNN)Support vector machine (SVM)Cross-entropy (log loss)Sigmoid (logistic function)Decision thresholdFeature scaling (normalisation / standardisation)

[[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].

≈
Three ways to sort mangoes
Sorting mangoes into ‘ripe’ and ‘unripe’: logistic regression builds a scoring formula (more yellow +, softer +) and turns the score into a probability. kNN finds the 5 most similar mangoes you have already sorted and copies the majority. SVM draws the widest possible ‘no man's land’ between the ripe pile and the unripe pile, decided only by the borderline mangoes.

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 = wᵀx + b p(y=1 | x) = σ(z) = 1 / (1 + e^(−z)) log( p / (1−p) ) = z
In words: Three views of the same model. First compute a linear score z, exactly as in linear regression. Then squash it with the Sigmoid (logistic function) σ into a probability between 0 and 1: large positive z → close to 1, large negative z → close to 0, z = 0 → 0.5. The third formula reads it backwards: z is the log of the odds p/(1−p), which is why the weights are interpreted as changes in log-odds.
Symbols(hover a symbol in the formula)
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
w = [2, −1], b = −1, x = [1.5, 1] z = 2·1.5 + (−1)·1 + (−1) = 3 − 1 − 1 = 1 p = 1 / (1 + e^(−1)) = 1 / (1 + 0.368) ≈ 0.731 odds = 0.731 / 0.269 ≈ 2.718 = e¹ log(2.718) = 1 = z ✓ With the 0.5 Decision threshold: 0.731 ≥ 0.5 → predict class 1. Raise x₁ by 0.5 → z = 2 → p ≈ 0.881, odds × e ≈ 7.39.
z−4−2024
σ(z)0.0180.1190.5000.8810.982
The sigmoid saturates: big positive scores → nearly 1, big negative → nearly 0.

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 = −(1/n) · Σᵢ [ yᵢ·log(pᵢ) + (1 − yᵢ)·log(1 − pᵢ) ]
In words: “the average surprise at the true label”. For each example only one of the two terms is active: if the true label is 1 you pay −log(p), if it is 0 you pay −log(1 − p). Being confident and right costs almost nothing; being confident and wrong costs a lot, because −log of a number near 0 is huge.
Symbols(hover a symbol in the formula)
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
Three examples (natural log): y = 1, p = 0.9 → −log(0.9) ≈ 0.105 (confident, right) y = 0, p = 0.2 → −log(1 − 0.2) = −log(0.8) ≈ 0.223 y = 1, p = 0.1 → −log(0.1) ≈ 2.303 (confident, wrong!) BCE = (0.105 + 0.223 + 2.303) / 3 ≈ 0.877 The one confident mistake contributes about 88% of the total loss.
knobC (LogisticRegression)
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.
knobdecision threshold
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) = √( Σᵢ (aᵢ − bᵢ)² ) ŷ = majority class among the k nearest neighbours
Because it is all distances, a feature measured in rupiah will drown out one measured in years — always scale features for kNN.
In words: Left: the straight-line (Euclidean) distance between two points — Pythagoras over all features. Right: to classify a new point, find the k stored examples with the smallest distance and let them vote; the most common class wins. Changing k can change the answer.
Symbols(hover a symbol in the formula)
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
New point q = (2, 2). Stored points: A (1, 1) red: √(1 + 1) ≈ 1.41 B (3, 2) blue: √(1 + 0) = 1 C (2, 4) blue: √(0 + 4) = 2 D (0, 0) red: √(4 + 4) ≈ 2.83 E (4, 4) red: √(4 + 4) ≈ 2.83 Sorted: B, A, C, D, E k = 1 → B → blue k = 3 → B, A, C → 2 blue vs 1 red → blue k = 5 → 3 red vs 2 blue → red
knobk (n_neighbors)
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 ½‖w‖² + C · Σᵢ ξᵢ subject to yᵢ(wᵀxᵢ + b) ≥ 1 − ξᵢ, ξᵢ ≥ 0
Margin width = 2/‖w‖, so a small ‖w‖ means a wide margin. ξᵢ (slack) measures how much point i violates the margin.
In words: “make the margin as wide as possible (small ‖w‖), while paying C for every bit by which a point crosses into the margin or onto the wrong side”. The constraint says each point should sit on its correct side at a score of at least 1; the slack ξᵢ measures how far short it falls.
Symbols(hover a symbol in the formula)
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
w = [1, 1], b = −3 (boundary x₁ + x₂ = 3), C = 1 ‖w‖ = √2 → margin width = 2/√2 ≈ 1.41, ½‖w‖² = 1 (3, 1), y = +1: wᵀx + b = 1 → y·(…) = 1 ≥ 1 → ξ = 0 (on the margin: support vector) (2.5, 1), y = +1: 0.5 → ξ = 1 − 0.5 = 0.5 (inside margin) (1, 1), y = −1: −1 → y·(…) = 1 → ξ = 0 (2, 2), y = −1: +1 → y·(…) = −1 → ξ = 2 (wrong side) Objective = 1 + 1·(0.5 + 2) = 3.5 With C = 10 it would be 1 + 25 = 26 → strong pressure to fit those points.

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′) = exp( −γ · ‖x − x′‖² )
In words: “similarity = e to the minus (γ × squared distance)”. Identical points have similarity 1; the further apart, the closer the similarity drops to 0. γ sets how fast it drops: a large γ means only very close neighbours count as similar, giving wiggly, island-shaped boundaries.
Symbols(hover a symbol in the formula)
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
x = (1, 2), x′ = (2, 4) ‖x − x′‖² = (1 − 2)² + (2 − 4)² = 1 + 4 = 5 γ = 0.1 → exp(−0.5) ≈ 0.607 (quite similar) γ = 1 → exp(−5) ≈ 0.0067 (almost unrelated) γ = 10 → exp(−50) ≈ 0 (unrelated) Same point (x = x′): distance 0 → exp(0) = 1 for any γ.
knobC (SVC)
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 γ.
knobgamma (γ, RBF kernel)
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 regressionkNNSVM (RBF)
Boundarylinear (unless you add features)any shapesmooth non-linear
Training costlownone (stores data)high: roughly O(n²)–O(n³)
Prediction costvery lowhigh (distances to all points)medium (support vectors)
Probabilitiesyes, well calibratedrough (vote fractions)only via extra calibration
Needs scalingyes (for regularisation/solver)yes, essentialyes, essential
Interpretabilityhigh (weights = log-odds)medium (show the neighbours)low
python
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).
Comparing the three classifiers on non-linear data with 5-fold cross-validation.
!
Pitfalls
Accuracy on imbalanced data lies: with 1% fraud, always predicting ‘legit’ scores 99% — look at Precision, Recall and the confusion matrix. Forgetting to scale cripples kNN and SVM. SVC probabilities (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

1.
Logistic regression outputs z = 0 for an example. What probability does it assign to class 1?
2.
You set k = 1 in kNN. What do you expect?
3.
An RBF-SVM has near-100% training accuracy but poor validation accuracy. Which change most likely helps?
4.
In a cancer screening model, missing a real case is far worse than a false alarm. What should you do with the threshold?
5.
Which points determine the decision boundary of a trained SVM?
Score: 0/5

References

  1. [1]
    An Introduction to Statistical Learning (2nd ed.) — Ch. 4 Classification, Ch. 9 Support Vector Machines
    BookJames, Witten, Hastie & Tibshirani2021statlearning.com
  2. [2]
    scikit-learn User Guide — Logistic regression
    Docsscikit-learn developersscikit-learn.org
  3. [3]
    scikit-learn User Guide — Support Vector Machines
    Docsscikit-learn developersscikit-learn.org
  4. [4]
    Support-Vector Networks
    PaperCortes & Vapnik1995doi.org
  5. [5]
    Nearest Neighbor Pattern Classification
    PaperCover & Hart1967doi.org
  6. [6]
    scikit-learn User Guide — Nearest Neighbors
    Docsscikit-learn developersscikit-learn.org
← Previous
Gradient descent
Next →
Decision trees and ensembles