Signal Processing for Machine Learning

A signal is a list of numbers, and machine learning learns from lists. How you write the list matters: one phone motion sensor scores 77% on raw samples and 95% after the right transform.

Pick an activity, slide where its cycle starts, then press Test 90 signals. Watch the raw samples fail and the spectrum hold. Then we build the whole lecture, piece by piece: samples, features, faces, voices, neurons and depth.

You need basic algebra and a feel for a sine wave (a smooth wave that repeats). We build the rest from zero.

Based on Lecture 1 of Stanford EE269: Signal Processing for Machine Learning (Fall 2020), taught by Mert Pilanci. Lecture slides (PDF), all decks. Every idea is re-taught here in our own words and devices. Next lesson: Discrete signals and vector spaces.

Read one signal two ways

0°
0.30

Toy data, made in your browser: each signal is 64 samples of a sine wave (0.1 high for sitting, 3 cycles for walking, 5 for running) plus noise, and 15 training signals (5 per activity) start at random points of their cycle. 3-NN (3 nearest neighbours) votes among the 3 training signals closest in straight-line distance. The deck’s real numbers for real phones (77% raw, 85% spectrum, 91% CNN, 95% wavelet features) come in Chapter 9.

Chapter 0

Why a Learning Machine Needs Signal Processing

Count the numbers a sensor makes, and see why raw numbers alone are a hard way to learn

You say “hey” to your phone. A tiny microphone measures how hard the air pushes on it, and it measures that 16,000 times every second. After one second the phone holds a list of 16,000 numbers. That is all it has.

Nothing in that list says “hey”. No number is a vowel, a pitch or a person. Yet a program must read the list and decide: who spoke, and what did they say? The same problem appears when a watch counts your steps, a doctor reads a brain scan or a camera finds a face. Each one starts with a long list of numbers that came from a sensor.

This course sits where two fields meet. Signal processing is the older field: it studies lists of numbers that come from the world, and it knows how to clean them, reshape them and pull facts out of them. Machine learning is the newer field: it builds programs that learn a task from examples instead of from hand-written rules. Each field is weak where the other is strong, and Stanford’s EE269, taught by Mert Pilanci, teaches them together.

How big is the list?

Start with the size of the problem, because size explains a lot. Different sensors make very different amounts of data. Pick one below and set how long it records. The bars use a log scale: each gridline is ten times more than the one before it.

Count the numbers

Four bars show how many numbers each source makes in the time you pick. Choose one source to light its bar, then drag the recording time.

10 s

Illustrative rates: speech at 16,000 samples per second (a common rate for speech, one microphone), a phone motion sensor with 3 axes at 50 readings per second, 30 frames per second of a 1,000 by 1,000 grey picture, and typing at 5 characters per second. Reading speed is set at 3 numbers per second.

Ten seconds of speech is 160,000 numbers. If you read them aloud at three per second, you would still be reading tomorrow. A model that must find a word inside that list, with no help, has a lot to sort through. Most of the numbers repeat each other, and most of the rest are noise.

What this course sets out to teach

The lecture states four goals. First, learn mathematical models for signals, for the systems that change them, and for the transformations that re-write them. Second, learn methods that extract information from a signal. Third, learn the theory of machine learning that applies to signals. Fourth, learn to implement the algorithms that process, learn and classify signals, which means writing code, not just reading proofs.

The lecture then spends a little time on the course itself, so here it is in one paragraph. The class met on Zoom on Mondays and Wednesdays in the fall of 2020, with instructor Mert Pilanci and course assistant Tolga Ergen. It expects exposure to signals and systems, basic probability, some programming in Matlab or Python and familiarity with linear algebra. Homework counts 60% (bi-weekly, with programming, handed in through Gradescope, groups of up to four allowed but each person writes their own answers), the project counts 40% (a group of two or three, a one-page proposal, then a video and a report due on November 20), and Piazza contributions earn 5% extra. The readings are Bishop’s Pattern Recognition and Machine Learning, Prandoni and Vetterli’s Signal Processing for Communications, Goodfellow, Bengio and Courville’s Deep Learning and Boyd and Vandenberghe’s Introduction to Applied Linear Algebra, all free online.

The claim of this lesson. Machine learning does not read a signal. It reads a list of numbers, and the choice of list (raw samples, a spectrum, a learned feature) can decide whether it works. The hero at the top of the page is the smallest version of that claim.

The rest of this page follows the lecture in order. It starts with what a signal is, moves through the applications the lecture shows, then the history of neural networks, and ends with the map of the whole course.

  1. What a signal is: a function, and the two jobs of processing it.
  2. Samples: x[n] = x(nT), and how two waves can leave the same numbers.
  3. Arrays: sound, photos, text and ratings as lists with a shape.
  4. What machine learning adds: patterns, features and a speaker identifier.
  5. Brains and bodies: brain scans and activity from a wrist.
  6. Faces: the 2001 detector and its sums of rectangles.
  7. Voices: the spectrogram and microphone arrays.
  8. The first neural networks: Adaline and the convolutional idea.
  9. Depth and the activity test: when learned features beat chosen ones.
  10. The course map: ten topics, the open questions and convexity.
  11. Field Guide: numbers, terms, a checklist and the core code.
A model must find the word “hey” in 10 seconds of raw speech. Why is that hard for a model with no signal processing at all?

Chapter 1

What a Signal Is, and What Processing Does

Treat a signal as a function, then split the work into converting it and reading it

Put a clip on your fingertip, and a small sensor shines light through the skin. Each time your heart pushes blood into the finger, the skin gets a little darker. The sensor turns that darkness into a voltage, and the voltage into a line that wobbles up and down once per heartbeat. The line is also fuzzy, because the skin moves and the electronics hiss. How do you describe that line in mathematics, and how do you get a heart rate out of it?

The lecture opens with one plain sentence: a signal is, mathematically, just a function. A function is a rule that takes an input and returns exactly one output. For a signal, the input is usually time, and the output is a measurement. Write it x(t): at time t, the sensor reads x(t). For a photo, the input is a position (row and column) and the output is a brightness. The word signal sounds grand, but the content is modest: a rule from where or when to how much.

The simplest signal: a sine wave

One signal appears everywhere in this course, so meet it now. A sine wave is a smooth curve that rises, falls and repeats forever. A tuning fork makes one: the air near the fork is pushed and pulled in a perfect repeating pattern. The wave has three numbers that describe it.

x(t)
The reading at time t, in seconds. This is the signal itself: a function from time to a measurement.
A
The amplitude: how high the wave rises above zero. Bigger A means a louder tone.
f
The frequency: how many full cycles happen each second, in hertz (Hz). Bigger f means a higher pitch. The time for one cycle is the period, 1/f.
φ
The phase: where in its cycle the wave starts at t = 0. Shift φ and the wave slides sideways but keeps its shape.

440 Hz tone: period = 1/440 = 0.00227 s, so the wave repeats every 2.27 ms and completes 440 cycles in one second.

Real signals are rarely a single sine. A heartbeat looks like a sine at about 1.2 Hz (72 beats a minute) plus smaller waves at twice that rate, plus noise. Keep this picture: a real signal is a stack of sine waves, and the amplitudes tell you how much of each frequency is there. Chapter 4 and the lessons that follow turn that idea into the Fourier transform.

Two jobs for processing

The lecture then defines signal processing as two jobs. The first job is to convert one signal to another: filter it, de-noise it, interpolate it (fill in values between the ones you have). The input is a signal and the output is a signal. The second job is information extraction and interpretation: speech recognition, computer vision. The input is a signal and the output is a fact, such as a word or a heart rate.

The two jobs help each other. Cleaning a signal first often makes the fact easier to read. The device below runs both jobs on the pulse line from the opening. Drag the window width and watch the line, the beat count and the error.

Clean the pulse, then count it

