Distance-Based Classification

A new signal arrives and you must name its class. Copy the label of the closest labeled example. It works, but only if you measure the distance in the right space.

Slide the test signal along the time axis, then flip between raw samples and the magnitude spectrum. Watch the nearest neighbor change its mind in one space and never in the other. Then we build, piece by piece, the rule, the distances, the choice of k, the real phone results and the Hilbert space geometry underneath.

You need a little vector arithmetic (add, scale, dot product) and the DFT idea from the last lessons. We rebuild the rest from zero.

Based on Lecture 4 of Stanford EE269: Signal Processing for Machine Learning, taught by Mert Pilanci (Stanford, January 2019). Course slides. Every idea is re-taught here in our own words and devices. It follows the STFT lesson and leans on the DFT lesson.

Name the nearest neighbor

0
0.15

Toy data, labelled illustrative: 64-sample signals, class A has 3 cycles per window and class B has 5, each with one harmonic; three training signals per class, each with a random circular shift and noise of 0.15. The test signal is always a class A recording. The accuracy counts are computed live in your browser over all 64 shifts with the current noise. The lecture’s real numbers are in Chapter 6.

Chapter 0

Why a Signal Is a Point

See why comparing two recordings means measuring a distance, and why that distance depends on the space you choose

Your phone sits in your pocket. Its accelerometer (a sensor that measures how fast the phone speeds up or slows down) writes a number every few milliseconds. Take 128 of those numbers and you have a short recording of your motion.

One recording came from a person walking. Another came from a person sitting still. A third has no label yet, and you want the computer to say which kind of motion it saw. That is the whole problem of this lecture.

The lecture opens with a one-line recap: the DFT changes the basis of a signal. We will use that fact in a few pages. First we need to say the problem in numbers.

The problem, written down

A signal is a list of numbers, one for each moment in time. We write it x[n], and n counts the samples, from 0 up to N − 1. A label is the name of the class the signal belongs to. In the simplest case there are two classes, so the label y is 0 or 1.

The training set is a pile of signals whose labels we already know: x1[n], x2[n], up to xm[n], with labels y1 up to ym. Then comes one new signal x[n] with no label. The task is to find its label y. The lecture calls this binary signal classification. (The slide writes the labels as 0 and 1, and the question as 0 or +1. Both mean “two classes”.)

(xi[n], yi)
One training example: a signal and its known label. There are m of them. This is the only knowledge the computer has.
y
The label we want, 0 or 1. It is a name, not a measurement.
x[n]
The new signal, N samples long, with no label yet.

The idea: closer means more alike

Here is the plain idea. If the new signal looks like a walking recording, call it walking. “Looks like” needs a number. We need a way to say how far apart two signals are. Then the closest training signal wins.

That number only makes sense if a signal is a place. It is. A signal with N samples is a list of N numbers, and a list of N numbers is a point in N dimensions. A signal with two samples is a point on a sheet of paper. A signal with 128 samples is a point in a space you cannot draw, but the arithmetic is the same.

Play with the smallest case. Drag the two samples and watch the signal and the point move together.

One signal, one point

Left: the signal x[n] with two samples. Right: the same two numbers as a point, with an arrow from the origin. Drag the two samples. The ring shows the distance from the origin.

3.0
4.0

Illustrative: a two-sample signal is the only one we can draw as a point. The same rule, add the squares of the samples and take the root, holds for any length N.

Set the samples to 3 and 4. The point is (3, 4). Its distance from the origin is the square root of 3² + 4², which is 5. This is the old Pythagoras rule. For a signal, the sum of the squared samples has a name: the energy. So the distance from the origin is the square root of the energy.

Recap: the DFT changes the basis

Slide 2 lists four facts about the DFT (discrete Fourier transform: the recipe that writes a signal as a sum of pure waves, from our DFT lesson). Read them as pictures, not formulas.

First, a single spike at time n0 gives a spectrum of constant size whose phase turns steadily with k. Second, a constant signal (all ones) gives one tall spike, of height N, at k = 0. Third, a pure wave that repeats k0 times per window gives one tall spike, also of height N, at k = k0. Fourth, the DFT itself is a sum of the signal times N waves, one wave for each k.

A basis is a set of directions you use to describe a point. The DFT keeps the point and swaps the directions, from “one axis per time sample” to “one axis per wave”. The hero used this. In the raw space two shifted copies of one wave sit far apart. In the spectrum space they sit on the same spot.

The plan. Chapters 1 and 2 define the nearest-neighbor rule. Chapters 3 and 4 ask which distance to use. Chapter 5 picks k. Chapter 6 runs it on real phone data. Chapters 7 to 9 build the Hilbert space geometry that explains why it all works.

One question stays open until Chapter 3: “far apart” in which sense? Two recordings of the same walk, started half a second apart, have very different samples. They are the same motion. Whether they count as close depends on the space and on the distance. That choice is the real subject of the lecture.

  1. The nearest-neighbor rule: copy the label of the closest example, and see the cells it makes.
  2. k nearest neighbors: a vote instead of one example, and what k does.
  3. Choosing a distance: p-norms, and a pair of signals that two norms rank in opposite ways.
  4. Rotation and the DFT: why l2 is special.
  5. Choosing k: validation, hold-out and q-fold cross-validation.
  6. The phone experiment: 77, 85, 91 and 96 percent.
  7. Ingredients of a Hilbert space: vectors, inner product, completeness.
  8. Geometry: convex sets, the best approximation, Parseval.
  9. Null space: when columns are independent.
  10. Field guide: numbers, code, and onward.
A signal has samples [3, 4]. What is its energy, and what is its distance from the all-zero signal?

Chapter 1

The Nearest-Neighbor Rule

Copy the label of the closest training signal, and see the map of cells that rule draws across signal space

You move to a new town and you do not know which bus to take. You ask the person standing closest to you. They are not an expert. They are only nearby. Most of the time, nearby people want the same bus as you.

The nearest neighbor (NN) classifier works the same way. To label a new signal, find the training signal that sits closest to it, and give the new signal the same label. That is the entire algorithm. The lecture states it in one line: assign x[n] the same label as the closest training signal.

The rule as a formula

“Closest” needs a ruler. The lecture’s first ruler is the Euclidean norm, which is the square root of the signal energy that Chapter 0 introduced. We apply it to the difference between the new signal and each training signal, and take the smallest.

minj
Try every training signal j, from 1 to m, and keep the smallest result. The label comes from the j that wins.
∑( x[n] − xj[n] )²
At each sample n, subtract, square, and add up over all N samples. This is the energy of the difference signal.
√
Take the root. The root does not change which j is smallest, so a program may skip it.

