Neighbors, margins and probabilistic classifiers
Learn from examples in different ways
K-nearest neighbors (KNN), naive Bayes and support vector machines (SVM) can all classify a feature vector, but use different assumptions. KNN compares a query with stored labeled examples; naive Bayes combines class priors and feature likelihoods; SVM finds a separating boundary with a margin objective. Use fictional inventory decisions with label 1 for review and label 0 otherwise. A prediction is not an automatic purchase instruction.
Nearest neighbors with a worked example
Training points with a single feature are (2,0), (5,1), (6,1). Query 3 has absolute distances 1,2,3. With k=1 it gets 0; with k=3 the majority is 1. For vectors we use squared Euclidean distance, which has the same ordering as Euclidean distance for finite nonnegative squared distances. The helper orders equal distances by original training index and tied class votes by label 0. It assumes finite numeric coordinates and integer k; it is a simple brute-force classifier, not a library API. Fitting mainly stores data; prediction can be expensive because it scans all rows. Indexes may help in suitable dimensions.
def knn(rows, query, k): if not 1 <= k <= len(rows): raise ValueError("k outside training set size") if not query or any(len(x) != len(query) or y not in (0, 1) for x, y in rows): raise ValueError("Invalid feature shape or label") distances = [(sum((a - b)**2 for a, b in zip(x, query)), i, y) for i, (x, y) in enumerate(rows)] nearest = sorted(distances)[:k] return int(2 * sum(y for _, _, y in nearest) > k)
rows = [([2], 0), ([5], 1), ([6], 1)]print(knn(rows, [3], 1))print(knn(rows, [3], 3))Feature scale changes a neighbor
Consider query (0,0), item A=(1,100), label 0, and B=(4,0), label 1. Raw squared distances are 10001 and 16, so B wins. If the second feature is expressed in hundreds of its original units, A becomes (1,1), with squared distance 2, while B stays at 16. Now A wins. Scaling changes the geometry; fit scaling parameters only on training data, apply unchanged to validation/test, and choose a meaningful distance. High-dimensional spaces can make distances less informative. Small k may be sensitive to noise; large k can smooth away local structure. Validate rather than choosing k on the test set.
Naive Bayes with binary features
Bayes classification compares P(class) times P(features | class). Naive Bayes approximates the latter by multiplying the individual feature likelihoods conditioned on class. This is a conditional independence assumption, not an assertion that all features are independent in the population. Use four labeled examples: class 0 has (0,0),(0,1); class 1 has (1,1),(1,0). With add-one smoothing on binary class priors and binary likelihoods, both priors are 1/2; for query (1,1), class 0 likelihoods are 1/4 and 1/2, and class 1 likelihoods 3/4 and 1/2. Unnormalized weights are 1/16 and 3/16; divide by their sum for 1/4 and 3/4. For (0,1), the weights reverse. Smoothing prevents a single unseen binary value from setting a likelihood to zero. This deliberately smooths priors too, unlike some libraries. Exact fractions avoid underflow in the tiny example; larger models commonly use log scores. Correlated features can double-count evidence; normalized model scores need not be calibrated.
from fractions import Fraction
def bayes_scores(rows, query): if not rows or any(v not in (0, 1) for v in query): raise ValueError("Binary query and training rows required") if any(len(x) != len(query) or y not in (0, 1) or any(v not in (0, 1) for v in x) for x, y in rows): raise ValueError("Invalid binary training row") scores = [] for label in (0, 1): group = [x for x, y in rows if y == label] n = len(group) score = Fraction(n + 1, len(rows) + 2) for j, value in enumerate(query): score *= Fraction(1 + sum(x[j] == value for x in group), n + 2) scores.append(score) total = sum(scores) return [s / total for s in scores]
rows = [([0, 0], 0), ([0, 1], 0), ([1, 1], 1), ([1, 0], 1)]print([str(p) for p in bayes_scores(rows, [1, 1])])print([str(p) for p in bayes_scores(rows, [0, 1])])Support vector machines and margins
Imagine one feature x, with negative samples at 1 and 2 and positive samples at 4 and 5. A separating boundary at x=3 leaves a distance of one unit to the nearest sample on either side. These nearest samples illustrate support vectors in a separable hard-margin case. A linear SVM seeks a large margin; soft-margin training allows violations and trades them against margin size via regularization. For a linear score w dot x + b, the sign selects a class; the raw score is not automatically a probability. Kernels let an SVM represent nonlinear decision boundaries without explicitly listing all transformed coordinates. C and kernel settings need validation; feature scaling often matters. The example is geometry, not an executed SVM fit.
Choose a candidate, then measure
For a small dataset where explaining threshold rules matters, a shallow tree is a reasonable candidate. When examples are close in meaningful feature space and storage is feasible, KNN is a candidate. For sparse count features, multinomial naive Bayes can be a useful baseline, distinct from the binary likelihood example above. SVM can suit a margin-based representation but kernel fitting and prediction can be costly. Forests and boosting may capture interactions with less manual feature design but add model complexity. Compare using identical splits, task-relevant metrics, measured fitting and serving costs, and a simple baseline. No toy result proves an algorithm is superior.
Practice and next steps
For query [3], change k from 1 to 2: the neighbors at 2 and 5 tie, so our policy yields 0. For naive Bayes query [0,0], the first feature favors class 0 and the second is equally likely, so the result is [3/4,1/4]. Explain why rescaling a feature can change KNN without changing labels. Keep the original records immutable. Next chapter: unsupervised learning, cluster structure and dimensionality reduction; deeper SVM optimization and model tuning belong to the ML track.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Neighbors, margins and probabilistic classifiers quiz
Apply model-family concepts to small original examples.
For points (2,0),(5,1),(6,1), query 3 and k=1, which label wins?
Where should scaling parameters be fitted?
What feature-independence assumption does the lesson naive Bayes model make?
What does add-one smoothing do to an unseen binary feature value within a class?
For a linear SVM with decision score w dot x + b, what does the raw score represent?