Top: ten seconds of noisy pulse. The faint line is the raw reading, the dashed blue line is the true pulse and the bold line is your smoothed version. Pink dots are the beats the program counts. Bottom: how far your line is from the truth at each window width.

1 sample

Toy signal made in your browser: a 72 beats per minute pulse (1.2 Hz plus a second wave at 2.4 Hz) sampled at 100 readings per second, with Gaussian noise of 0.6. The smoother is a moving average centred on each sample. A beat is a local peak above 0.5 and at least 0.4 s after the last one. Error is the root mean square (rms) distance from the true pulse.

Look at what the slider does. At width 1 the line is raw, and the program counts far too many beats, because every noise spike looks like a peak. Widen the window, and each point becomes the moving average of its neighbours. Now the count settles at 12 beats in 10 seconds, which is 72 beats per minute.

y[n]
The smoothed signal, at sample number n. The square brackets mean the signal is a list, indexed by whole numbers (Chapter 2).
1 / w
One divided by the window width w, the number of samples in the average. Dividing makes it an average instead of a total.
k = −h to h
The neighbours to include: h samples before n and h after, where w = 2h + 1. A window of 7 uses h = 3.

Why does averaging help? Each raw reading is the true pulse plus an independent bit of noise. Averaging seven of them keeps the pulse, which changes slowly, and the noise bits partly cancel. With w independent readings, the noise shrinks by about the square root of w. For w = 7 that is a factor of 2.6, so noise of 0.60 falls to about 0.23.

Now the failure mode. Push the window past about 60 and the line goes flat. The symptom: the beats vanish and the count falls to zero. The measurement: the average of a window as wide as a whole beat (83 samples at 72 beats a minute) sums the high and low parts together. For a window of w samples at fs readings per second, a wave of frequency f keeps this fraction of its height:

gain = | sin(π f w / fs) | / ( w · sin(π f / fs) ), so for f = 1.2 Hz and fs = 100: w = 21 keeps 90%, w = 41 keeps 65%, w = 81 keeps 3%.

The fix is a compromise. The bottom curve is the error against the truth. It falls while noise is the problem, bottoms out near a window of 15, then climbs as the smoothing destroys the pulse itself. Every processing step trades one error for another, and the best setting sits in the middle.

Think of it this way. Converting a signal is like cleaning a window. Extracting information is like reading the street through it. You clean until you can see, and not further, or you scrub off the paint.
You widen the averaging window from 15 to 81 samples. The line is smoother, but the beat count falls to zero. What went wrong?

Chapter 2

Samples: Turning a Wave into Numbers

Take x[n] = x(nT) apart, and find out when two different waves leave the same samples

Egypt, about 2500 BC. Every year the Nile floods, and the farmers along its banks need to know how high the water will rise. So someone carves a number into stone: this year the flood reached this height. Next year, another number. After a hundred years the stone holds a hundred numbers, one per year.

That stone is the earliest digital signal that the lecture shows. The river is a smooth, continuous thing: its level moves every minute. The stone keeps only one reading per year. Everything between the readings is gone, and the scribes were fine with that, because yearly readings were enough to plan a harvest.

Digital means countable

The word digital comes from digitus, the Latin word for finger. A digital signal is one you could count on your fingers: a list of separate values, taken one at a time. A discrete signal is the same idea, a list with gaps between the entries. An analog signal is the opposite: it has a value at every instant, with no gaps.

A computer can only keep lists. So to store a sound, it measures the sound at regular moments. Each measurement is a sample. The time between two samples is the sampling period T, and its inverse, 1/T, is the sampling rate fs: how many samples per second. The lecture writes the whole idea in one line.

x[n]
The discrete signal: a list, where n = 0, 1, 2, … counts the samples. Square brackets mean “a list indexed by whole numbers”.
x(·)
The continuous signal it came from, with round brackets: a function of time, defined at every instant.
nT
The time of sample number n, in seconds. Sample 0 is at time 0, sample 1 at T, sample 2 at 2T.

Speech at fs = 16,000 samples per second: T = 1/16,000 = 62.5 μs, and sample n = 8,000 sits at 8,000 × 62.5 μs = 0.5 s.

The lecture adds that a signal can also be discrete by nature. The Nile stone is close to that, and a movie rating is exactly that: there is no smooth rating between three stars and four. For these signals there is no x(t) to sample; the list is the signal.

Does sampling lose something?

Yes, and sometimes it loses everything that matters. Think of the Nile stone again: a flood that rises and falls twice in a year leaves one reading, and a reader of the stone cannot tell. Sampling too rarely does worse than lose detail. It creates a false story. Try it below with sound, where you can hear the false story.

Sample a tone, hear the ghost

Warm: the true wave, 5 milliseconds of it. Blue dots: the samples a computer keeps. Dashed red: a slower wave that passes through every dot. Pick a rate and a pitch, then press the buttons to hear the true tone and the ghost.

3,000 Hz

The tones are real: your browser plays a pure cosine at the pitch shown, then one at the ghost pitch the formula gives. Keep the volume low. Nothing here is toy except the 5 ms window, which is short so that you can see single samples.

Set 4,000 samples per second and 3,000 Hz. The true tone has a high pitch, but the dots follow a slower wave of 1,000 Hz. Play the ghost, and you hear a lower note. This is aliasing: two different waves that leave the same samples, so the samples cannot say which was real.

Why does it happen? Use a cosine, so that x(t) = cos(2π f t). Its samples are cos(2π f nT) = cos(2π f n / fs). Now add one full sampling rate to the frequency. The phase gains 2πn, a whole number of turns, and a whole number of turns changes nothing: cos(2π (f + fs) n / fs) = cos(2π f n / fs + 2π n) = cos(2π f n / fs). So f and f + fs leave identical samples. So do f − fs and all the other shifts by whole multiples of fs. Cosine is even, so the sign of the frequency does not matter either.

Worked check, f = 3,000 Hz, fs = 4,000: samples n = 0, 1, 2, 3, 4 give cos(1.5π n) = 1, 0, −1, 0, 1. The ghost f = 1,000 Hz gives cos(0.5π n) = 1, 0, −1, 0, 1. The two lists are identical.

The ghost is the frequency nearest zero among all the shifts: fghost = | f − fs × round(f / fs) |. A wave is safe from aliasing only if no shifted copy lands closer to zero than the wave itself. That holds when f is below half the sampling rate. This limit, fs/2, is the Nyquist frequency, and it is the rule behind every audio format: to keep a pitch, you must sample more than twice as fast as the pitch.

Here is the failure in the field. The symptom: a recording of a violin has a faint whistling note that the violin never played. The measurement: the sound contained energy above half the sampling rate, and sampling folded it down into the audible range. The fix: put a low-pass filter (a filter that blocks everything above a chosen frequency) in front of the sampler, so nothing above fs/2 reaches it. The lecture’s later lessons study filters, and the next lesson studies discrete signals as vectors.

A 6,000 Hz tone is sampled 8,000 times per second with no filter. What does the sample list look like?

Chapter 3

Everything Is an Array

Write sound, photos, text and ratings as arrays with a shape, and see what that shape promises

Think about four small things you did on your phone today. You recorded a voice memo. You took a photo. You sent a text message. You gave a film four stars. Four different kinds of thing, and your phone stores every one of them the same way: as numbers in a block of memory.

The lecture lists exactly these four as modern examples of digital signals. The useful question is not “what are they?” but “what shape of block holds each one?” The shape tells a program what it may assume. Nearby entries in one block are related, and nearby entries in another are strangers.

Four signals, four shapes

Audio. A microphone turns a pressure wave into a voltage, and the phone measures the voltage at regular instants. The result is a one-dimensional discrete-time signal: a list with one number per instant. One second of speech at 16,000 samples per second has the shape (16000,). A shape is the list of lengths along each direction of the block. Here there is one direction, and its length is 16,000.