A full example by hand

Take signals with four samples. The training set holds three signals. x1 = [1, 2, 1, 0] has label A. x2 = [0, 1, 3, 2] has label B. x3 = [2, 2, 0, 1] has label A. The new signal is x = [1, 2, 2, 1].

For x1, the differences are 0, 0, 1 and 1. Squared, they are 0, 0, 1 and 1, which add to 2. The distance is the root of 2, about 1.41.

For x2, the differences are 1, 1, −1 and −1. Squared and added they give 4, so the distance is 2.00. For x3, the differences are −1, 0, 2 and 0. They give 1 + 0 + 4 + 0 = 5, so the distance is about 2.24.

The smallest is x1, at 1.41. Its label is A, so the new signal gets label A. Notice that x and x2 are the only pair that differs by exactly 1 at every sample. Even so, x1 wins, because it matches at two samples exactly.

The data flow, and what it costs

In code, the training set is a table X: (m, N) with one row per signal, and a list y: (m,) of labels. One query is a vector x: (N,). Subtracting gives (m, N). Squaring and summing over the columns gives (m,), one distance per training signal. The index of the smallest picks one entry of y.

Map the nearest-neighbor cells

Each shaded cell is the territory where one training point is the nearest. Warm is class A, blue is class B. Drag any point, or the teal test point. Then press Mislabel one point.

Toy data in a unit square, labelled illustrative: two real numbers per point stand in for the N samples of a signal. Distances are in units of 0.01 of the square’s width. The mislabel button flips the label of the one training point nearest the middle.

Look at the shapes. Every training point owns a convex patch of the map: a polygon made of straight edges. The lecture calls these Voronoi cells, and says the NN rule partitions (splits) the signal space into them. Where an A cell touches a B cell, the boundary is the line of points exactly as far from one as from the other.

That line is straight, and there is a short reason. Say a point z sits equally far from training points a and b. Then the squared distances match: |z − a|² = |z − b|². Expand both sides. The |z|² terms cancel, and what remains is a rule that is linear in z. A linear rule draws a straight line. In N dimensions it draws a flat sheet.

The failure mode: one bad label makes a hole

The symptom: the classifier gives a strange answer in a small spot, deep inside a region of the other class. The measurement: switch on the mislabel button and find the cell that appears. The fix comes in the next chapter.

A single mislabeled or unusual training point owns its whole cell. Every new signal that lands there copies its label, however wrong. NN trusts each example completely. The next chapter softens that trust with a vote.

NN has no training step, which is its charm. It also has a bill at query time. Each query costs m × N subtractions. For a set of 7,724 signals of length 128 (the lecture’s training-set size, and an illustrative length), that is about a million per query.

Why does a single mislabeled training point hurt a 1-NN classifier so much?

Chapter 2

k Nearest Neighbors

Replace one neighbor with a vote of k neighbors, and watch the boundary smooth out as k grows

Back in the new town, you decide not to trust one stranger. You ask the five people standing closest to you. Three say bus 12 and two say bus 40. You take bus 12. One odd answer cannot send you the wrong way any more.

That is k-nearest neighbors (k-NN). The letter k is a whole number that you choose. To label a new signal, find the k training signals closest to it, and take a majority vote: the label that most of them carry wins. The lecture writes it exactly so: assign a label to x[n] by a majority vote over the k training signals closest to x[n].

fk(x)
The classifier’s answer for the new signal x, when it uses k neighbors.
i in the k closest
The indices of the k training signals with the smallest distance to x. Chapter 1 showed how to get those distances.
yi
The known label of training signal i. Each neighbor casts one vote for its own label.
majority
The label with the most votes. With two classes, an odd k can never tie.

Two ends of the dial

The lecture names the two extreme settings. With k = 1, the vote has one voter, and we are back at nearest neighbors. With k = m, every training signal votes, so the answer is the same everywhere: the class that has the most training examples. The lecture says it simply: k = m will always predict the majority class.

So k is a dial between two bad ideas. At the low end, the boundary follows every training point, noise and all. At the high end, the boundary ignores the new signal. The best k lies between. The play area below lets you find the settings for yourself.

Turn the k dial

Thirty-nine training points: 20 of class A and 19 of class B, overlapping. The shading shows what a new point would be labelled at each spot. Drag k from 1 up to 39. Drag the teal test point to see its vote.

1

Toy data, labelled illustrative: two overlapping clouds in a unit square, seeded so they are the same on every visit. Training error counts every training point against its own k nearest points including itself, so k = 1 always scores zero. That is the trap Chapter 5 solves.

At k = 1 the map is full of islands: each stray point carves out a cell, as in Chapter 1. At k = 9 the islands are gone and the boundary is a smooth curve. At k = 39 the map is one solid colour, class A, which has 20 points to class B’s 19. The training error reads zero at k = 1 only because each point votes for itself. At k = 39 it is stuck near 49%. The left end memorizes the data. The right end ignores it.

More than two classes, and a promise

The vote does not care how many classes there are. The lecture notes that k-NN works for multi-class problems, with labels yi in {0, 1, 2, …, L − 1}. Count the votes for each of the L labels and take the largest. With three classes and k = 5, a split of 2, 2 and 1 is a tie. A common fix is to give the tie to the class of the single nearest neighbor.

The lecture then makes a promise about the limit. As the number of training signals m grows without bound, k-NN reaches an error of at most twice the minimum error possible for two classes. What is that minimum? Imagine the two classes overlap, so that some signals could honestly belong to either. Even a perfect judge, who knew the true odds, would be wrong on the confusing ones. That judge’s error rate is the Bayes error. (Our Bayes classifier lesson builds it.)

So the promise reads as follows. If the best possible judge errs 10% of the time, then a nearest-neighbor rule with endless data errs at most 20% of the time. That is a strong guarantee for a rule with no training step. It is a limit in m, not a promise for your data set. With 7,724 signals, you are still far from infinity.

The data flow, once more

The cost is the same as in Chapter 1, plus a small selection step. Compute the distances, shape (m,). Pick the k smallest, for example with np.argpartition(d, k)[:k], which is cheaper than sorting everything. Look up their labels, shape (k,). Count with np.bincount, shape (L,). Take the argmax.

Why the vote helps. A hole needs bad labels to win a vote. With k = 3, one mislabeled neighbor is outvoted by two good ones. The vote spreads trust over k examples instead of putting it all on one.

