kNN, distance, and local decisions
In kNN, representation defines the neighborhood, and the neighborhood defines the decision.
Support tickets need explainable routing under a 15 ms latency budget.
This chapter moves from fit the geometry to measure serving reality. We will make the idea concrete in a small code example before placing it back inside a production system with 15 ms batch-one latency.
Benchmark batch-one search, memory, index recall if approximate, and behavior for points far from all training examples.
Verify the behavior illustrated in scaled_knn.py, then measure decision utility, slice reliability, and system latency.
Unscaled revenue dominates kNN distance while perfectly separating features destabilize unregularized logistic coefficients. An unsafe release must degrade to a named baseline or the last known-good version.
Build the idea one layer at a time.
k-nearest neighbors does not learn one global boundary. It defers the decision until a query arrives and asks which stored examples are nearby.
“Nearby” is entirely defined by representation and distance. Without scaling, a feature measured in thousands dominates another measured between zero and one, regardless of which carries useful signal.
Small k follows local detail but is sensitive to noise; larger k smooths decisions and can erase minority regions. Serving also stores the reference set and searches it per request, so memory and latency are part of model selection.
- distance concentration
- hinge loss
- latency baselines
Follow the reasoning before touching the code.
- 01
Fit the geometry
Learn scaling or representation from training data only and choose a distance compatible with its meaning.
- 02
Inspect neighborhoods
Vary k, use deterministic tie-breaking, and examine distance plus label composition around difficult queries.
- 03
Measure serving reality
Benchmark batch-one search, memory, index recall if approximate, and behavior for points far from all training examples.
from math import dist
train = [([20, 20_000], "normal"), ([25, 24_000], "normal"),
([50, 80_000], "urgent"), ([55, 76_000], "urgent")]
columns = list(zip(*(features for features, _ in train)))
mins = [min(column) for column in columns]
maxs = [max(column) for column in columns]
def scale(features):
return [(value - low) / (high - low)
for value, low, high in zip(features, mins, maxs)]
query = [48, 70_000]
neighbors = sorted((dist(scale(features), scale(query)), label)
for features, label in train)[:3]
votes = {label: sum(item[1] == label for item in neighbors)
for label in ["normal", "urgent"]}
print(neighbors, "prediction", max(votes, key=votes.get))Classify a query after min-max scaling the training geometry.
What to notice
- Age and income each occupy a comparable zero-to-one range after training-fitted scaling.
- The prediction can be explained by the three stored neighbors, but every request pays for that search.
YOUR TURN Pause and predict before revealing the answer.
What should happen if maxs and mins are equal for one feature?
Need a hint?
The scaling denominator for a constant column is zero.
Check your reasoning
The pipeline should drop or constant-encode that feature under an explicit fitted policy, rather than divide by zero or invent request-specific scaling.
Lessons 1, 2, 3 in this course.
Connect the chapter to the course’s quantitative spine.
In kNN, representation defines the neighborhood, and the neighborhood defines the decision. The logistic probability below is the shared course-level lens that helps quantify the surrounding system. Name each symbol, check its units or shape, and use only values that were available at the production cutoff.
Logistic probability
| Symbol | Meaning / shape / unit |
|---|---|
x | feature vector |
β | learned coefficients |
xᵀβ | linear log-odds score |
Open derivation and numerical substitution
Start from the production quantity being optimized, substitute the observed values with their declared units, then isolate the model-controlled term. Preserve shape annotations at each step so broadcasting or aggregation cannot silently change the result.
- Write the named inputs: x, β, xᵀβ.
- Substitute one small, hand-checkable batch before vectorizing.
- Calculate an independent reference value and compare within a declared tolerance.
# equation → code contract
inputs = validate_shapes_and_units(batch)
value = compute_c04(inputs)
assert is_finite(value)Change one assumption and make the tradeoff visible.
Use the worked chapter as your prediction, then change one input in the lab and explain why the output moves. The lab runs predefined TypeScript and never executes learner code, so the focus stays on the concept rather than setup.
Regularization boundary lab
Increase regularization and watch complexity trade against margin violations.
Assumption: Synthetic standardized two-feature classification problem.
Open nonvisual data table
| Item | Computed state | Interpretation |
|---|---|---|
| x=-2 | logit -2.57 | negative |
| x=-1 | logit -1.29 | negative |
| x=0 | logit 0.00 | negative |
| x=1 | logit 1.29 | positive |
| x=2 | logit 2.57 | positive |
Trace the complete operating path.
Carry the chapter’s central idea into the system: In kNN, representation defines the neighborhood, and the neighborhood defines the decision. The path below shows where that reasoning needs an artifact, a test, an owner, or a fallback.
- 01
Turn “Fit the geometry” into a written invariant and a failing test.
- 02
Promote scaled_knn.py from illustration to a versioned implementation with representative fixtures.
- 03
Use “Measure serving reality” as the release checkpoint: Benchmark batch-one search, memory, index recall if approximate, and behavior for points far from all training examples.
- 04
Serve or materialize behind explicit 15 ms batch-one latency.
- 05
Join telemetry to mature outcomes and retain a rollback path.
Observability
Join service health, input quality, prediction distributions, slice behavior, and mature outcomes by exact version.
Cost
Measure storage, preprocessing, compute, queueing, and human review under a representative arrival pattern.
Failure modes
Unscaled revenue dominates kNN distance while perfectly separating features destabilize unregularized logistic coefficients. Add a detector, owner, mitigation, and stop condition for this class of failure.
Alternatives
Compare a rule, a simpler statistical baseline, and a different system boundary before adding model complexity.
Explain the contract, not just the vocabulary.
Explainable ticket-routing baseline
Compare linear/logistic regression, Naive Bayes, kNN, and SVM under one evaluation and serving contract.
- Preprocessing parity
- Model-family comparison
- Calibration and cost policy
- Serialized latency test
Read primary material with a purpose.
Return to the opening failure.
Compare quality, calibration, latency, memory, and interpretability under one stable validation contract.
For this lesson, the release evidence is the worked code example, a hand-checked formal result, deterministic simulation output, a ≥80% checkpoint, the production rubric, and a named fallback. The course resolves when the system can produce a justified baseline across regression, naive bayes, knn, and svm.