Photos. The lens focuses light onto a grid of tiny light meters, called a CCD array. Each meter measures the light at one spot. The photo is a discrete-space signal in two dimensions: a number for each row and column. A grey photo has shape (H, W). A colour photo has three numbers per spot (red, green, blue), so its shape is (H, W, 3). A 12-megapixel phone photo is about (3024, 4032, 3).

Text. Each character gets a standard number. The lecture says 16 bits, which means a whole number from 0 to 65,535. The letter h is 104, e is 101 and y is 121. A message is these numbers stored in sequence, so a text of L characters has shape (L,).

Ratings. Books on Goodreads, films on Netflix and rentals on Airbnb get scores stored as the integers 0 to 5. One person’s ratings are a row, and a table of many people and many items is a block of shape (users, items). Unlike the others, most of this block is empty: nobody has rated everything.

Try each one. The device shows the actual numbers behind them and lets you change them.

Open the block

Choose a signal. Audio shows 32 samples as bars. A photo is an 8 by 8 grid: click a pixel to brighten it. Text turns your own words into numbers. In ratings, click a cell to set a score, and a blank means no rating.

Audio: 32 samples of a 440 Hz tone at 16,000 samples per second (illustrative). Photo: a made-up 8 by 8 face, brightness 0 to 255. Text: your browser’s own character numbers (UTF-16 code units, 16 bits each, as the lecture describes). Ratings: a made-up table of 5 people and 6 films, scores 1 to 5, blank for missing.

Look at the audio bars. Neighbouring samples are close in value, because air pressure cannot jump between two instants that are 62 microseconds apart. The same holds in the photo: a pixel usually looks like the pixels around it. This locality is what makes filters, edge detectors and the convolutional networks of Chapter 8 work. They all slide a small window along the block, and the window only helps if neighbours carry related values.

The idea of a sampling period carries over from Chapter 2 to space. A camera sensor samples light at positions a fixed distance apart, called the pixel pitch, the way a microphone samples pressure at times a fixed gap apart. A photo with too few pixels for its detail aliases in exactly the same way, which is why a striped shirt on a low-resolution camera sometimes shows wavy bands that the shirt never had. Time and space are two directions for one idea: measure at regular spots, and keep the spacing finer than the finest detail.

Now the text mode. The code for a is 97 and for b is 98, and for z it is 122. Does that mean b is close to a? No. These numbers are labels, not quantities. A program that treats character codes as a measurement, and computes distances between them, makes nonsense. The same goes for ratings, in a different way.

Here is a failure that catches many beginners. The symptom: a model trained on ratings predicts that every film is bad. The measurement: take one person who rated three films 5, 4 and 5, with seven films unrated. If you store the unrated ones as 0 and average the row, you get (5 + 4 + 5 + 0 × 7) / 10 = 1.4. If you average only the real ratings, you get 14 / 3 = 4.67. The fix: keep a second block of the same shape, a mask, that says which entries are real, and compute every average and every error over the real entries only.

Sizes: 1 s of speech = 16,000 × 2 bytes = 32,000 bytes. One 12-megapixel colour photo = 3,024 × 4,032 × 3 = 36.6 million bytes, before compression. 1,000 users who each rate 20 of 5,000 films fill 20,000 of 5,000,000 cells: 0.4%.

So before any learning, ask three questions about a signal. What is its shape? Are neighbouring entries related? Are the values quantities, labels or missing? The answers decide which tools make sense. The first lesson in the next stretch of the course, Discrete signals and vector spaces, turns each block into a point in a space with a distance, which is how later chapters compare signals.

The idea. To a learning machine, a signal is a block of numbers with a shape. The shape says where neighbours are, and the meaning of the numbers says what arithmetic is allowed.
A rating table stores unrated films as 0. Why does that bias a model toward low predictions?

Chapter 4

What Machine Learning Adds

Build a speaker identifier from a signal, one feature and a nearest-centre rule

You switch on the radio in the middle of a show, and a voice says three words. You know who it is. You could not tell anyone how you know. The voice is not louder or slower than a hundred others. Something in it is a signature, and your ear reads it faster than you can think.

That is the first reason the lecture gives for using machine learning: humans cannot always explain their expertise. If you cannot write the rule, you cannot code the rule. But you can collect many examples and let a program find the rule for itself.

Two definitions, one idea

The lecture gives two definitions. Arthur Samuel said in 1959 that machine learning is the field of study that gives computers the ability to learn without being explicitly programmed. Kevin Murphy wrote in 2012 that it is a set of algorithms that automatically detect patterns in data, and then use the patterns they find to predict future data or other outcomes of interest.

Put them together. A pattern is a regularity that repeats across examples, such as “this person’s voice has a low pitch and few high overtones”. Learning is finding the pattern from examples instead of from a programmer. Prediction is using the pattern on something new. The examples you learn from are the training set. The new thing, which the program has not seen, is the test case.

The lecture’s first full pipeline

Slides 18 and 19 show speaker identification as a diagram in two rows. In the top row, signals from speakers 1 to n flow into a box called feature extraction, which lists pitch and MFCCs (a set of numbers that describe the shape of a sound’s spectrum; a later lesson builds them). A feature is a number computed from the raw signal that is useful for the task. The features flow into model training, which produces a trained classifier, a program that maps features to a label. In the bottom row, an unknown speaker’s signal goes through the same feature extraction, and the classifier says “Speaker k”.

Notice the word same. The training row and the test row must use the identical feature extraction, or the numbers mean different things. Now build the pipeline yourself. The device makes three synthetic speakers. Each speaker has a base pitch and a different brightness, meaning how much energy sits in the high overtones. Press Record, and the machine finds the pitch and the brightness of the clip and decides who spoke.

Who is speaking?

Top: the last clip’s waveform (warm) and spectrum (purple). Below: each clip becomes one point, with pitch across and brightness up. Pink marks are the speakers’ centres, the average of their training clips. Your clip is the teal dot. Press Record, then switch to pitch only and score again.

8 clips

Synthetic voices made in your browser at 8,000 samples per second: a clip is 512 samples (64 ms), a stack of overtones of a base pitch (A 120 Hz and dark, B 135 Hz and bright, C 190 Hz and middle) that varies 10% between clips, plus noise. Pitch is the strongest peak of the spectrum between 70 and 300 Hz. Brightness is the spectrum’s centre of mass between 70 and 3,500 Hz, and noise lifts it. Each feature is divided by its spread across the training clips before distances are measured.

Here is how the classifier decides, with every step shown. Training finds each speaker’s centre: the mean of that speaker’s feature points. Say speaker A has a centre of (120 Hz, 840 Hz) and speaker B has (135 Hz, 1,220 Hz). Suppose the spreads are 20 Hz for pitch and 150 Hz for brightness. An unknown clip arrives with pitch 128 Hz and brightness 1,150 Hz.

Distance to A = √( ((128 − 120)/20)2 + ((1,150 − 840)/150)2 ) = √(0.16 + 4.27) = 2.10. Distance to B = √( ((128 − 135)/20)2 + ((1,150 − 1,220)/150)2 ) = √(0.12 + 0.22) = 0.58. The unknown clip is nearest to B, so the answer is speaker B.

Using pitch alone, the same clip is 8 Hz from A and 7 Hz from B. That is nearly a tie, and noise can flip it. Brightness settles the matter. Two features separate what one cannot, and the device shows it: with pitch alone the score is lower than with both.

Now the failure mode. The symptom: a classifier ignores a feature that clearly carries information. The measurement: pitch changes by tens of Hz between speakers, and brightness changes by hundreds, so without any correction the brightness distance is ten times larger and swamps pitch. That is why each feature is divided by its spread before the distance is taken. The fix: put every feature on a common scale, then measure.

When should you reach for learning?