The failure mode of a large k is quieter. Symptom: the classifier says “A” for almost everything. Measurement: count how many predictions are A, and compare it with the share of class A in the data. At k = m the first is 100% while the second is 51% (20 of 39 in the toy map above), a clear mismatch. The fix is to pick k by testing, not by guessing. Chapter 5 does that.

A training set has 70 signals of class A and 30 of class B. What does k-NN predict for every new signal when k = 100?

Chapter 3

Choosing a Distance

Compare the p-norms on one pair of signals, and see how the ruler decides which signal counts as big

Two sensors watch the same machine for one second each, taking 100 readings. Sensor one wobbles by a tiny amount at every reading, always plus one or minus one. Sensor two reads zero for 99 readings, and then reports a single huge jump of 100. Which sensor shows the bigger disturbance?

Your answer depends on what you care about. If you care about the total amount of movement, they look alike. If you care about the one violent moment, sensor two is far worse. A norm is a rule that turns a signal into one number for its size. Different norms answer this question differently, and nearest neighbors needs one of them.

The p-norm family

The lecture gives one formula that holds a whole family. For a number p that is at least 1, the p-norm of a signal is the p-th root of the sum of each sample’s size, raised to the power p.

||x||p
The size of signal x, measured with the p-norm. To compare two signals, apply it to their difference x − y.
∑ |x[n]|p
Take each sample’s size, raise it to the power p, and add. A large p makes big samples count much more than small ones.
1/p
The root that undoes the power, so the result has the same units as the samples.

Two members get names. With p = 1, the ℓ1-norm adds the absolute values of the samples: the total movement. With p = 2, the ℓ2-norm is the square root of the sum of squares: the Euclidean length, and the root of the energy. The lecture also lists two more. The ℓ∞-norm is the largest absolute sample, and the ℓ0-norm is the number of nonzero samples.

See the shape of each ruler

A norm has a shape. Collect every point whose norm equals exactly 1. For p = 2 you get a circle. Other values of p give other curves. The lecture draws the family in one picture. Slide the value of p and watch the curve change.

Bend the unit ball

The warm curve holds every two-sample signal whose p-norm is exactly 1. The dashed ring is p = 2. Two test signals are marked: one that is all spike, and one that is spread evenly over both samples. Drag p, or press ℓ∞.

2.00

Two samples only, so the shape fits on a page. The curve is |x|p + |y|p = 1 drawn exactly. The spike is (1, 0) and the spread signal is (0.71, 0.71); both have ℓ2 length 1.

At p = 1 the curve is a diamond. At p = 2 it is a circle. As p grows, the curve fills out toward a square, which is the ℓ∞ ball: a square with sides of half-length 1, because only the largest sample matters. The diamond’s sharp tips sit on the axes. A signal that is all spike lives on a tip.

Now see how each norm sizes the two test signals. Both have the same ℓ2 length, 1. The spike has ℓ1 norm 1, and the spread signal has ℓ1 norm 1.41. So ℓ1 thinks the spread signal is bigger, and ℓ∞ thinks the spike is bigger (1 against 0.71). The ruler decides.

The lecture’s example, by hand

Let x1 be the signal of 100 samples that alternate between +1 and −1. Let x2 be the signal with one sample at 100 and 99 zeros.

The ℓ1 norm of x1 is 1 + 1 + … + 1, a hundred terms, so 100. The ℓ1 norm of x2 is 100 + 0 + … + 0, which is also 100. The two signals tie.

The ℓ2 norm of x1 is the root of 1 + 1 + … + 1, a hundred ones, so the root of 100, which is 10. The ℓ2 norm of x2 is the root of 100², which is 100. Under ℓ2 the spike is ten times bigger.

Rank the two signals

Top: x1 wobbles by ±1 at all 100 samples. Middle: x2 is one spike. Pick a norm and read the two bars. Then change the spike height and find where each norm ties.

100

The two signals are the lecture’s: x1 alternates ±1 over 100 samples (its norms are computed here for exactly 100 nonzero samples), x2 is one sample of the spike height and 99 zeros. The default height 100 is the lecture’s.

Slide the height to 10. Now ℓ2 ties, at 10 each, and ℓ1 says the spike is smaller. Slide it to 1. Now ℓ∞ ties, at 1 each. Each norm has its own tie point, and each one asks a different question about the signals.

Which ruler for which job?

Use ℓ2 when a large single error should hurt a lot, and the signals are clean. Use ℓ1 when glitches are common, because one huge sample adds only its size and does not square it. Use ℓ∞ when no single sample may be far off. Use ℓ0 to count how many samples differ at all, whatever the size. (Strictly, ℓ0 is not a norm. It does not scale: doubling a signal does not double its count. It is still a useful count.)

The failure mode shows up with a faulty sensor. Symptom: a clean walking recording is labeled sitting, because one sample jumped. Measurement: compute the distance to the nearest sitting signal under ℓ2 and under ℓ1, and see which one the glitch dominates. The fix is to pick the norm that matches your noise, or to clean the glitch first. The lecture then turns to the one property that makes ℓ2 special.

Signal a has 100 samples of 1. Signal b has one sample of 100 and the rest zero. Which statement is true?

Chapter 4

Why ℓ2 Ignores Rotation

Turn a whole signal space and see which distance survives, and why the DFT is exactly such a turn

You hold a paper map and walk to a friend’s house. You turn the map a quarter turn to read it better. The house did not move. The distance from you to the house did not change. Only the way you wrote the directions changed.

Changing the basis of a signal is that same turn of the map. Swap the time samples for sine waves, and every signal gets new coordinates. A good distance should not care. The lecture states which distances pass this test: the ℓ2-norm is invariant to rotation, and the ℓ1-norm is not.

A rotation, in numbers

In the plane, a rotation by angle θ turns the point (a, b) into (a cosθ − b sinθ, a sinθ + b cosθ). As a matrix, it is R = [[cosθ, −sinθ], [sinθ, cosθ]]. The two columns of R are arrows of length 1, and they are perpendicular. Write that down once: RTR = I, the identity matrix.

Take the point (3, 4) and turn it by 45°. The cosine and sine are both 0.707. The new point is (3 × 0.707 − 4 × 0.707, 3 × 0.707 + 4 × 0.707) = (−0.71, 4.95).

The ℓ2 length of (3, 4) is the root of 9 + 16, which is 5. For the new point it is the root of 0.5 + 24.5, which is the root of 25: also 5. The ℓ1 size was 3 + 4 = 7. Now it is 0.71 + 4.95 = 5.66. The turn changed ℓ1 and left ℓ2 alone.

Why ℓ2 survives, for every rotation