Slide 20 lists three conditions. First, humans cannot explain their expertise, as with speech, vision and language. Second, the solution changes with time, as in tracking, noise cancellation and adaptive filtering. Third, the solution must be adapted to particular cases, as in biometrics and personalization. Outside those cases, a short fixed rule is usually cheaper and easier to trust. Inside them, the rule is too hard to write or will not stay right.

Think of it this way. Feature extraction is a translator. Raw samples speak a language of pressure and time. Features speak a language of pitch and brightness. A classifier is easy to build in the second language and nearly impossible in the first.
A new clip is nearly equidistant from two speakers by pitch alone. What is the best fix within this pipeline?

Chapter 5

Reading Brains and Bodies

Follow a wrist signal through windows, features and a verdict, with the shape of every step

A volunteer lies inside a large magnet and watches a film. The scanner cannot see thoughts. What it can do is send radio pulses into the head and listen to what comes back. Blood that carries more oxygen answers a little differently, and active brain regions draw more oxygen-rich blood. So the machine listens for oxygen, and the lecture’s slide calls this the sensitivity to blood oxygenation, a stand-in for the response of the brain to activity.

This is functional MRI (fMRI), and it shows both jobs of signal processing in one place. The first slide is labelled “convert from one signal to another”. What the scanner hears is a pile of radio measurements, not a picture. Signal processing turns that pile into an image of the brain with glowing patches, one per active region. Every patch is a function of position and time, which is a signal.

The second slide is labelled “interpretation of signals”. A research group at UC Berkeley (the Gallant lab) used fMRI for what the slide calls mind reading. The idea is to learn, from many examples, how a person’s brain responds to what they see. Then run the learning backward: given a new brain recording, work out what the person was looking at. The slide shows a movie the volunteer watched, and next to it a movie rebuilt from the brain recording alone.

Look at the two steps together. Step one is signal in, signal out, with no learning needed. Step two is signal in, fact out, and it needs learning, because no one can write down the rule that links a patch of oxygen change to a face on screen. You will meet this split again in every application of the course.

The same pipeline on your wrist

Slide 23 shows the same skeleton for a body instead of a brain: activity recognition. A device on the body, such as a phone or a watch, measures movement. The pipeline has four boxes in a row. The activity signal comes from the sensors. Feature extraction turns it into time-domain features (made from the samples directly) and frequency-domain features (made from the spectrum). Model training learns from labelled examples. Activity inference names the activity, such as walking or running.

It helps to see the shape of the data at each box, because the shapes are what a program actually passes along. A motion sensor, called an accelerometer, measures how fast the device speeds up or slows down along three directions. At 50 readings per second for 10.24 seconds, that gives 512 readings in each of 3 directions, a block of shape (512, 3).

A model cannot judge 10 seconds in one gulp, because the person may switch activity halfway. So the pipeline cuts the signal into short windows, which are overlapping slices of equal length. With a window of 128 readings that moves forward 64 readings at a time, the number of windows is (512 − 128) / 64 + 1 = 7. The block becomes (7, 128, 3). Each window then shrinks to a few features. Two work well here: how much the signal moves (its standard deviation, a number that measures spread) and its strongest frequency (the tallest bar of its spectrum). The block becomes (7, 2), and a classifier can handle that easily.

Step through it yourself. The device makes a wrist signal for one of three activities. Press Next step to move down the pipeline, and watch the shape change at each stage. Then raise the sensor noise and see what happens to a person who is sitting still.

From wrist to verdict

Pick an activity. Press Next step four times. In stage 3, the pink dashed lines are the cut-offs a programmer chose by hand. Then drag the noise up and walk through the stages again for sitting.

0.05

Toy signals made in your browser, not the lecture’s data: a 2 Hz bounce for walking and 3 Hz for running (each varies 8% by run), nothing but a little noise for sitting, and gravity of 1 on the z axis. The two features come from the combined size of the three axes. The rules are mine: below 0.15 movement means sitting, otherwise a strongest frequency under 2.5 Hz means walking, else running.

With low noise, the rules work for all three activities. Sitting moves by about 0.06, walking by 0.25 and running by 0.60, so the two cut-offs sit comfortably between them. Now raise the noise to 0.2 and look at sitting. The symptom: a person sitting still is labelled running. The measurement: noise adds its own movement of about 0.2 to the window, which is above the 0.15 cut-off, and its random spectrum has a tall bar at any frequency, often a high one. So the rule sees “moves a lot, fast”. The cut-offs were tuned to a quiet sensor.

The fix is the big idea of this course. Do not tune the cut-offs by hand for one sensor. Measure the features on many labelled windows, from many people and many noisy sensors, and let an algorithm place the cut-offs. That algorithm is the trained classifier of the last chapter. In the same spirit, a later chapter asks whether a neural network can learn the features as well, so that even the first two boxes need no hand-tuning.

The pattern behind every application. A raw signal comes in, a chain of conversions makes it smaller and clearer, and a decision comes out. The conversions are signal processing. The decision, when no one can write its rule, is machine learning.
Why does a hand-set movement cut-off of 0.15 fail when sensor noise rises to 0.2?

Chapter 6

Finding Faces with Sums of Rectangles

Compute a face feature in four lookups, and see why the 2001 detector could run in real time

Your phone camera draws a green box around every face in the frame, thirty times a second. Behind that box is a question asked again and again: is there a face in this little square of the picture? The camera asks it for squares at every position and at every size. A single frame can hold hundreds of thousands of squares. The answer for each one must take a few microseconds, or the box would lag behind your friends.

The lecture shows the 2001 method of Viola and Jones for this job, under the heading of computer vision, and then a video of it running in real time on a crowd. Their method is a masterclass in signal processing for learning. It finds a very cheap feature, and it computes that feature in a way that costs the same whether the square is small or large. Note that this is face detection, which finds where the faces are. Face recognition asks whose face it is, which is a different problem.

A feature made of light and dark

What do all faces share, whoever they belong to? Not colour or shape, but a pattern of light and dark. The eye region is darker than the cheeks below it. The bridge of the nose is brighter than the eyes on either side. The lecture’s slide shows small black and white rectangle patterns that capture such facts. Each is a rectangle feature: add up the pixel brightness inside the white rectangles, add up the pixel brightness inside the black rectangles, and subtract.

f
The value of one feature at one position and size. A large positive f means “the light part is much brighter than the dark part here”.
∑light
The total brightness of all pixels inside the light rectangles. The capital sigma means “add up”.
∑dark
The same for the dark rectangles. Subtracting makes f measure contrast, not overall brightness.

One such feature is a weak witness. Many cheek-like patches in a photo of a wall will also be lighter than the patch above them. But a few thousand witnesses, each placed at a particular spot with a particular threshold, agree only on real faces. Training chooses which features to trust. That choice is the machine learning half of the method. The count of candidates is large: in a 24 by 24 window, five shapes of rectangle feature at every position and size give 162,336 choices, on our count.

Four lookups, whatever the size

Here is the cost problem. A feature that covers a 14 by 6 patch needs 84 additions if you total the pixels directly. A detector needs thousands of features for each of hundreds of thousands of squares. The sums would take far too long. The trick is to do the adding once, for the whole image, and then reuse it.

Build the integral image. Its entry II(x, y) is the sum of all pixels above and to the left of position (x, y). It is made in one pass over the image: each entry is the pixel, plus the entry above it, plus the entry to its left, minus the entry diagonally above-left (which was counted twice). Now any rectangle sum needs just four numbers. Call the corners A (top left), B (top right), C (bottom left) and D (bottom right).

rectangle sum = II(D) − II(B) − II(C) + II(A)

Why does that work? II(D) holds the whole region from the image corner down to D. Subtract II(B), the strip above the rectangle, and II(C), the strip to its left. That removes the top-left block, A’s region, twice, so add II(A) back once. Try it on a tiny 3 by 3 image with rows (1, 2, 3), (4, 5, 6) and (7, 8, 9). The bottom-right 2 by 2 patch is 5 + 6 + 8 + 9 = 28. The integral image there reads II(D) = 45, II(B) = 6, II(C) = 12 and II(A) = 1. So the sum is 45 − 6 − 12 + 1 = 28, and it took four lookups.

Now the cost no longer depends on the size. A two-rectangle feature shares one edge between its rectangles, so it needs six lookups. A three-rectangle feature needs eight. The device below lets you place a feature on a made-up 24 by 24 face, and shows all of this at once.

Slide a feature over a face

Left: a made-up face. Blue rectangles are the dark part of the feature and warm ones the light part. Teal dots mark the corners A, B, C, D of the lookups. Right: the feature’s value at every position. Drag the position until your dot reaches the pink box. Then drag the lighting.

5
6
14
1.00

Made-up image: a bright oval, a dark eye band, a dark mouth and a little noise, brightness 0 to 255. The integral image is computed live in your browser, and every rectangle sum uses the four-lookup formula. Lighting multiplies every pixel. The spread is the standard deviation of all 576 pixels.

The best spot for the dark-over-light feature sits on the eyes: the dark eye band is on top and the bright cheeks are below. The map lights up there and nowhere else. This is what the detector does, thousands of times: slide a feature, read its value and compare it with a threshold.

Now the failure mode. The symptom: a face in a dim room is not found. The measurement: drag the lighting to 0.5. Every pixel halves, so the feature value halves too, and a threshold learned in bright light now rejects the face. The fix: normalise. Divide the feature by the spread of the pixels, which also halves, and the ratio stays the same. The 2001 paper does this with the variance of each window, which a second integral image (of squared pixels) delivers with the same four lookups. A feature that ignores overall light, and sees only contrast, is robust.

One more idea makes it fast enough for real time. The paper chains its classifiers in a cascade: the first stage uses a handful of features and throws away most squares that are clearly not faces, such as blank walls. Only the rare squares that survive are examined by later, costlier stages. Most squares cost almost nothing. A cheap feature, a four-lookup sum and an early exit together turn a hopeless search into a live video demo.

The idea. Do the expensive adding once, store it in the integral image, and then every rectangle costs four lookups. Cheap features let the learner try thousands of them.
Why can the integral image compute a rectangle sum in four lookups, even for a huge rectangle?

Chapter 7

Voices, Spectrograms and Microphone Arrays

Turn a sound into a picture of frequency over time, then use two microphones to find where it came from

You sit on the sofa, the television is on, and you say “Hey Google” to a speaker across the room. The speaker hears your voice, the television, a fan and the echo of your own words off the walls, all mixed into one stream of pressure. Slide 29 shows this exact scene. The device must pick your voice out of that mix, and then turn it into words.

The lecture groups three applications here. Speech recognition turns a voice signal into text: voice search, and transcription of a meeting. Speech synthesis, or text to speech, goes the other way, from text to a voice signal. The slide names the Baidu Deep Voice and Google Tacotron demos. Systems of the Tacotron kind first predict a spectrogram from the text, and then turn the spectrogram into a waveform. The spectrogram is the common middle, and the lecture’s next slide is about exactly that.

The spectrogram: a picture of a sound

Here is the problem. A single spectrum of a whole recording, which later lessons call the Fourier transform, tells you which frequencies were present. It cannot tell you when. Speech changes every few hundredths of a second: a vowel, a hiss, a click. So cut the signal into short, overlapping slices called windows, take the spectrum of each slice, and stand the spectra side by side as columns. The result is a spectrogram: time runs across, frequency runs up, and the brightness at each spot is the strength of that frequency at that moment.

S[k, m]
The brightness of the spectrogram at frequency row k and time column m: the strength of frequency k in window m.
N
The window length in samples. The sum runs over the N samples of one window.
mH
Where window m starts. H is the hop, the number of samples between the starts of neighbouring windows.
w[n]
The window shape: a smooth bump that fades the slice in and out, so that its cut edges do not add false frequencies.

The exponential at the end asks one question for each frequency k: how well does this slice match a sine wave of that frequency? A strong match makes a large sum. You do not need more than that now; the lesson on the DFT builds it, and the one on the STFT builds the whole spectrogram. Meanwhile, play with the window. The signal below is one second at 8,000 samples per second: a rising whistle, then two steady tones, with a sharp click near the end.

Choose the window

Brighter purple means a stronger frequency. Choose a window length and look at the rising whistle, the two tones (440 and 1,200 Hz) and the click at 0.75 s. Press Play to hear the sound.

The sound is made in your browser: a whistle rising from 300 to 2,300 Hz in the first half second, then 440 Hz and 1,200 Hz together, a click at 0.75 s and a little noise. The spectrograms are computed live with a Hann window and a hop of one quarter of the window, shown from 0 to 4,000 Hz on a 60 dB scale.

At 64 samples the window lasts 8 ms, which is short. The click is a sharp thin line, and you can say exactly when it happened. But the spectrum has a row only every 125 Hz, so the tones are fat bands and the whistle is a thick smear. At 1,024 samples the window lasts 128 ms. Now the tones are thin lines, but the click smears across 128 ms, and the whistle sweeps through many pitches inside one window.

This is the failure mode of every spectrogram. The symptom: the picture is sharp in one direction and blurred in the other. The measurement: the row spacing is fs/N hertz and the window lasts N/fs seconds, so their product is always 1. No window can win both. The fix is to choose by the question. For “when did it happen?” use a short window. For “which pitch?” use a long one. Speech systems commonly settle in between, near 25 milliseconds, and the wavelet lesson shows a transform that uses short windows for high frequencies and long ones for low frequencies.

Many microphones: array signal processing

Back to the sofa. Slides 29 to 31 show a speaker with several microphones, a block called multi-channel speech processing, and a second called multi-condition training. The array lets the device do something one microphone cannot: listen in a direction. Sound travels at about 343 metres per second. A voice at an angle reaches one microphone slightly before its neighbour. For two microphones a distance d apart, and a voice at angle θ from straight ahead, the delay is

τ = d sin(θ) / c. For d = 8 cm, θ = 20° and c = 343 m/s: τ = 0.08 × 0.342 / 343 = 79.8 μs, which is 3.8 samples at 48,000 samples per second.

That tiny delay is a fingerprint of direction. Delay-and-sum beamforming exploits it: delay each microphone’s signal so that sound from your chosen direction lines up, then add them. Sound from the chosen direction adds up in step. Sound from other directions arrives out of step and partly cancels. Try it. The pink region below shows how loudly each direction is heard when the array is aimed where the dashed line points.

Aim the array

The voice (V) is at 20° and the television (T) at −50°. Drag the aim to point the array at the voice, then add microphones. Then raise the pitch past 2,150 Hz and watch what the pattern does.

20°
1,500 Hz

Physics, not a recording: the pattern is the standard delay-and-sum gain of a straight line of microphones spaced 8 cm apart, for a single pure tone and sound arriving from far away (343 m/s). The voice and television positions are made up. Real rooms add echoes that this model leaves out.

With four microphones aimed at the voice at 1,500 Hz, the television still comes through at about −12 dB. With eight, it falls to about −28 dB, which is a much quieter source. More microphones make a narrower beam. Now raise the pitch past 2,150 Hz. Extra lobes appear and sound from the television’s direction may leak back in. This is Chapter 2 again, but in space: the microphones sample the sound field at positions 8 cm apart, and a wave shorter than twice the spacing is aliased. The array’s spacing sets the highest pitch that it can steer cleanly.

The last block, multi-condition training, closes the loop with learning. The recogniser behind the array is trained on audio recorded in many rooms and under many noise conditions, so that it has met television, fans and echoes before it meets yours. A signal-processing front end (the beam) plus a learned back end (the recogniser) is a pattern you will see again.