The lecture writes the argument in one line. The squared ℓ2 norm is an inner product of the signal with itself, so ||Rx||22 = ⟨Rx, Rx⟩. Expand it with the transpose.

||Rx||22
The energy of the signal after the turn R.
⟨Rx, Rx⟩
The inner product of the turned signal with itself. This equals its energy.
xT RT R x
The transpose of a product reverses the order, so (Rx)T = xTRT.
xT x
RTR is the identity, so it vanishes. What is left is the original energy.

The same holds for a distance between two signals, because x − y turns into R(x − y). Rotate every training signal and the new signal together, and every ℓ2 distance stays put. The nearest neighbor stays the same. For ℓ1, no such identity exists, and the distances can change. Try it.

Turn the whole map

The teal test point sits at the origin. Candidates A and B turn around it as you drag the angle. Compare the ℓ2 bars with the ℓ1 bars and see who is nearest.

0°

Illustrative: A starts at (2, 0) and B at (1.5, 1.5), with the test point at the origin. Turning every point by the same angle about the origin is a rotation. The same change of coordinates, in higher dimension, is what a basis change does.

At 0° both norms say A is nearest. Drag to 45°. The ℓ2 bars have not moved: A stays nearest, at 2.00 against 2.12. The ℓ1 bars have moved a lot, and B has become the nearest. Same points, same turn, a different winner.

The DFT is a turn, too

Here is the payoff. The DFT is a change of basis from time samples to waves, and with the right scaling it is a rotation of N-dimensional space (a complex one, called a unitary map). That means the lecture’s line: if x[n] has DFT X[k], then ||x[n]||2 = ||X[k]||2. This is the classical Parseval statement, and Chapter 8 proves it from the orthonormal basis idea.

Check it on four samples. Let x = [1, 0, 0, 0], a single spike. Its unnormalized DFT is X = [1, 1, 1, 1]. The energy of x is 1. The energy of X is 4, which is N times larger. Divide X by the square root of N, which is 2, and X becomes [0.5, 0.5, 0.5, 0.5], with energy 4 × 0.25 = 1. The scaled DFT keeps energy.

So, if you run nearest neighbors with ℓ2 on the full complex spectrum, you get exactly the same neighbors as on the time samples. A pure basis change buys nothing. The improvement the lecture reports in Chapter 6 comes from a second step: it keeps only the magnitude of the spectrum and throws the phase away. That step is not a rotation. It discards information on purpose, and it is the part that makes the distance blind to a time shift.

The rule to keep. A norm that comes from an inner product, like ℓ2, does not care which orthonormal basis you describe the data in. A norm like ℓ1 does care.

The failure mode is a surprise after a harmless-looking change. Symptom: you change the feature basis and the classifier’s answers change. Measurement: compare the neighbor lists before and after. If the metric is ℓ1, expect differences. The fix is to know which of your two moves is the culprit: the rotation, or the metric.

You run 1-NN with the ℓ2 distance on x[n], then again on the full complex DFT X[k], scaled to keep energy. What happens to the neighbors?

Chapter 5

Choosing k Honestly

Grade the classifier on signals it has never seen, and compare hold-out with q-fold cross-validation

A student studies for an exam with last year’s paper and its answers. On that same paper she scores 100%. Does that mean she understands the subject? No. She may have memorized the answers. To learn how good she is, give her questions she has never seen.

A k-NN classifier has the same problem. Ask it to label its own training signals and it will look good, because each signal is its own nearest neighbor. At k = 1 the training error is exactly zero, always, whatever the data. A zero tells you nothing. The previous chapter’s device showed the trap.

Hold back a validation set

The lecture’s fix is simple. Keep r signals out of the training set. Call them the validation set: signals xm+1[n], …, xm+r[n], whose labels you know but the classifier never uses as neighbors. Then count how often the classifier fk gets them wrong.

R(fk)
The validation risk of the classifier that uses k neighbors: the share of validation signals it labels wrongly.
1fk(xi) ≠ yi
The indicator: 1 if the answer for signal i is wrong, 0 if it is right.
∑i=m+1m+r
Add up over the r validation signals, which follow the m training signals in the list.
1/r
Divide by the number of validation signals, to turn a count into a rate.

Then minimize over k: compute R for k = 1, 3, 5, and so on, and keep the k with the smallest risk. Worked by hand: say r = 10 validation signals, and k = 1 gets 4 wrong, k = 5 gets 2 wrong, and k = 15 gets 3 wrong. The risks are 0.4, 0.2 and 0.3. The pick is k = 5.

Two ways to do it

The lecture names two schemes. In the hold-out method, you split once: for example 70% of the signals train and 30% validate. It is cheap. It has two weaknesses. The result depends on which signals landed in the 30%, and the validation signals are never used as neighbors, which wastes data.

In q-fold cross-validation, you cut the data into q equal parts, called folds. Take fold 1 as the validation set and the other q − 1 folds as training, and record the error. Then take fold 2, and so on, so every signal is validated exactly once. Average the q errors.

Worked by hand: 40 signals, q = 5 folds, 8 signals in each fold. The five folds produce 2, 1, 3, 2 and 2 wrong answers. That is 10 wrong of 40, a cross-validated error of 0.25. Every signal served as validation once, and as training four times. The cost is q runs of the classifier. For k-NN that is cheap, because there is nothing to retrain: each run just changes which signals count as neighbors.

One extreme is worth knowing. With q equal to m, each fold holds a single signal. This is leave-one-out. It uses the most data for training, and it costs m runs.

Pick k four ways

The same 39 points as before. Each curve is an error rate against k. The dashed grey curve is the training error, which always favors k = 1. Choose a scheme and see which k it picks.

5

Toy data, labelled illustrative: the 39 points of Chapter 2, split by a seeded shuffle. The hold-out scheme holds back 12 points, so each error is a multiple of 1/12. The 5-fold scheme deals the shuffled points into 5 folds of 7 or 8. The lecture gives the schemes and the risk formula; these error curves are this toy set’s own.

Choose “Training error” first. The curve starts at zero at k = 1 and the pick is always k = 1. Now choose “5-fold”. The curve starts well above zero, dips in the middle, and rises again. The dip is the honest answer: some smoothing helps, a lot of it hurts. Next, flip between hold-out and leave-one-out. They may pick different k. That disagreement is real: with few signals, the best k is blurry.

When to trust which

A larger q uses more data to train each run and gives a steadier answer, at a higher cost. A smaller q is cheaper and a bit pessimistic, since each run trains on less. A common middle choice is 5 or 10 folds. Leave-one-out is the most thorough and, for k-NN, still affordable on small sets.