The idea. A spectrogram turns a sound into a picture, and a microphone array turns a room into a direction. Both are signal processing that makes the recogniser’s job easier, and both have a trade-off hidden inside.
You must find the exact moment of a door slam in a recording. Which spectrogram window is the better choice, and why?

Chapter 8

The First Neural Networks

Train a 1960 Adaline with its own error rule, then slide a small filter across an image the way a convolutional network does

1960, a university lab. On a bench sits a metal box with rows of switches and a dial. A person sets the switches to a pattern, say a rough letter, and the box lights a meter: yes or no. When it answers wrongly, the person tells it the right answer, and the box nudges its own internal knobs a little. After many nudges it answers correctly on its own. The lecture’s slides 33 and 34 show this machine and its two builders, Bernard Widrow and Ted Hoff.

They called it the Adaline, short for adaptive linear neuron. Slide 32 sets it on a timeline of neural networks that runs from the 1940s to the 2010s. The machine looks quaint, but its learning rule is the ancestor of the rule that trains today’s largest networks.

A neuron is a weighted vote

First, what is an artificial neuron? Take some inputs, such as the brightness of three pixels. Give each input a weight, a number that says how much that input matters, with a negative weight meaning “against”. Multiply and add them up: that is the neuron’s output y. If you only want a yes or no, call it yes when y is positive. Those knobs on the 1960 box were the weights.

y
The neuron’s output. Say yes (class +1) when y ≥ 0 and no (class −1) otherwise.
w0
The bias: a constant nudge that moves the yes/no boundary, like the starting position of a see-saw.
w1 x1 + w2 x2
Each input x times its weight w. Large positive w1 means “a big x1 pushes toward yes”.

Now the learning rule. Show the machine one example with inputs x and a correct answer d (+1 or −1). It computes its own y. The error is e = d − y. The goal is to make the squared error, E = ½(d − y)2, small. Slope tells you which way is downhill. Because y = w · x, the slope of E with respect to a weight wi is −(d − y) xi = −e xi. Step against the slope by a small rate η (eta):

wi ← wi
Replace the weight by itself plus a correction. The arrow means “becomes”.
η
The learning rate: how big a step to take. Small is slow and safe; large is fast and risky.
e
The error d − y. A bigger mistake gives a bigger correction, and the sign says which way to push.
xi
The input on that weight. An input that was zero gets no correction: it cannot be blamed.

Worked step: x = (1, 0.5, 0.45), d = +1, weights (0, 0, 0), η = 0.1. Then y = 0 and e = 1, so the weights become (0.10, 0.05, 0.045). The machine now says y = 0.1 + 0.025 + 0.02 = 0.145 for this input, which is closer to +1.

This is the Widrow-Hoff rule, also called LMS (least mean squares). Try it on 40 points from two groups. Each press of One step shows one sample, the error and the exact weight change.

Teach the Adaline

Circles are +1 and squares are −1. The pink line is where the Adaline’s output is 0. The teal ring is the sample it just learned from. Press One step a few times, then Run 40 steps. Then switch to the 2.0 rate.

Toy data made in your browser: 40 points from two fuzzy groups, labels ±1, weights start at 0. The update is exactly the rule above with the rate you pick, one sample per step. This is a linear unit: it can only separate groups that a straight line can split.

The line swings toward the groups and settles in a handful of passes. Now the failure mode. The symptom: with the 2.0 rate, the line spins wildly and the error chart climbs off the top. The measurement: each step overshoots, so the next error is larger than the last, and the weights grow without limit. The fix: shrink the rate. For this rule the step is safe only when η times the squared length of the input stays below 2, and with inputs this size 2.0 breaks it while 0.1 does not.

How the visual cortex inspired the filter

The lecture then turns to vision. Slide 35 shows the work of Hubel and Wiesel in 1968 on the visual cortex, area V1. Their finding: single cells there respond to a bar of light only when it has the right tilt and sits in a small patch of the visual field. Cells with similar tilts sit near each other, so the cortex forms an orderly map. The idea behind it is local detectors repeated over the whole visual field.

Slide 36 turns that idea into a network: a feature vector computed from small image patches by hidden units, and credits Fukushima (1980) and LeCun (1989). In a convolutional neural network a small grid of weights, called a filter, slides over the image. At each position the nine products (one per pixel under the filter) are added into one output number. The grid of outputs is a feature map. The key trick is that the same filter is used at every position, which is called weight sharing.

Slide the filter

The teal square marks where the filter sits. Choose an edge filter, then drag the position, or press Show the whole map. Blue marks a dark-to-light edge, pink the opposite.

24 of 100

Made-up 12 by 12 picture: a bright square and a bright stripe. The filters are the standard edge and blur examples (the lecture’s networks learn their filters from data instead). Output = the sum of the nine products at each position, no padding, so 10 by 10.

Watch the vertical-edge filter. In a flat region its nine products cancel to 0. At the left side of the square it sees dark then light, and it outputs a large positive value. At the right side it outputs a large negative value. The map is a picture of where vertical edges are. Change to the horizontal filter and the top and bottom edges appear instead.

Two gains follow. First, fewer weights: nine, instead of 14,400 if every output looked at every pixel. Second, the same detector everywhere: an edge is an edge wherever it sits in the picture. The 1960 rule still trains the weights, with one extra idea (backpropagation) to pass the error back through several layers. A later lesson builds the whole network, and the neural networks lesson and deep learning lesson carry it forward.

The idea. A neuron is a weighted vote that learns by stepping against its own error. A convolutional network makes that vote local and repeats it across the image, so it needs very few weights.
An Adaline’s error grows with every step. What is the most likely cause, and the fix?

Chapter 9

The Revolution of Depth, and the Activity Test

Compare classical features with learned ones on the same signals, and read the lecture’s four accuracies

Every year from 2010, research groups entered a contest. The task: look at a photo and say which of 1,000 kinds of thing it shows. A program gets five guesses, and counts as wrong only when the right label is missing from all five. That score is the top-5 error. The contest used the ImageNet collection of photos, and slide 37 plots the winning error for six years.

In 2010 and 2011 the winners were shallow methods: hand-built features followed by a simple classifier. In 2012 the winner was a convolutional network with 8 layers, and the curve dropped. Then the layers kept piling up. The slide labels the bars with the depth of each winner. Slide through the years.

Add the years, add the layers

Each bar is one winning entry: its error in per cent, and its depth in layers. Drag the slider to reveal the entries one at a time.

2015 ResNet

The seven numbers are read off the chart on slide 37 (the ImageNet challenge winners; the entry names AlexNet, ZFNet, VGG, GoogLeNet and ResNet are the ones the chart labels, and 152 layers is the label on the last bar). The “fewer mistakes” percentages are computed here from those numbers. Depth counts the layers the chart gives.

In five years the error fell from 28.2% to 3.57%, almost eightfold. Not every step came from depth alone, but the lecture names depth as the theme: the winning depth went from 8 layers in 2012 to 152 in 2015.

What deep learning changes

Slide 38 compares two styles of learning. In classical learning, an engineer designs the features, as in the face detector and the speaker identifier. This work is called feature engineering. In deep learning the features are learned by optimization: the same procedure that sets the weights also shapes the filters, so that no one has to say “look at the pitch”. The slide adds two claims. Deep learning scales much better with more data, and its accuracy now goes far beyond classical methods in speech processing, natural language processing, computer vision and reinforcement learning. The small graph on the slide is a sketch: the classical curve flattens as data grows, and the deep curve keeps rising.

The sketch is a claim to test, not a law. The lecture ends this chapter with a test.

Machines that sense and move