The failure mode has a clear symptom. Symptom: the chosen k is 1, and the test accuracy is far lower than the one you measured. Measurement: you picked k using training error, or you used the validation set to tune k and then reported the same number as your final score. Fix: choose k with validation or cross-validation, and report the accuracy on a separate test set that no choice has ever touched. Chapter 6 shows the lecture doing exactly that, with 7,724 signals to train and 2,575 to test.

You choose k by minimizing the error measured on the training signals themselves. Which k wins, and why is it misleading?

Chapter 6

The Phone Experiment: 77, 85, 91, 96

Follow one real data set through four methods, and see why dropping the phase of the DFT gains eight points

Researchers asked volunteers to carry a smartphone on the waist and to walk, climb stairs, sit, stand and lie down. The phone recorded its accelerometer all the while. The result is the Human Activity Recognition Using Smartphones data set (Reyes-Ortiz and colleagues, 2012). The lecture uses it as its test bench. The task: from a short burst of acceleration, say what the person was doing.

The lecture splits the data into 7,724 training signals and 2,575 test signals. Each signal has a time-domain form: samples on three acceleration axes, x, y and z, in time order. Every result in this chapter is a score on the same 2,575 test signals.

First try: nearest neighbors on the samples

The first experiment is the plain recipe from Chapters 1 and 2. Use 3-NN, with the ℓ2 distance, directly on the time samples x[n]. The lecture reports an accuracy of 0.77. Out of 2,575 test signals, that is about 592 wrong.

The slide before the result carries only a title: problems with time domain representation. The problem is timing. A person walks at a steady pace, but the recording begins at a random moment of the step cycle. Two bursts of the same walk have the same shape, shifted along the time axis. Sample by sample, they look very different, as the hero showed.

The cure: the DFT, and the shift property

The lecture brings back the DFT as a change of basis. A signal is written as a sum of N complex waves, each scaled by a coefficient X[k]. (We use the scaled form with 1/√N in front, so that the basis is a rotation, as Chapter 4 explained.) The key fact is the shift property: if you move the signal later by n0 samples, wrapping around at the end, every coefficient X[k] is multiplied by the complex number e−j2πn0k/N.

x[(n − n0) mod N]
The signal delayed by n0 samples. The “mod N” wraps the end of the window round to the start.
↔
The two sides are a DFT pair: one in time, one in frequency.
e−j2πn0k/N
A turn in the complex plane by an angle that grows with k and with the delay. Its size is exactly 1.
X[k]
The coefficient for wave number k of the original signal.

Because the multiplier has size exactly 1, it turns each coefficient and never stretches it. The phase (the angle) of X[k] changes with the delay. The magnitude |X[k]| does not change at all. So the magnitude spectrum is a fingerprint that ignores when the recording started. The lecture computes the DFT of every training signal and uses the magnitudes |X1[k]|, …, |Xm[k]|.

Delay the recording

The grey curve is a walking-like signal. The teal curve is the same signal delayed. Right: one DFT coefficient as an arrow. Drag the delay and compare the two distances.

0

Illustrative signal of 64 samples: a 3-cycle wave plus a weaker 7-cycle wave, standing in for a walking burst. Distances are exact for this signal. The arrow shows the coefficient at k = 3 of the unscaled DFT; its angle turns by 2πn0k/N and its length stays put.

With zero delay, both distances are zero. With a delay of 5 samples, the time-domain distance is already large, while the spectrum distance is still zero. Drag the delay all the way around. The time distance rises and falls, and the arrow goes round the circle, but the spectrum bar never moves.

Reading the lecture’s results

The same 3-NN with ℓ2 on |X[k]| scores 0.85. That is about 386 wrong. Eight points came from one idea: compare shape, not timing. Chapter 4 told you the plain DFT would change nothing. This is the proof that magnitude is what helps.

The next two rows on the slides carry a credit to Taspinar. A wavelet transform (a change of basis whose waves are short and local in time, from our wavelets lesson) scores 0.91. A wavelet transform followed by a deep network scores 0.96. Wavelets keep both when and how fast the signal moves, so they are not blind to timing the way the full-window spectrum is.

Climb the ladder

Four methods on the same 2,575 test signals. Pick a rung to see what changed and how many signals it fixed.

Accuracies are the lecture’s (slides 28 to 30; the last two credit Taspinar). Wrong-signal counts are 2,575 times (1 minus accuracy), rounded: the accuracies are given to two decimals, so the counts are approximate.

The ladder has a lesson in it. The first step, from 0.77 to 0.85, needed no learning at all, only a better space. The last step, to 0.96, used a learned model. Choosing the representation often matters as much as choosing the classifier.

The cost of the magnitude trick is real. Dropping the phase throws away information: two different signals can share a magnitude spectrum. For walking versus sitting that is a good trade. For a task where the order of events matters, it would not be. The failure mode: symptom, two distinct activities get the same label because their spectra match; measurement, compare the confusion table of the spectrum method with the wavelet one; fix, keep local timing, as wavelets do.

Why does 3-NN on |X[k]| beat 3-NN on x[n] for activity signals recorded from random starting moments?

Chapter 7

Three Ingredients of a Hilbert Space

Test the rules that make a space of signals feel like ordinary geometry, one ingredient at a time

We have used the words distance, length and energy as if they came free. In the plane they do. You draw an arrow and measure it. A signal of 128 samples is an arrow in 128 dimensions, and nobody can draw it. What lets us still talk about its length, and about right angles between two signals?

The lecture’s answer is a short list of rules. A space that obeys them is a Hilbert space. Any space on the list behaves like the plane, however many dimensions it has, and even if its “vectors” are signals with infinitely many samples. The lecture builds the list from three ingredients.

Ingredient 1: a vector space

We start with a collection of vectors (here, signals) and a set of scalars (real or complex numbers). The collection must be closed under two operations. Closed means that the result of the operation never leaves the collection. First, vector addition: if x and y are in the space, then x + y is too. Second, scalar multiplication: if x is in the space and α is a scalar, then αx is too.

Signals pass easily. Add two length-N signals sample by sample and you get a length-N signal. Multiply by 2 and you get another. The set of all fixed-length signals is a vector space.

Ingredient 2: an inner product

An inner product ⟨x, y⟩ takes two vectors and returns one number. It measures how much two signals point the same way. For real vectors in the plane, it is x0y0 + x1y1. The lecture lists four rules. A candidate formula is only an inner product if it obeys all four.

  1. Positive. ⟨x, x⟩ ≥ 0, and it equals 0 only when x is the zero vector. (This is what makes a length possible.)
  2. Scales. ⟨x, αy⟩ = α⟨x, y⟩, and ⟨αx, y⟩ = α*⟨x, y⟩. The star is the complex conjugate: flip the sign of the imaginary part. For real scalars it does nothing.
  3. Distributes. ⟨x + y, z⟩ = ⟨x, z⟩ + ⟨y, z⟩.
  4. Conjugate-symmetric. ⟨x, y⟩ = ⟨y, x⟩*. For real signals, the order does not matter.

The lecture checks the dot product on the plane, one rule at a time. Rule 1: ⟨x, x⟩ = x0² + x1², which is never negative, and it is zero only when x0 = x1 = 0. Rule 2: ⟨x, αy⟩ = x0(αy0) + x1(αy1) = α(x0y0 + x1y1) = α⟨x, y⟩. Rule 3: ⟨x + y, z⟩ = (x0 + y0)z0 + (x1 + y1)z1, and expanding gives ⟨x, z⟩ + ⟨y, z⟩. Rule 4: x0y0 + x1y1 = y0x0 + y1x1, because numbers commute. All four hold.

Now be the judge. Pick a candidate formula below. The device tests the four rules on fixed example vectors and shows the number that decides each one.

Judge the candidate

Each candidate takes x = (x0, x1) and y = (y0, y1) and returns a number. Pick one and see which rules it breaks.

Real scalars only, so the conjugate does nothing. Test vectors, fixed: for positivity, the five vectors (1,0), (0,1), (1,1), (1,−1), (2,−3); for the other rules, x = (1,2), y = (3,−1), z = (2,5) and α = 2. Passing a few examples is not a proof; the dot product’s proof is the algebra above. A failure on one example is a proof of failure.

The dot product and the weighted version pass. The minus sign fails rule 1: for x = (0, 1) it gives −1, a negative energy, and no length can be the root of that. The cross term fails rule 4 and rule 1 too. A formula that fails any rule cannot give a length or an angle.

From the inner product we get a norm for free: ||x|| is the root of ⟨x, x⟩. That is how ℓ2 was born. From the norm, we get distance: ||x − y||. And when ⟨x, y⟩ = 0, we say the signals are orthogonal, the plane’s right angle.

Ingredient 3: completeness

The last ingredient is about limits. Say you have a sequence of vectors that crowd closer and closer together, so that after some point every two of them are nearer than any gap you name. This is a Cauchy sequence. The space is complete when every such sequence has a limit inside the space. The lecture puts it this way: every Cauchy sequence converges.

Why ask? Think of the decimals 3, 3.1, 3.14, 3.141, and so on. They crowd together, but their limit, π, is not a fraction. So the fractions are not complete: the sequence converges to a hole. A Hilbert space has no such holes. A search that creeps toward an answer, such as a best fit, can trust that the answer exists.

Watch a Cauchy sequence close in

The grey square wave lives on [−1, 1]. The teal curve is a sum of its first few sine waves. Add terms and watch two distances shrink: the step to the next sum, and the gap to the square wave.

3

The L2 distance is the root of the integral of the squared difference over [−1, 1]. Illustration with an exact sum: the m-th sum is (4/π) ∑ sin(jπt)/j over the first m odd j; the sine waves are orthogonal on [−1, 1], each with energy 1, so the squared step to the next sum is (4/(πj))² and the squared gap to the square wave (energy 2) is 2 minus the energy collected so far.

With 3 sine waves the gap to the square wave is still about 0.37, and the step to the next sum is 0.18. With 30 sine waves the gap is about 0.12 and the step is 0.02. The step shrinks faster than the gap. Each sum is a smooth sine curve, yet the limit is a square wave with a jump. The limit lives in the space of square-integrable signals, so it counts as a vector there. That is completeness at work.

The spaces that qualify

The lecture closes the list with four spaces that pass all three tests. RN (real signals with N samples, with the inner product ∑x*[n]y[n]). CN (the same with complex samples, which is where DFT coefficients live). L2[−1, 1] (continuous-time signals on that interval whose energy ∫|x(t)|²dt is finite, with the inner product ∫x*(t)y(t)dt). And ℓ2(Z) (infinite-length discrete signals whose energy ∑|x[k]|² is finite). One theory covers all four.

The failure mode for newcomers: symptom, a proof or formula that worked for vectors in the plane fails for a strange space. Measurement: check which of the three ingredients the strange space lacks. Fix: a space that has all three can reuse every theorem of the plane.

A candidate formula gives ⟨x, x⟩ = −1 for x = (0, 1). Which inner product rule does it break?

Chapter 8

Closest Points and Conserved Energy

Use the Hilbert space geometry to find the unique best approximation, and prove that energy survives a change of basis

You stand in a field. A fenced pen sits somewhere ahead. You want to touch the fence at the spot nearest to you. Is that spot unique? For a round pen, yes. For a pen with a dent in its side, you can stand where two spots tie. This one question is the heart of denoising, regression and much of classification.

The lecture turns the field into a Hilbert space and the pen into a set A. It then asks for the point of A closest to a given signal x. Two ideas answer it: convexity and the fundamental theorem of approximation.

Convex sets

A set A is convex if for any two points x and y in A, every point on the straight segment between them is in A too. In symbols: λx + (1 − λ)y is in A for every λ between 0 and 1. With λ = 1/2 you get the midpoint. A disk is convex. A banana is not: the midpoint of its two tips falls outside.

||x − a||
The distance from the signal x to a point a of the set.
a ∈ A
Try every point a of the set A. A must be nonempty, convex and closed (it contains its own boundary).
argmin
The point that gives the smallest distance, not the distance itself.
p*
The best approximation of x in A. The theorem says it exists and is unique.

This is the fundamental theorem of approximation. Let A be a nonempty, closed, convex set in a Hilbert space H. For any x in H there is a unique point in A closest to x. As a special case, take x = 0: there is a unique point of A with the smallest norm, the minimum-energy point. The lecture lists its uses: signal denoising, kernel regression and classification.

Find the closest point

Drag the teal point x. The green point is the closest point of the shaded set. Try all three sets, then press Put x at the origin to find each set’s minimum-energy point.

Toy sets in a unit square with the origin at the bottom-left corner: a disk of radius 0.2 at (0.6, 0.6), a box from (0.45, 0.4) to (0.8, 0.7), and two disks of radius 0.16 at (0.3, 0.7) and (0.7, 0.3). The nearest point is computed exactly; a tie is reported when the two closest points differ by under 0.012 in distance.