Slides 39 to 42 show where learned perception goes next. A self-driving car carries a GPS receiver, a camera, a laser scanner (LIDAR), radar, ultrasonic sensors, wheel encoders and a short-range radio link between vehicles. Each sensor is a signal with its own sampling rate and its own noise, and a car must fuse them all. The slides then show autonomous helicopter control, a rover that perceives and navigates, and a small drone that builds a 3D map of a room while labelling each surface as floor, wall or furniture. Every one of these runs on the ideas you have seen: samples, features, and a learned decision.

The activity test

Slides 43 to 46 run the lecture’s own head-to-head test of classical and deep methods on signals. The task is human activity recognition from smartphone motion sensors, using the dataset of Reyes-Ortiz and colleagues from 2012. Windows of sensor readings x1[n], x2[n], … are labelled with what the person was doing. The people are split: some train the classifier, and different people test it. That split matters: a model that has seen your walk scores higher than one that meets a new walker.

Four methods compete. First, 3-nearest-neighbours on the raw samples x[n], with the straight-line distance between two windows: 77%. Second, the same 3-nearest-neighbours on the magnitude of the Fourier transform, |X[k]|: 85%. Third, a 1D convolutional network with 4 layers: 91%. Fourth, wavelet-transform features (entropy, zero crossings and simple statistics) with a linear classifier: 95%. Pick each below.

Climb the ladder

The bars are the lecture’s four accuracies. Choose a method to see what it reads, what model it uses, and who chose the features.

Numbers from slides 45 and 46 of the lecture (a smartphone activity dataset, Reyes-Ortiz et al., 2012; test users unseen in training). The bar axis starts at 50%, so bar lengths exaggerate the gaps. The one-line explanations of why each method does better are mine, and the slide does not test them.

Read the ladder from the bottom. The first step, 77 to 85, changes only the list of numbers. Same classifier, same data, but the Fourier magnitude ignores where in its stride the window starts. This is exactly the hero at the top of this page: shift the start, and raw samples fail while the spectrum holds. Eight points came from signal processing, with no new learning.

The second step, 85 to 91, hands the features to the machine. A network with four layers learns its own filters from the labelled windows, and it beats both hand-fed methods. That supports slide 38: no one told it to take a Fourier transform.

The third step is the surprise. A person chose wavelet statistics, a classical recipe, and the simplest classifier, a straight-line boundary, and that scored 95%, four points above the network. One plausible reason, which the slide does not claim, is data size. A 4-layer network has many weights to learn, and this dataset has limited labelled windows. Wavelet features already encode useful structure, so a linear model has little left to learn. With more data the sketch on slide 38 says the network would catch up.

So the lecture’s later question, when does a deep network beat a classical model?, has a data-dependent answer. The failure mode of each style is the mirror of the other. Classical methods fail when the engineer picks the wrong features. Deep methods fail when the data cannot pay for all the weights. Neither is a free lunch, and the best practitioners know both toolboxes. That is why this course teaches both.

The idea. The same signals, read four ways, scored 77, 85, 91 and 95 per cent. What improved was not the data but the representation, whether a person or a machine chose it.
In the lecture’s activity test, the raw-sample 3-NN scored 77% and the spectrum 3-NN scored 85%. What changed between them?

Chapter 10

The Course Map and the Questions Behind It

Walk the ten topics, then roll a ball down a convex and a non-convex curve to see why training is hard

Slides 47 to 56 build one list, one line at a time. It is the table of contents of the course, and it reads like a journey. You start with the mathematics of signals as points in a space. You learn to see frequencies. You learn to classify, to fit models, to find building blocks in data, and to look at several scales at once. Then neural networks arrive, and then the networks that adapt, and finally the deep ones. Pick a topic below to see what question it answers, where this page touched it and which lesson comes next.

Walk the map

Ten circles, one per topic, in the order of slides 47 to 56. Choose one to read its question and open its lesson.

The ten topics are the lecture’s own list. The questions and the pointers to chapters and lessons are my own summaries. The lessons are re-teachings of the course’s later lectures, linked here so that you can jump ahead.

Slide 57 then asks seven questions that the course explores. How do you find the best signal representation for machine learning? How do you find the best classifier? Is feature engineering necessary? Can a neural network find good features by itself? Can we replace domain knowledge with a network and data? When does a deep network beat a classical model? How can we understand what a network has learned? You have already met three of these. Chapter 4 showed that a feature can decide a result. Chapter 9 showed a classical method beating a network, and a network beating two classical ones. The rest you will carry into the course.

Why training a neural network is hard

Slides 58 and 59 pose one more puzzle, under a photo of a baby studying a book called Neural Networks for Babies: how do neural networks work? The answer starts with a contrast. Many classical models, such as least squares and support vector machines, give a training problem that is convex. Training a neural network gives a non-convex problem, which the slide calls challenging to train and hard to interpret.

Picture the training problem as a landscape, where height is the loss (how wrong the model is) and your position is the set of weights. You always walk downhill, one small step at a time. This is gradient descent. On a convex landscape there is one valley, so every walk ends at the bottom. On a non-convex landscape there are many valleys, and where you end depends on where you began. The precise test of convexity is this:

f(λa + (1 − λ)b)
The curve’s height at a point between a and b. The number λ between 0 and 1 says how far along: 0.5 is halfway.
λ f(a) + (1 − λ) f(b)
The height of the straight chord that joins the curve at a and at b, at the same spot.

In words: the curve never rises above any chord. Take f(x) = x2, with a = −1 and b = 3, halfway. The curve gives f(1) = 1, and the chord gives 0.5 × 1 + 0.5 × 9 = 5, so 1 ≤ 5 and the test passes. Now take f(x) = (x2 − 1)2 with a = −1 and b = 1. The curve gives f(0) = 1, and the chord gives 0.5 × 0 + 0.5 × 0 = 0. Here 1 ≤ 0 is false. The curve pokes above the chord, which makes a hill between two valleys. Try both curves below.

Roll the ball

The warm curve is the loss, and the green dot is its best point. Choose a curve, drag the start, then press Roll the ball. Then press Drop 20 balls to try twenty starts at once.

1.4

Two toy curves in one variable: x2 + 0.3x (convex) and (x2 − 1)2 + 0.3x (non-convex, best point near −1.04, a worse valley near 0.96). Plain gradient descent with step 0.02 and 400 steps, run exactly in your browser. Real networks have millions of weights, not one, but the trap is the same.

On the convex curve, every start ends at the bottom. On the non-convex curve, about half of them do. A ball started at 1.4 slides into the right-hand valley and stays there, with loss 0.29 where −0.31 was possible. The symptom: the same network, trained twice from two random starts, gives two different scores. The measurement: the training loss stops falling, but it stops at different heights. Gradient descent cannot see the other valley, because from where it stands, every direction is uphill.

The fixes are partial. You can restart from many random places and keep the best. You can use tricks such as momentum that carry you over small hills. And the lecture’s last claim, on slide 59, is the striking one: neural networks can be written as convex optimization problems in higher dimensions. If that holds, the trap disappears, and the answers become interpretable. The instructor’s own research is the source of that claim, and a later lesson teaches it.

The projects

The last slides show eight projects from earlier years, and each reuses a pattern from this page. Clustering the daily power curves of solar panels uses features and clustering. Tracking objects in video uses an SVD filter, a matrix method that the course reaches under adaptive bases (topic 6). Emotion detection from faces is Chapter 6’s detection with learning on top. Composer classification from classical music works on the spectrogram of Chapter 7. Predicting epileptic seizures from brain recordings compares Fourier spectra and projects the data onto two principal components. Tracking when crops are planted uses satellite images over time. Estimating the direction of a sound from the phase difference between two microphones is Chapter 7’s array. Estimating the flight state of an unmanned aircraft reads sensors on the aircraft and turns them into a state, which is Chapter 1’s second job. Every one of the eight starts with the same question that has run through this page: given a signal, what is it telling us?

The idea. Most classical methods give landscapes with one valley, so training always works. Neural networks give landscapes with many valleys, so training depends on the start. The course teaches both worlds, and one route that turns the second into the first.
Why does gradient descent always find the best point on a convex curve, but not on a non-convex one?