Why can a convex set have only one closest point? Suppose two points p and q of A both sit at the same smallest distance d from x. Convexity puts their midpoint m inside A. A short identity (the median formula) says that |x − m|² = (|x − p|² + |x − q|²)/2 − |p − q|²/4. The first part equals d². Subtract a positive amount, and m is closer than d. That contradicts the choice of d, unless p = q.

Run the two-disk set from the origin. The two disks sit symmetrically, so both are equally near. The device reports a tie, and the argument above shows why: the midpoint of the two touching points lies in the gap, outside the set, so it cannot save the day. Convexity is the missing ingredient.

Subspaces, span, dimension

Three more words from the lecture finish the vocabulary. A subspace is a set of vectors closed under addition and scaling: if x and y are in it, so is αx + βy. A line through the origin is a subspace of the plane. A subspace is always convex, so the theorem applies to it. The best approximation in a subspace is the familiar projection.

The span of a set of vectors is every combination ∑αmx(m) you can build from them. In RN, the span of the N spike signals δ0, …, δN−1 is everything. In CN, the span of fewer than N Fourier waves is a smaller subspace: signals made from only those frequencies. The dimension is the number of independent vectors needed to span the whole space. Length-N signals need N spikes, so RN has dimension N.

Parseval: energy does not care about the basis

Now return to the rotation of Chapter 4. Let y(0), …, y(N−1) be an orthonormal basis: each has length 1, and any two are orthogonal. Any signal is x = ∑cky(k), with ck = ⟨y(k), x⟩. Take the energy: ⟨x, x⟩ = ∑∑ck*cl⟨y(k), y(l)⟩. Every cross term with k ≠ l is zero, and every term with k = l has ⟨y, y⟩ = 1. So only ∑|ck|² survives.

||x||2
The energy of the signal, found in the original coordinates.
∑|⟨y(k), x⟩|2
The energy found in the new coordinates: the squared size of each coefficient, added up. This is Parseval’s identity.

Worked check with the plane. Use the 45° basis y(0) = (0.707, 0.707) and y(1) = (−0.707, 0.707), and x = (3, 4). The coefficients are 0.707 × 3 + 0.707 × 4 = 4.95 and −0.707 × 3 + 0.707 × 4 = 0.71. Their squares are 24.5 and 0.5. They add to 25, the energy of (3, 4).

The Fourier basis wk[n] = (1/√N)e−j2πnk/N is orthonormal, so the classical identity follows: ∑|x[n]|² = ∑|X[k]|², with the scaled DFT. The same energy, counted two ways.

Count the energy twice

Top: the energy of each sample of a 16-sample signal. Bottom: the energy of each scaled DFT coefficient. Pick a signal, then delay it, and compare the two totals.

0

Illustrative 16-sample signals. The spectrum uses the scaled DFT with 1/√16 in front, so the Fourier basis is orthonormal and Parseval holds exactly. Spike: a single sample of height 3. Sine: 2 cycles, amplitude 2. Mixture: a 1-cycle sine of amplitude 2 plus a 5-cycle sine of amplitude 1.

Choose the spike. In time, one tall bar of 9. In frequency, sixteen equal short bars of 0.5625, which add to 9. Choose the sine: in frequency only two bars are lit, at k = 2 and k = 14, with 16 each. Delay any signal. The time bars slide around, the frequency bars stay the same height, and both totals stay put.

The failure mode is a unit mismatch. Symptom: the energy of the spectrum is 16 times the energy of the signal. Measurement: divide one by the other and see N. Fix: use the scaled DFT, or divide the sum by N. The slide’s first DFT formula has no 1/√N, so keep track of which one you hold.

Why can the closest point of a convex set to x never be a tie between two different points p and q?

Chapter 9

The Null Space: What a Measurement Cannot See

Find the signals that a matrix turns into zero, and learn why their size tells you whether the columns are independent

A microphone records sound. It has a limit: above some pitch it hears nothing. A bat could squeak at that pitch all night, and your recording would stay flat. The bat’s squeak is invisible to the microphone. Every measurement device has a set of signals like that. The lecture gives the set a name: the null space.

The lecture ends on this idea in two slides. It matters for classification. A classifier that works from measurements cannot tell apart two signals that the measurement cannot tell apart.

A matrix is a measurement

Take a matrix A with M rows and N columns, with complex entries. Feed it a signal x of N samples and it returns Ax, a list of M numbers. In shapes: A: (M, N), x: (N,), Ax: (M,). Each of the M outputs is one measurement, a weighted sum of the samples.

The null space is the set of all signals that the matrix maps to exactly zero.

N(A)
The null space of A: every signal that A cannot see. It always contains the zero signal.
x ∈ CN
A signal with N complex samples, the same length that A accepts.
Ax = 0
The measurement reads zero in every one of its M outputs.

A worked example

Let A have two rows and three columns: row one is (1, 0, 2) and row two is (0, 1, 3). A signal x = (x1, x2, x3) maps to (x1 + 2x3, x2 + 3x3). For the output to be zero, both entries must vanish. So x1 = −2x3 and x2 = −3x3.

Set x3 = t. Then x = t(−2, −3, 1). Check with t = 1: A times (−2, −3, 1) gives (−2 + 2, −3 + 3) = (0, 0). The null space is a whole line through the origin. Three samples go in, two measurements come out, and one direction is lost.

That count is no accident. The size of the null space plus the number of independent rows equals N. Here 1 + 2 = 3. A measurement with fewer outputs than inputs always loses something.

Columns, and why independence matters

Write A as a row of its columns: A = [a1 a2 … aN]. Then Ax = x1a1 + x2a2 + … + xNaN. The product is a mix of the columns, and x says how much of each. So Ax = 0 means that some mix of the columns cancels to zero.

The columns are linearly independent if no mix cancels except the trivial one where every xn is zero. The lecture states it as a rule: a1, …, aN are linearly independent exactly when N(A) = {0}. If a nonzero x sits in the null space, then one column can be built from the others, and it adds nothing new.

Close the loop

The warm arrow is column a1 = (1, 0), the blue arrow is a2 = (0, 1). The purple arrow is a third column you place with the sliders. Slide t and watch the scaled columns, laid tip to tail, find their way back home.

2.0
3.0
1.00

Illustrative 2-by-3 matrix with a1 = (1, 0), a2 = (0, 1) and a third column of your choice; the default (2, 3) is this chapter’s worked example. With the third column on, the null space is the line t(−a31, −a32, 1), computed exactly. With it off, the two columns are independent and the null space is only {0}.

With the third column on, drag t to 1. The path goes left 2 along a1, down 3 along a2, then up and right along a3, and lands on the origin. Every value of t closes the loop, so the null space is a line. Turn the third column off. Now no nonzero mix of two perpendicular columns returns home: the columns are independent, and the null space is just the origin.

What it means for classifying signals

Suppose a classifier works on features Ax, for instance a few averages of the samples. Take two signals x and x + n, where n lies in the null space. Their features are identical: A(x + n) = Ax + An = Ax. The classifier gives them the same label, always, whatever the data.

The lecture’s magnitude trick is not a matrix, so this is not the same thing. It is a close cousin. It also builds a feature that ignores one kind of difference, the phase. The question is always: what does my feature throw away, and does the classes’ difference live there?

The failure mode: symptom, the classifier cannot separate two classes however much data you give it. Measurement: check whether the class difference lies in the null space of your feature map. Fix: change the features so that the difference becomes visible.

A matrix A has 2 rows and 3 columns. Which statement must be true?

Chapter 10

Field Guide: The Whole Lecture on One Page

Keep the numbers, the checklist and the core code, and see where this lecture leads next

The lecture makes one move and then explains why it works. The move: label a new signal by its closest labeled neighbors. The refinements: pick the ruler, pick k with honest validation, and pick a space where the signals of one class sit close together. The explanation: signals live in a Hilbert space, where lengths, angles and closest points behave as they do in the plane.

The course logistics for this session are short. It is Lecture 4 of the January 2019 offering, taught by Mert Pilanci, with slides on the course site. We have taught every slide here in our own words and devices, and the real data results are the lecture’s.

The numbers to remember

QuantityValueWhere it came from
Energy of the signal [3, 4]25, so the norm is 5Chapter 0, worked by hand
Wobble and spike under ℓ1100 and 100, a tieSlide 13
Wobble and spike under ℓ210 and 100Slide 14
Error of 1-NN with unlimited dataat most 2 times the minimum possibleSlide 11, two classes
Training error of 1-NN0, alwaysChapters 2 and 5
Training and test signals7,724 and 2,575Slide 28
3-NN, ℓ2 on x[n]accuracy 0.77Slide 28
3-NN, ℓ2 on |X[k]|accuracy 0.85Slide 28
Wavelet transformaccuracy 0.91Slide 29, credit Taspinar
Wavelet transform + deep learningaccuracy 0.96Slide 30, credit Taspinar
Energy of (3, 4) in the 45° basis24.5 + 0.5 = 25Chapter 8, Parseval
Null space of the 2-by-3 exampledimension 1, the line t(−2, −3, 1)Chapter 9, worked by hand

The terms, in plain words

TermPlain meaning
Nearest neighborCopy the label of the single closest training signal.
k-NNTake a majority vote among the k closest training signals.
Voronoi cellThe territory where one training signal is the nearest.
p-normOne number for the size of a signal; p picks how much big samples count.
Validation setSignals with known labels, kept out of training, used to grade a choice of k.
q-fold cross-validationCut the data into q parts and let each part be the validation set once.
Hilbert spaceA vector space with an inner product and no holes (completeness).
Parseval identityThe energy is the same in every orthonormal basis.
Null spaceThe signals a matrix turns into zero.

The checklist before you ship a distance classifier

  1. Decide what must not matter. Shift, loudness, rotation? Choose features that ignore it.
  2. Pick the ruler. Use ℓ2 for clean data, ℓ1 where glitches occur.
  3. Pick k by cross-validation, never by training error.
  4. Keep a test set that no choice has touched, and report its accuracy.
  5. Check the cost. One query costs m × N operations. Plan for it.
  6. Look at the mistakes. Ask what your features throw away.

The core as code

This is the whole lecture, runnable. The features switch between raw samples and the scaled DFT magnitude. The shapes sit in the comments.

pythonimport numpy as np

def features(X, mode):                          # X: (m, N), one signal per row
    if mode == "spectrum":
        return np.abs(np.fft.fft(X, axis=1)) / np.sqrt(X.shape[1])   # (m, N), ignores shifts
    return X

def knn_predict(Xtr, ytr, Xq, k=3, p=2):         # Xtr (m,N)  ytr (m,) ints  Xq (q,N)
    diff = Xq[:, None, :] - Xtr[None, :, :]       # (q, m, N)  chunk Xq if this is too big
    d = np.linalg.norm(diff, ord=p, axis=2)       # (q, m)     one distance per training signal
    idx = np.argpartition(d, k - 1, axis=1)[:, :k]   # (q, k)     the k closest, no full sort
    votes = ytr[idx]                                 # (q, k)     their labels
    L = ytr.max() + 1
    counts = np.stack([np.bincount(v, minlength=L) for v in votes])   # (q, L)
    return counts.argmax(axis=1)                  # (q,)       the majority label

def cv_error(X, y, k, q=5, seed=0):
    order = np.random.default_rng(seed).permutation(len(y))
    wrong = 0
    for fold in np.array_split(order, q):
        train = np.setdiff1d(order, fold)
        wrong += (knn_predict(X[train], y[train], X[fold], k) != y[fold]).sum()
    return wrong / len(y)

F = features(X, "spectrum")
best_k = min(range(1, 26, 2), key=lambda k: cv_error(F, y, k))   # choose k honestly

Where this sits in the field

Nearest neighbors is the baseline that every smarter method must beat. The wavelet row on the ladder is the subject of the wavelets lesson and its applications. The best-possible judge from Chapter 2 is built in the Bayes classifiers lesson. Learned boundaries come next: Fisher’s discriminant and support vector machines. Kernel regression, named among the closest-point applications, is in the kernels lesson, and the Hilbert space idea returns in RKHS. The spectrum tools are in the DFT, spectral descriptors and STFT lessons.

The takeaway. A nearest-neighbor classifier is only as good as its notion of “near”. The ruler, the features and k are three dials. Hilbert space geometry tells you what each dial can and cannot change: ℓ2 survives rotation, magnitudes survive shifts, and a null space hides what a feature cannot see.

Now press Present or Teach and explain one thing out loud, from memory: why 3-NN on the DFT magnitude beat 3-NN on the samples, and what the magnitude gave up to get there. Then go back to the instrument at the top, set the noise to 0.45, and find the shifts where each space still gets the label right.

Credit: Lecture 4 of Stanford EE269, Signal Processing for Machine Learning, by Mert Pilanci. See the slides and the course site. The phone data set is by Reyes-Ortiz and colleagues (2012); the wavelet results carry a slide credit to Taspinar.

EE269 Lecture 9: Distance-Based Classification and Hilbert Spaces
Re-taught from Mert Pilanci’s EE269 slides · Course site · Back to Gleams