Chapter 11

Field Guide

Keep the numbers, the terms, a checklist and the core code on one page

Here is the whole lecture in one paragraph. A signal is a function, and a computer keeps it as a list of samples, x[n] = x(nT). Sound, photos, text and ratings are all blocks of numbers with a shape. Machine learning finds patterns in those numbers, but how you write the numbers decides what it can find: a spectrum beat raw samples, a learned filter beat both, and hand-made wavelet features beat a small network. Applications from brain scans to self-driving cars follow the same chain, from signal to features to decision. Training is easy when the loss is convex and fragile when it is not.

The numbers

QuantityValueWhere it comes from
Samplingx[n] = x(nT); keep f below fs/2Slide 12; Chapter 2
Aliasing example3,000 Hz sampled at 4,000 /s looks like 1,000 HzOur worked example; Chapter 2
Machine learningSamuel 1959; Murphy 2012Slides 16 and 17
AdalineWidrow and Hoff, 1960Slide 33
Orientation-selective cellsHubel and Wiesel, 1968Slide 35
Convolutional networksFukushima 1980; LeCun 1989Slide 36
Face detectorViola and Jones, 2001Slides 24 to 26
Rectangle features, 24 by 24162,336Our count of five shapes; Chapter 6
Integral imageAny rectangle sum in 4 lookupsChapter 6
Spectrogram trade-off(blur in Hz) × (blur in s) = 1Chapter 7
ImageNet top-5 error28.2% in 2010 to 3.57% in 2015; 152 layersSlide 37 chart
Activity test accuracy77, 85, 91, 95 per centSlides 45 and 46
Course gradingHomework 60%, project 40%, Piazza 5% extraSlide 7

The terms

TermPlain meaningChapter
SignalA function: a number for each time or position.1
SampleOne measurement taken at a regular instant.2
AliasingTwo different waves that leave the same samples.2
ShapeThe lengths of a block of numbers in each direction.3
FeatureA number computed from a signal that helps the task.4
ClassifierA program that maps features to a label.4
WindowA short slice of a signal, cut so it can be analysed alone.5
Integral imageA table of running sums that makes every rectangle sum cheap.6
SpectrogramFrequency over time, one spectrum per window.7
BeamformingDelaying and adding microphone signals to listen in one direction.7
Adaline, LMSA linear neuron that learns by stepping against its own error.8
Filter, feature mapA small weight grid slid over an image, and the grid of results.8
Top-5 errorThe share of photos whose right label is not in five guesses.9
ConvexA loss with one valley, so every downhill walk finds the bottom.10

Before you train anything

  1. Name the shape. Is it (T,), (H, W), (L,) or (users, items)? Are neighbours related?
  2. Check the rate. Is the sampling rate above twice the highest frequency you care about? If not, filter before you sample.
  3. Check what the numbers mean. Are they quantities, labels or missing values? Keep a mask for the missing ones.
  4. Pick a representation on purpose. Raw samples, a spectrum, a spectrogram or a wavelet? Ask which change in the signal must not change the answer.
  5. Scale the features. Put every feature on a common scale before you measure distances.
  6. Split by people, not by windows. Test on users the model has never seen.
  7. Run a simple baseline first. A 3-nearest-neighbour or a linear model may already win.
  8. Then ask whether depth pays. A network needs data to pay for its weights.

The core as code

Four short pieces carry the lecture: sampling and aliasing, a classifier on two representations, the Adaline rule, and the integral image. Run it with numpy. The exact scores change with the random seed.

pythonimport numpy as np

# 1. Sampling: x[n] = x(nT). A 3,000 Hz cosine sampled at 4,000 /s is a 1,000 Hz ghost.  (Chapter 2)
fs, f = 4000, 3000
n = np.arange(8)
x = np.cos(2 * np.pi * f * n / fs)
ghost = np.cos(2 * np.pi * (f - fs) * n / fs)
assert np.allclose(x, ghost)                     # identical samples

# 2. Features: raw samples vs magnitude spectrum, same 3-NN classifier.  (Chapters 4 and 9)
def make(cycles, phase, noise, rng, N=64):
    t = np.arange(N)
    return np.sin(2 * np.pi * cycles * t / N + phase) + noise * rng.standard_normal(N)

def spectrum(x):                                  # shape (N,) -> (N // 2 + 1,)
    return np.abs(np.fft.rfft(x)) * 2 / len(x)

def knn(train_X, train_y, q, k=3):
    d = np.linalg.norm(train_X - q, axis=1)       # straight-line distance
    return np.bincount(train_y[np.argsort(d)[:k]]).argmax()

rng = np.random.default_rng(0)
cycles = [1, 3, 5]                                # sitting, walking, running (toy)
amp = [0.12, 1.0, 1.0]
def sample(c, noise):
    return amp[c] * make(cycles[c], rng.uniform(0, 2 * np.pi), 0, rng) + noise * rng.standard_normal(64)

train_y = np.repeat([0, 1, 2], 5)
train_X = np.array([sample(c, 0.3) for c in train_y])
train_S = np.array([spectrum(x) for x in train_X])
test_y = np.repeat([0, 1, 2], 30)
test_X = np.array([sample(c, 0.3) for c in test_y])
raw = np.mean([knn(train_X, train_y, q) == y for q, y in zip(test_X, test_y)])
spec = np.mean([knn(train_S, train_y, spectrum(q)) == y for q, y in zip(test_X, test_y)])
print(f"raw 3-NN {raw:.0%}, spectrum 3-NN {spec:.0%}")

# 3. Adaline: w <- w + eta * (d - w.x) * x.  (Chapter 8)
def lms(X, d, eta=0.1, passes=5):
    w = np.zeros(X.shape[1])
    for _ in range(passes):
        for x_i, t in zip(X, d):
            w += eta * (t - w @ x_i) * x_i
    return w

# 4. Integral image: any rectangle sum in four lookups.  (Chapter 6)
def integral(img):
    return np.pad(img.cumsum(0).cumsum(1), ((1, 0), (1, 0)))

def rect(II, x, y, w, h):
    return II[y + h, x + w] - II[y, x + w] - II[y + h, x] + II[y, x]

img = np.arange(1, 10).reshape(3, 3)
print(rect(integral(img), 1, 1, 2, 2))           # 5 + 6 + 8 + 9 = 28

The first assertion proves the aliasing identity from Chapter 2. The printed line reproduces the hero in text form: raw samples land far below the spectrum, here 67% against 100% on this seed. The last line prints 28, the worked rectangle sum from Chapter 6.

Where it sits in the field

This lecture is the front door of EE269. The classical half of the course (Fourier, spectrograms, wavelets, classifiers, least squares) comes from signal processing and statistics. The learned half (neural networks, convolution, depth) comes from machine learning. The open questions of slide 57 live where the two halves meet.

Keep going

The takeaway. A learning machine reads numbers, not signals. Signal processing decides which numbers it reads. When the representation fits the problem, even the simplest classifier works, and when it does not, no amount of data saves you.

Credit: this lesson re-teaches Lecture 1 of Stanford EE269, Signal Processing for Machine Learning (Fall 2020), taught by Mert Pilanci with course assistant Tolga Ergen. We wrote every explanation and built every device ourselves, and we use the lecture only for its order and its facts. The lecture credits the makers of its figures on the slides themselves; please see the slides for them. Nothing here is endorsed by the course.

Now press Present or Teach and explain the activity test out loud, from memory: why the spectrum beat the raw samples, what the network learned for itself, and why hand-made features still won. Then go back to the instrument at the top, shift the start of the cycle to 180 degrees, and explain why the raw samples fail and the spectrum holds.

EE269 Lecture 1: Introduction, re-taught
Course site · Lecture 1 slides · Back to Gleams