Expectation and Emotion
Why does music move us, and how much of that can expectation, measured in bits, explain?
In 2011 Salimpoor and colleagues caught dopamine released twice, at a musical chill and in the seconds of anticipation before it; Meyer had argued in 1956 that musical emotion is expectation delayed and fulfilled. The part builds a listener: a variable-order Markov model blended by prediction by partial matching, in the manner of Pearce's IDyOM, trained on the series' 51 major-key tunes and listening to each with a short-term model that learns the piece. It measures surprise (information content) and uncertainty (entropy) note by note: the Tune costs 1.98 bits a note, random scale notes 3.93; Part 42's kept draft 3.1 against a rejected draft's 3.8; probe tones rank C, D, F sharp as listeners do. Expectation is learned (a Saffran-style stream of tone words, heard and tested); repetition teaches it (a leap costs 4.8 bits, then 2.1); delay makes an ending more certain (the deceptive turn costs 6.3 bits and the final C only 0.9, against 1.2 undelayed); denial leaves the cost unpaid (F sharp, 10.9 bits, falling to 2.2 when repeated). It covers the ERAN and reward, Cheung's interaction of surprise and uncertainty, groove's inverted U and syncopation, the cues of expressed emotion (a quiz in four settings), chills, sad music, memory, and what does not replicate.
What you need. Part 14 for melody and the corpus; Part 15 for key and probe tones; Part 18 for cadences; Part 21 for form; Part 38 for syncopation; Part 42 for tension and the searcher; Part 45 for grouping. Entropy, Markov models.
- Ideas, mathematics and history
- Meyer, statistical learning, surprise and uncertainty, chills, tension, groove's inverted U
- What we build, compute and hear
- a listener model; three endings: expected, delayed, denied
What you will be able to do
Foundations
- Hear expected, delayed and denied endings, a suspension and a Neapolitan, and say what each does.
- Learn tone 'words' from a stream, and rank probe tones by fit.
- Hear the cues of four expressed emotions, and four grooves of rising syncopation.
Full course
- Build a PPM listener with long- and short-term models, and compute surprise and uncertainty per note.
- Compute transitional probabilities in a stream and a syncopation index for a pattern.
- Compare melodies by mean surprise, and engineer endings by their cost in bits.
Research
- Design a study measuring how much of moment-to-moment pleasure surprise and uncertainty predict.
Practice
- Build and delay expectations in songs and scores; choose music for its cues with measured effects.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Foundations 22 min · Full course 31 min · Research 33 min · Practice 31 min.
- 0Wanting, then gettingFoundations2 min
- 1ExpectationFoundations3 min
- 2Statistical learningFoundations3 min
- 3A listener modelPractice4 min
- 4Surprise across melodiesPractice2 min
- 5Three endingsFoundations3 min
- 6The brain at a wrong chordFoundations2 min
- 7Surprise and uncertainty togetherPractice3 min
- 8GrooveFoundations3 min
- 9Expressed emotionFoundations5 min
- 10Frontier: the predicting brainResearch2 min
- Variation 46, recap and problemsAll tracks2 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.
Wanting, then gettingFoundations2 min
In 1956 Leonard Meyer argued that musical emotion is expectation, delayed and fulfilled. Test your own expectations first. The Tune's last phrase, three times, each with a different last note. A model listener, trained on fifty other tunes, heard them too. Which ending surprised it most, and which least?
Most surprising: the third, ending on F sharp, at bits. Least: the second, the real ending on C, at . The first, on A, sat between, at . A bit is a yes-or-no question: the scores describe minus log probabilities, not literal counts of guesses or exact code lengths for each note. This part is about those numbers, and why they might have anything to do with feeling.
In 2011 Valorie Salimpoor and colleagues asked listeners to bring music that gave them chills. PET provided evidence of striatal dopamine release during intensely pleasurable music, while fMRI distinguished anticipatory and peak-related activity. Anticipation was associated more with caudate activity, and peak pleasure with nucleus accumbens activity; these methods do not directly time two separate dopamine pulses. Pleasure in music has a phase of wanting before a phase of getting. Leonard Meyer had argued as much in 1956: musical emotion is expectation, delayed and fulfilled.
Here is the plan. Meyer, Huron, and expectation as prediction. Statistical learning: how expectations are acquired. A listener model that measures surprise and uncertainty note by note. Three endings for the Tune: expected, delayed and denied. The brain, groove, and the cues of expressed emotion. And sad music, preference, and what does not replicate.
1ExpectationFoundations3 min
Where does musical feeling come from?
The question is old. In 1854 Eduard Hanslick argued that music's content is tonally moving forms, and nothing more. Against him stood expression theories: music represents or arouses feelings. The debate ran for a century without a way to measure either side. Meyer joined the two: feeling arises from the forms themselves, through expectation, a claim about forms that could, in time, be tested.
The modern story starts with Leonard Meyer's book Emotion and Meaning in Music, of 1956. His claim: emotion arises when a tendency to respond is delayed or blocked. Music builds tendencies, a leading note, a dominant chord, and then plays with them. Its meaning lies in the relation between what is heard and what is expected next. It was a theory waiting for a way to measure expectation.
David Huron's book Sweet Anticipation, of 2006, splits expectation into five responses around an event. Before it: imagination, picturing outcomes, and tension, arousal rising as the moment nears. At it: prediction, whether it was foreseen, and reaction, a fast, crude response. After it: appraisal, a slower judgement. Huron's key point: the prediction response rewards accurate prediction itself, so even a foreseen sad cadence can feel good, and a surprise can be reappraised from alarm into delight.
Huron also separates three kinds of expectation. Schematic: what a style has taught you, that a dominant goes to the tonic. Veridical: what you know of this particular piece, the next note of a tune you know. Dynamic: what the piece so far has taught you, so a motive heard twice is expected a third time. They can disagree: a deceptive cadence still surprises the schema even when you know the piece by heart. Chapter two asks where schemas come from.
Dynamic expectation, heard. A motive of ours, three times, and then a fourth time with its leap changed.
The listener's surprise at the leap: bits the first time, and once the piece has taught it, and when the fourth leap goes somewhere new. The piece itself built the expectation it then broke.
Expectation does not explain everything. There is timbre, a voice, the words, and the memories attached to a song. And a piece can move us on its hundredth hearing, when nothing in it can surprise us. Meyer's answer, and Huron's, is that schematic expectation is never fully overwritten by knowing the piece. Chapter nine meets the other mechanisms: reflexes, contagion, memory. Expectation is one engine among several, but the best measured.
2Statistical learningFoundations3 min
How do expectations get into a listener?
Expectations are learned, and the learning is statistical. In 1996 Jenny Saffran and colleagues played eight-month-old infants two minutes of a continuous stream of syllables, made of nonsense words with no pauses, so only the transitional probabilities from one syllable to the next marked where words began. Afterwards the infants told words from part-words. In 1999 the same was shown with tones, for infants and adults. Expectation is learned by counting, without trying.
Try it. A stream of tones with no pauses, about twenty seconds of it. Then two groups of three tones. One of them was a word that kept recurring in the stream; the other was not. Which was the word?
The second. The stream was made of four three-tone words, coloured now, in random order. Inside a word the next tone was certain; across a boundary it was one of three. The first triplet straddled a boundary, and most listeners find it less familiar, without being able to say why.
Krumhansl and Shepard measured such learning with probe tones: play a context, then one note, and ask how well it fits. Here, the Tune's first phrase three times, followed by D, by C, and by F sharp.
Listeners rate C as fitting best, then D, and F sharp worst; our listener's surprise ranks them the same way: , and bits. Fit and predictability can correlate but are distinct judgments; this toy ranking is not a new listener experiment.
A lifetime of such counting builds a listener. It builds a sense of key: Carol Krumhansl's probe-tone profiles track how often notes occur, as Part 15 showed. Listeners without training expect a tonic after a dominant, and respond to a wrong chord; Emmanuel Bigand and Bénédicte Poulin-Charronnat argued in 2006 that non-musicians' implicit knowledge of harmony nearly matches musicians'. A style is a statistical environment, and expectations are its fingerprints in the listener. Chapter three builds a listener the same way.
Children show the learning happening. Infants hear contour and rhythm from the start, but key and harmony take years of exposure. Laurel Trainor and Sandra Trehub found in 1994 that by about the age of seven, children notice a changed note that leaves the key more readily than one that stays in it. Preference for consonance, and for endings on the tonic, grows through childhood. The schemas of chapter one are built slowly, from the music a child hears. Part 47 asks which parts need no learning at all.
3A listener modelPractice4 min
Can a program be surprised?
Our listener counts symbolic transitions; this is an analogy to statistical learning, not a complete model of an infant's learning. In the corpus, it counts which note followed every context of up to four notes. To predict, it uses the longest context it has seen before, keeps some probability back for the unseen, and passes that down to shorter contexts. This is prediction by partial matching, the method behind Marcus Pearce's model IDyOM. A long-term model knows the style; a short-term model learns the piece as it goes; the more certain of the two counts for more. Our corpus is the series' fifty-one major-key tunes from Part 14, and each tune is heard by a model trained on all the others.
It gives two numbers for every note. Surprise, or information content: minus the logarithm, base two, of the probability the model gave the note that came, in bits. A certain note costs nothing; a one-in-two note one bit; a one-in-a-thousand note about ten. Uncertainty, or entropy: the surprise the model expects before the note arrives. Surprise is about what happened; uncertainty about what might. Pearce and colleagues found information content predicts listeners' ratings of how expected each note was.
Pearce's full model is richer than ours. A melody can be predicted in more than one representation: pitch, interval, contour, scale degree, duration. IDyOM runs a model for each such viewpoint and combines them, weighting the more certain. Ours uses pitch relative to the tonic only, with a long-term and a short-term model. Richer viewpoints predict listeners better; ours is enough to show the shape of the idea. Darrell Conklin and Ian Witten introduced multiple viewpoints for music in 1995.
Here is the Tune through the listener's ears: surprise above, uncertainty below, one bar per note, while the Tune plays. Watch where the bars rise.
The biggest surprise of the first phrase is the leap up to G, bits. Over the piece, surprise falls, from about bits a note in the first phrase to in the last: the short-term model has learned the piece, so the returning phrases cost little. The Tune averages bits a note: predictable under this small corpus model; that does not establish why children learn it.
A model that predicts can also generate. Let the listener sing: start on C, and draw each next note from its own prediction.
It sounds like a folk tune that wanders: every step is plausible, and the phrase has no plan. That is what a listener without a sense of form produces, and Part 65 will ask what more a composing machine needs.
Now every note of all tunes, each tune heard by a model trained on the rest. Across, the uncertainty before the note; up, the surprise when it came. Most notes sit low: folk tunes average bits. Where the model is uncertain, bigger surprises are possible, but the correlation is only : the two numbers measure different things, and chapter seven shows why that matters.
4Surprise across melodiesPractice2 min
Is good music predictable or surprising?
Point the listener at other melodies. The Tune and the Ode to Joy cost about two bits a note. Part 42's searcher kept a draft that cost bits, and threw away one that cost : its critics, without being told to, preferred the more predictable. Its chain of order four, which copied whole phrases, costs about the same as a real folk tune; order one costs much more; and random notes of the scale cost most of all.
Hear the two drafts, melody alone: the rejected one first, then the kept one.
The rejected draft lurches; the kept one moves by step and sequence. The critics knew nothing of this listener, but they encoded the same style, so they chose the draft the listener finds more predictable.
And the two ends of the scale: random notes of the scale, then Part 42's chain of order four.
Random notes never let an expectation form; the chain borrows a folk tune's whole shape. These sketches illustrate a proposed complexity trade-off; they do not establish what all listeners value.
Does such a model hear as we do? Pearce and colleagues showed in 2010 that high-information notes evoke larger brain responses and lower ratings of expectedness. The model's surprise also predicts where listeners hear phrase boundaries, after a run of predictable notes, at a surprise. And models trained on one culture's music predict that culture's listeners better than another's. Expectation is real, measurable, and learned from exposure. But is predictable music good, or surprising music?
The classic answer is: neither, but in between. Daniel Berlyne proposed in 1971 that liking rises and then falls with complexity, an inverted U: too predictable is boring, too surprising is noise. The peak moves with familiarity: the more you know a style, the more complexity you enjoy. And mere exposure raises liking, up to a point. Chapter five uses surprise on purpose, in three endings.
5Three endingsFoundations3 min
What does delay do to an ending?
Here are the three endings this part will give the Tune. Expected: down to C over the tonic. Delayed: down to A over A minor, the deceptive turn, then round again to C. Denied: up to F sharp over D, and stop.
The listener's surprise for each note. Expected: the last C costs bits. Delayed: the deceptive A costs bits, a real jolt; but when C finally comes it costs only , less than in the plain ending. Delay made the resolution more certain, and arguably more satisfying: Meyer's point, in numbers. Denied: F sharp costs bits, and nothing comes after to repair it.
What if the denial is repeated? Hear the denied ending three times running. The listener's surprise at F sharp falls from bits to and then : the short-term model learns the piece's own rule. Repeat a surprise and it becomes a feature of the style, which is how many musical languages grow.
Huron also asked listeners to describe how each scale degree feels at the end of a phrase. The tonic: stable, home, finished. The fifth: strong, but open. The leading note: unstable, yearning, pointing upward. The raised fourth: strange, lifting. The feelings track the statistics: the more reliably a degree is followed by one particular note, the more it seems to lean towards it. These are Meyer's tendencies, and Part 15's, heard as qualities.
Composers have many devices of delay. The deceptive cadence, five to six instead of five to one, from Part 18. The suspension and the appoggiatura, where the right note arrives late, after a dissonance, from Part 16. The long dominant pedal before a recapitulation, Part 21's: wanting, prolonged. And the build and drop of dance music, Part 40's, the same device engineered. Chapter six asks what the brain does at a wrong chord.
Here is the smallest delay of all. A plain cadence; then the same with a suspension, the C held over from the previous chord into the dominant, clashing, before it falls to B.
One held note, one beat of wanting, and the cadence lands harder.
6The brain at a wrong chordFoundations2 min
Does the brain parse harmony like grammar?
What does the brain do at a wrong chord? In 2000 Stefan Koelsch and colleagues played chord sequences ending either on the tonic or on a Neapolitan sixth. The unexpected chord evoked a brain response about two hundred milliseconds later, the early right anterior negativity, in non-musicians too, and its size tracks how improbable the chord is in the style. The brain predicts chords automatically, even while attending to something else. It is Part 19's Neapolitan, seen in an EEG.
Hear a sequence like Koelsch's: five chords ending on the tonic, then the same ending on a Neapolitan sixth.
The last chord of the second sequence is in tune and consonant; only its place is wrong. That is enough for the brain to flag it within a fifth of a second.
Is this like grammar? In 1998 Aniruddh Patel and colleagues found that out-of-key chords and ungrammatical words evoke similar late brain responses. Patel proposed that music and language share resources for integrating structure, but not the structures themselves. Some studies find interference: a harmonic surprise slows the reading of a difficult sentence. The overlap is real but partial: amusia and aphasia can each occur without the other. Part 47 returns to music and language.
Prediction goes deeper than harmony. The mismatch negativity is a brain response to a deviant sound in a regular sequence, about a hundred and fifty milliseconds after it. It appears without attention, even in sleep and in newborns. Musicians show larger mismatch responses to small deviations of pitch and timing. Prediction runs automatically, at every level from the brainstem to harmony: Part 4's ear, predicting.
And reward. Pleasurable music engages the brain's reward circuits, as food and money do. In 2019 Laura Ferreri and colleagues showed that a drug raising dopamine increased musical pleasure, and one blocking it reduced it. A few per cent of people have musical anhedonia: they feel little reward from music, though they enjoy other things. The reward follows prediction: the wanting and the getting of the hook's chills. Chapter seven puts surprise and uncertainty together.
7Surprise and uncertainty togetherPractice3 min
When is a surprise a pleasure?
The most direct test came in 2019. Vincent Cheung and colleagues modeled harmonic expectations using a large corpus of US popular songs and tested selected chord sequences without melody or lyrics. A model gave each chord a surprise and an uncertainty, and listeners rated pleasure in behavioral and neuroimaging experiments. Pleasure was high for surprising chords after certain contexts, and for unsurprising chords after uncertain ones. Neither number alone predicted pleasure; their interaction did, and so did activity in the amygdala and hippocampus. The finding is quoted here; the songs are under copyright and are not played.
Map it onto our listener's plane. Each dot is a note from our corpus, placed by uncertainty and surprise. Cheung's listeners liked best two opposite corners: a surprise when everything had seemed certain, the well-prepared twist; and a predictable arrival when things had been uncertain, the reassuring resolution. The gold regions sketch that pattern on our notes; they are not Cheung's data, which came from chords. A good surprise needs a firm expectation to break.
Hear the two corners. A firm approach to the dominant, held, that turns to A flat major instead of home; then chromatic chords that wander, unsure where they are going, and find their way home to C.
Different pleasures: the twist you did not see coming, and the relief of a home you were not sure you would reach.
This links to tension. Part 42's chosen tension proxy uses pitch height, non-chord tones, chord labels and density; it does not directly compute this listener's entropy, and Lerdahl and Krumhansl's model and listeners' continuous ratings agree in broad shape. A phrase that builds uncertainty and then resolves predictably is the reassuring corner, stretched out in time; a phrase that sets up certainty and then twists is the other. Composers engineer both.
Composers engineer uncertainty on purpose. Film scores, Part 44's subject, use drones and ostinatos with no cadence in sight. Risset's endless glide, from Part 45, is uncertainty that never resolves. And the build and drop of Part 40 raises uncertainty for many bars, then delivers one very likely event exactly on time. Each is a route to one of Cheung's two corners. Chapter eight turns to expectation in the body: groove.
8GrooveFoundations3 min
Why do some rhythms make you want to move?
Expectation also lives in the body. Petr Janata and colleagues defined groove as the pleasurable urge to move to music. Syncopation, from Part 38, is a note on a weak position followed by silence on a stronger one, and Christopher Longuet-Higgins and Christopher Lee measured it in 1984 by adding up, for every such note, how much stronger the silent position is. A syncopation is a broken metrical expectation: the body predicts the beat and the music withholds it. We score four patterns of ours.
Hear four patterns, the same drums and backbeat each time, with the bass and kick moved to more and more syncopated positions: none, a little, a medium amount, and a lot. Which makes you want to move most?
Maria Witek and colleagues had sixty-six listeners rate fifty drum breaks in 2014. Wanting to move, and pleasure, rose with syncopation and then fell: an inverted U, Berlyne's shape again. Too regular, and the body has nothing to fill in; too syncopated, and the beat itself is lost. Where on the curve would you put our four patterns?
Musicians often credit groove to microtiming, the tiny deviations from the grid of Part 43, or the swing of Part 38. But in 2013 Matthew Davies and colleagues, and separately Jan Frühauf and colleagues, found that adding random microtiming did not raise groove ratings, and often lowered them. Systematic patterns like swing can help; random wobble does not. Groove seems to come mostly from structure: syncopation, density, and the bass's interplay with the drums. Which leaves the question of why a beat moves the body at all.
Why should a beat make us move at all? Entrainment: bodies lock to a beat, and most people tap, nod or sway within seconds. Marcel Zentner and Tuomas Eerola found in 2010 that infants move more to music than to speech, though not yet in time with it. Synchronising to a beat is rare among animals: some parrots do it, most primates do not. Groove may be the pleasure of predicting the beat with the whole body. Chapter nine turns to the emotions music expresses, and Part 47 takes up the beat as a candidate universal.
9Expressed emotionFoundations5 min
How does music sound happy or sad?
A question for your ears. The Tune's first two phrases, four ways. For each, which emotion does it express: happy, sad, angry, or tender?
Happy, sad, angry, tender. Those are the intended labels of our sketches; agreement depends on listener, culture and stimulus, and this demonstration does not measure it. The underlying tune was kept, with mode and other performance features changed. What changed were cues: tempo, register, mode, loudness, articulation and timbre.
Patrik Juslin and Petri Laukka reviewed over a hundred studies in 2003 and found a consistent code. Happy: fast, fairly loud, detached, major, bright. Sad: slow, soft, legato, minor, dull. Angry: fast, loud, sharp attacks, harsh. Tender: slow, soft, legato, gentle. And the same cues signal emotion in speech: a sad voice is slow, low and soft. Music may borrow the code the voice already uses.
Why do those cues sound sad? The philosopher Peter Kivy gave the answer that is still the starting point, in 1980: music resembles the voice and the bearing of a person who feels the emotion. A sad person speaks slowly, softly and low, in small steps, and so does sad music. In 2003 Patrik Juslin and Petri Laukka reviewed a hundred and forty-five studies and found the same cues carrying emotion in speech and in musical performance. So music can be expressive of sadness the way a Saint Bernard's face looks sad, without being sad itself; that is Kivy's reply to Hanslick, from chapter one. And expressed is not the same as felt. What music does to the listener comes next.
The hook's chills have been studied directly. Chills, or frisson, a shiver and goose bumps, are reported from music by roughly half to two thirds of people. John Sloboda found in 1991 that listeners' chill passages often held a new harmony, a sudden change in loudness, or a voice entering; Oliver Grewe and colleagues found in 2007 that chills are personal and unreliable: the same passage rarely gives everyone a chill. They follow expectation: violations, entrances, and arrivals after a build. The hook's dopamine, on the skin.
Patrik Juslin listed the routes by which music arouses emotion, under the acronym BRECVEMA. A brainstem reflex to a sudden loud sound; rhythmic entrainment of the body; evaluative conditioning, music paired with past events. Emotional contagion, catching the voice-like cues of this chapter; visual imagery; episodic memory. Musical expectancy, this part's subject, and aesthetic judgement. Different mechanisms, with different time courses and different brain systems.
Why would anyone enjoy sad music? First, perceived emotion is not felt emotion: a sad song need not make you sad. Many people do enjoy sad music, and report nostalgia, being moved, and peace. Jonna Vuoskoski, Tuomas Eerola and others found that enjoyment of sad music goes with empathy and openness. Huron suggested a hormone of consolation, prolactin, released by sadness without any real loss, a hypothesis not yet confirmed.
Memory is one of the strongest routes. In the reminiscence bump, people remember and value most the music of their late teens and early twenties; Carol Krumhansl and Justin Zupnick found in 2013 that young adults also knew, and liked, the music of their parents' bump years. Music cues autobiographical memories vividly, often with emotion attached, and some musical memories can remain accessible in dementia, with substantial variation across people and disease stages. Liking a song is partly liking a time of one's life.
Some claims do not survive. The Mozart effect of 1993 said that ten minutes of Mozart briefly raised spatial reasoning; later meta-analyses found little or nothing, and what remained was arousal and mood: any enjoyable stimulus helped a little. Claims of music's power to cure, calm or teach often rest on small studies. The remedy is the replication standard: preregistration, larger samples, shared data. Chapter ten turns to predictive processing, and machines as listeners.
10Frontier: the predicting brainResearch2 min
Is all of music prediction?
The broadest current account is predictive processing. The brain continually predicts its input and learns from the errors. Stefan Koelsch, Peter Vuust and Karl Friston argued in 2019 that musical pleasure comes from reducing prediction error, weighted by its precision, where precision refers to confidence or inverse variance in a specified model, not simply the reciprocal of our Shannon entropy: errors count more when expectations were firm. It explains Cheung's interaction, and the build and the drop. But a framework that explains everything must still be tested on what it predicts.
Expectation also depends on where you grew up. In 2000 Carol Krumhansl and colleagues studied North Sami yoiks with Finnish and Sami listeners, and expectations followed what each group knew. Listeners from other traditions bring other schemas, Part 34's ragas and Part 35's maqam, and models trained on one culture predict that culture's listeners best. Expectation is universal; what is expected is learned. Part 47 asks what, if anything, every musical culture shares.
Machines have become listeners too. Many symbolic music models predict next tokens; generative audio also uses diffusion and other objectives, so their surprise can be read note by note, as ours was, and compared with people's. Early studies find that large models predict expectedness ratings and brain responses well, though they learn from far more music than any person hears. Part 65 builds a small one.
A concrete version. Train listener models on different amounts of music, from a child's exposure to a large model's. Compare their surprise with listeners' ratings, brain responses and pleasure, moment by moment. Find which model, and which amount of experience, predicts each person best. How much of musical pleasure is predicted by surprise and uncertainty alone? An answer would bound what expectation explains, and show what it leaves out.
Variation 46, recap and problemsAll tracks2 min
Every part ends by doing something to the Tune with what it built. Here, its last two phrases three times: ending as expected; with the ending delayed by the deceptive turn; and with the ending denied. Beside each, the listener's surprise, note by note.
Row forty-six of the ledger: the measurement is the listener's surprise. The turn to the ending costs , and bits in the three versions; the last note , and .
What did we find? Musical feeling is tied to expectation: wanting, then getting. Expectations are learned by counting, without trying. A listener model measures surprise and uncertainty in bits. Delay makes a resolution more certain; denial leaves the cost unpaid. Pleasure lies in the interaction of surprise and uncertainty. And selected groove and liking studies report inverted-U patterns, with effects depending on stimulus and listener, while expressed emotion has a code of cues.
Five problems. One to compute, one to prove, one for your ears, one to build, and a research problem, marked with a star. Solutions are in this part's notes. Pause here.
Where does this come back? In origins and universals, what all listeners share. In mastering, where loudness sets arousal. In finding music, recommendation and preference. In machines that compose, a listener that writes. And in doing research in music, where replication matters.
And in practice. Composers build expectations before breaking them. Songwriters delay the chorus, then pay it off. Producers build tension with uncertainty and release it with a drop. And music therapists choose music by its cues, and measure what it does.
The books and papers this part follows. The full list, with notes, is in the README.
Where it goes next. Origins and universals in Part 47; mastering and loudness in Part 57; recommendation in Part 63; machines that compose in Part 65; replication in Part 67.
Key results
The part's results in one place, for revision.
Try it
Lab 46 · Expectation, computed
Train a listener on a corpus and measure the surprise of every note; write your own endings for the Tune and price them; and score drum patterns for syncopation.
python -m videos.music.labs 46
needs numpy, scipy, matplotlib · download lab46.py ·
source on GitHubthe Tune heard at order 4: mean surprise / uncertainty (bits) 1.98 / 2.51
your ENDING, note by note (bits) 1.4, 1.4, 1.2, 0.6, 0.6, 2.7, 6.3, 4.6, 1.6, 2.3, 0.9
the plain ending's last C, for comparison (bits) 1.23
PATTERN's syncopation index (Longuet-Higgins and Lee) 4
ear problem: after the stream, each triplet is a word or a part-word (listen first) part-word, word, part-word
Surprise is -log2 of the probability the model gave the note that came; uncertainty is the entropy of its prediction. A delay raises surprise at the turn and lowers it at the arrival.
The code (71 lines; it asserts its own result)
"""Lab 46: expectation, computed: a variable-order listener's surprise and uncertainty, endings of your own,
statistical learning and a syncopation index."""
import numpy as np
from videos.coursekit import labs
from explainer.music.monochord import SR, Clip, concat, mix
from explainer.music.monochord import listener as L
from explainer.music.monochord import melody as M
from videos.music.music46 import compute as C
TITLE = "Expectation, computed"
GOAL = ("Train a listener on a corpus and measure the surprise of every note; write your own endings for the Tune and "
"price them; and score drum patterns for syncopation.")
TASKS = [
"Change ORDER (0 to 6). Does a longer memory make the Tune more or less surprising? Why does it stop helping?",
"Write ENDING (pitches after the Tune's sixth phrase, relative to C). Can you write a delay that makes the last C cheaper still?",
"Edit PATTERN (onsets on 16 steps) and find the syncopation that grooves best for you.",
]
ORDER = 4
ENDING = [5, 5, 4, 4, 2, 2, -3, 5, 4, 2, 0]
PATTERN = [0, 3, 6, 10, 12, 14]
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
corpus = [t.pitches for t in C.TUNES if t.name != M.THE_TUNE]
lis = L.Listener(corpus, ORDER)
r = lis.listen(C.THE.pitches)
lab.row(f"the Tune heard at order {ORDER}: mean surprise / uncertainty (bits)", f"{r['mean_ic']:.2f} / {r['mean_entropy']:.2f}")
head = C.THE.pitches[:-7]
e = lis.listen(head + ENDING)
ic = e["ic"][-len(ENDING):]
assert all(x >= 0 for x in ic)
lab.row("your ENDING, note by note (bits)", ", ".join(f"{x:.1f}" for x in ic))
plain = lis.listen(C.THE.pitches)["ic"][-1]
lab.row("the plain ending's last C, for comparison (bits)", f"{plain:.2f}")
lab.row("PATTERN's syncopation index (Longuet-Higgins and Lee)", f"{L.syncopation(PATTERN)}")
# sound: your ending; ear problem: a stream of words, then a word or a part-word at random
clips = [C.play_line([(m, 1 if i < len(ENDING) - 1 else 2) for i, m in enumerate(ENDING)], beat=0.42)]
words = C.WORDS
s = L.saffran(words, 24, rng)
ioi = 0.22
clips.append(Clip(mix([(Clip(C.sine(m, 0.2), SR), i * ioi, 0.0) for i, m in enumerate(s["sequence"])], duration=len(s["sequence"]) * ioi + 0.3).y, SR))
answers = []
for i in range(3):
if rng.random() < 0.5:
trip, kind = words[int(rng.integers(4))], "word"
else:
a, b = rng.choice(4, 2, replace=False)
trip, kind = (words[a][2], words[b][0], words[b][1]), "part-word"
clips.append(Clip(mix([(Clip(C.sine(m, 0.2), SR), j * ioi, 0.0) for j, m in enumerate(trip)], duration=3 * ioi + 0.3).y, SR))
answers.append(kind)
lab.audio = concat(clips, gap=0.9)
lab.row("ear problem: after the stream, each triplet is a word or a part-word (listen first)", ", ".join(answers))
fig, (ax1, ax2) = labs.figure(2)
ax1.bar(range(len(r["ic"])), r["ic"], color=labs.GOLD, label="surprise")
ax1.plot(range(len(r["entropy"])), r["entropy"], color="C0", label="uncertainty")
ax1.set_xlabel("note of the Tune")
ax1.set_ylabel("bits")
ax1.legend(fontsize=7)
ax2.bar(range(len(ic)), ic, color="C3")
ax2.set_title("your ending")
ax2.set_xlabel("note")
lab.fig = fig
lab.note = ("Surprise is -log2 of the probability the model gave the note that came; uncertainty is the entropy of its "
"prediction. A delay raises surprise at the turn and lowers it at the arrival.")
return lab
Now change it
- Change ORDER (0 to 6). Does a longer memory make the Tune more or less surprising? Why does it stop helping?
- Write ENDING (pitches after the Tune's sixth phrase, relative to C). Can you write a delay that makes the last C cheaper still?
- Edit PATTERN (onsets on 16 steps) and find the syncopation that grooves best for you.
Problems, with solutions
Try each problem before opening its solution.
-
Compute. A model gives the next note probability 1/8. What is its surprise? And for 1/1000?
Solution
−log₂(1/8) = 3 bits; −log₂(1/1000) = log₂ 1000 ≈ 9.97 bits. Each halving of the probability adds one bit.
-
Prove. Prove that uncertainty is largest when every next note is equally likely, and equals log₂ n.
Solution
Maximise H = −Σ pᵢ log₂ pᵢ subject to Σ pᵢ = 1. With a Lagrange multiplier, −log₂ pᵢ − 1/ln 2 = λ for every i, so all pᵢ are equal, pᵢ = 1/n, and H = log₂ n. H is concave, so this stationary point is the maximum. (Gibbs's inequality gives the same in one line.)
-
Ear. The lab plays word and part-word triplets after a stream; say which was the word.
Solution
The lab prints them. A word's three tones always came together in the stream, so it sounds complete; a part-word straddles a boundary and sounds subtly wrong. Listening twice to the stream helps.
-
Build. Train the listener on a different corpus and compare the Tune's surprise.
Where to look.
Listener(corpus, order)takes any list of pitch sequences relative to their tonics: try only the minor tunes, only the Christmas carols, or Part 42's chain outputs, and compare the Tune's mean surprise and which notes become surprising. -
★ How much of musical pleasure do surprise and uncertainty alone predict?
Where the frontier is. Collect continuous pleasure ratings and physiology for many pieces; model each moment with surprise, uncertainty and their interaction from listener models trained on different amounts of music; report the variance explained per listener, and what remains.
Notes and sources
Sources
- L. B. Meyer, Emotion and Meaning in Music (1956); E. Hanslick, On the Musically Beautiful (1854); D. Huron, Sweet Anticipation (2006) and "Tone and voice" (2001).
- V. N. Salimpoor and others, "Anatomically distinct dopamine release during anticipation and experience of peak emotion to music", Nature Neuroscience (2011); L. Ferreri and others, PNAS (2019).
- J. R. Saffran, R. N. Aslin and E. L. Newport (1996); J. R. Saffran and others, "Statistical learning of tone sequences by human infants and adults", Cognition (1999); C. L. Krumhansl and R. N. Shepard (1979); L. J. Trainor and S. E. Trehub (1994); E. Bigand and B. Poulin-Charronnat (2006).
- M. T. Pearce, "The construction and evaluation of statistical models of melodic structure" (thesis, 2005); M. T. Pearce and others, NeuroImage (2010); D. Conklin and I. H. Witten, "Multiple viewpoint systems for music prediction" (1995).
- S. Koelsch and others, "Brain indices of music processing", J. Cognitive Neuroscience (2000); A. D. Patel and others (1998); S. Koelsch, P. Vuust and K. Friston, "Predictive processes and the peculiar case of music", TICS (2019).
- V. K. M. Cheung and others, "Uncertainty and surprise jointly predict musical pleasure and amygdala, hippocampus, and auditory cortex activity", Current Biology (2019).
- P. Janata and others (2012); M. A. G. Witek and others, PLoS ONE (2014); H. C. Longuet-Higgins and C. S. Lee (1984); M. Davies and others (2013); J. Frühauf and others (2013); M. Zentner and T. Eerola (2010).
- P. N. Juslin and P. Laukka, Psychological Bulletin (2003); P. N. Juslin, "From everyday emotions to aesthetic emotions", Physics of Life Reviews (2013); J. A. Sloboda (1991); O. Grewe and others (2007); J. K. Vuoskoski and T. Eerola on sad music; C. L. Krumhansl and J. A. Zupnick (2013); D. E. Berlyne, Aesthetics and Psychobiology (1971); F. H. Rauscher and others (1993) and later meta-analyses of the "Mozart effect".
- P. Kivy, The Corded Shell: Reflections on Musical Expression (1980), the contour theory of chapter 9; P. N. Juslin and P. Laukka, "Communication of emotions in vocal expression and music performance: different channels, same code?", Psychological Bulletin 129 (2003).
About this partfrom its README
Part 46 of a sixty-eight-part course in music (see the series plan and
the syllabus), the second part of Act VIII, The Mind. In 2011 PET supported striatal dopamine release during pleasurable music, while fMRI distinguished anticipatory and peak-related activity. Meyer had argued in 1956
that musical emotion is expectation delayed and fulfilled. This part builds a listener model, measures surprise and
uncertainty in bits, and engineers three endings for the Tune. The tools are Monochord's
(explainer/music/monochord/listener.py). The listener is trained on the series' corpus of folk and public-domain tunes;
published findings (Salimpoor, Cheung, Witek, Juslin and others) are quoted, not reproduced, and are listed under
Sources.
- Wanting, then getting. An ear question (three endings for the Tune: which surprised the listener most and least? F♯ 10.9 bits, A 5.5, C 1.2); chills and dopamine; the plan.
- 1. Expectation. Hanslick and the expression theories; Meyer; Huron's ITPRA; three kinds of expectation; dynamic expectation heard (a motive's leap costs 4.8 bits, then 2.1 and 2.0, then 7.4 when changed); what expectation leaves out.
- 2. Statistical learning. Saffran's infants; an ear question (a stream of tone words, then a word and a part-word; transitional probability 1 inside words, 0.4 across); probe tones heard (C 2.0, D 4.8, F♯ 8.6 bits); a lifetime of counting; growing up a listener.
- 3. A listener model. How it works (PPM, long- and short-term models, after IDyOM); surprise and uncertainty; viewpoints; the Tune note by note, heard (1.98 bits a note, falling from 2.6 in the first phrase to 1.3 in the last); the listener sings; the whole corpus (1,788 notes; surprise and uncertainty correlate 0.23).
- 4. Surprise across melodies. Mean surprise for the Tune, Ode to Joy, Part 42's kept and rejected drafts (3.1 and 3.8 bits), its chains, random notes (3.9); the drafts heard; random notes and the order-4 chain heard; does the model hear as we do?; the inverted U.
- 5. Three endings. Expected, delayed, denied, heard; their surprise note by note (the deceptive turn 6.3 bits, then the final C 0.9, against 1.2 undelayed; F♯ 10.9); the denied ending three times running (10.9, 3.0, 2.2 bits); how scale degrees feel; devices of delay; a suspension heard.
- 6. The brain at a wrong chord. The ERAN; a Neapolitan ending heard; music and language (the P600); automatic prediction (the mismatch negativity); reward.
- 7. Surprise and uncertainty together. Cheung and colleagues' interaction; where pleasure lies, sketched on our corpus; the two corners heard; tension as uncertainty; uncertainty engineered.
- 8. Groove. Groove and syncopation; four patterns of rising syncopation (index 0, 3, 4, 11), heard; Witek's inverted U; is groove in the timing?; moving to a beat.
- 9. Expressed emotion. An ear question (the Tune in four settings: happy, sad, angry, tender); the cues (after Juslin and Laukka); chills; eight mechanisms; the pleasure of sad music; music and memory; what does not replicate.
- 10. Frontier: the predicting brain. Predictive processing; expectation across cultures; models as listeners; ★ research problem: how much of musical pleasure do surprise and uncertainty alone predict?
- Variation 46, recap and problems. The Tune's last two phrases with three endings, with the listener's surprise at each note; the ledger; what we found; five problems; where it comes back; in practice; references; Part 47.
What is computed and built
python -m videos.music.music46.compute (under a minute) fills .cache/music46/.
| Item | What it computes | Checked against |
|---|---|---|
hook, endings, again, tune46 |
endings priced in bits; a denial repeated; Variation 46 | delay lowers the arrival's surprise (tests) |
tune, corpus, compare, extremes, drafts |
the listener on the Tune, the corpus and other melodies | random > the Tune; rejected > kept (tests) |
learn |
a Saffran-style stream and test | transitional probabilities (tests) |
probe, rep, sing |
probe tones; dynamic expectation; a sampled melody | probe ranking (tests) |
susp, neap, corners |
a suspension; a Neapolitan; the two corners | — |
groove, emotion |
four syncopation patterns; four expressive settings | the syncopation index (tests) |
Monochord's tools are held in tests/music/test_listener.py; this part's claims and clips in tests/music/test_music46.py.
Sounds. Part 7's piano and Part 38's bass (physical models), the additive orchestra, Part 40's drums, sine tones. There are no recordings; the songs of Cheung's study are under copyright and are not played.
What the models are, and are not. The listener uses one viewpoint (pitch relative to the tonic) and a corpus of 51 tunes; IDyOM uses many viewpoints and far more music. Its surprise is a model's, not a measurement of any listener. The shaded regions of chapter 7 sketch Cheung's published pattern on our notes; they are not his data. Witek's curve is sketched, not reproduced.
Notes
PET and fMRI provide complementary evidence; they do not directly resolve two timed dopamine pulses. Surprise is minus log probability, not a literal guess count. This symbolic transition model is an analogy to statistical learning, not a complete infant or brain model. Probe-tone fit and predictability differ; corpus comparisons do not validate pleasure. Part 42’s tension proxy does not compute entropy, and predictive precision is not reciprocal Shannon entropy. Cheung’s reported chord results are sketched on our note data, not re-estimated. Emotion labels and inverted-U effects depend on listener and stimulus; mode changes alter pitches as well as performance.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Hook: an ear question (three endings: which surprised the listener most?); chills and dopamine; the plan.
- Expectation: Hanslick; Meyer; ITPRA; three kinds; dynamic expectation heard; what expectation leaves out.
- Statistical learning: Saffran; an ear question (a word or a part-word?); probe tones heard; a lifetime of counting; children.
- A listener model: how it works; two numbers per note; viewpoints; the Tune note by note heard; the listener sings; the corpus.
- Surprise across melodies: the comparison; Part 42's drafts heard; random and chain heard; evidence; the inverted U.
- Three endings: heard; priced in bits; a denial repeated; scale-degree qualia; devices of delay; a suspension heard.
- The brain at a wrong chord: the ERAN; a Neapolitan heard; music and language; mismatch negativity; reward.
- Surprise and uncertainty together: Cheung; where pleasure lies; the two corners heard; tension; uncertainty engineered.
- Groove: syncopation; four patterns heard; the inverted U; microtiming; entrainment.
- Expressed emotion: an ear question (four settings); the cues; chills; mechanisms; sad music; memory; what does not replicate.
- Frontier: predictive processing; expectation across cultures; models as listeners; the research problem.
- Variation 46: the Tune with three endings, priced in bits. Outro: problems, payoffs.
Covers: Meyer; statistical learning; surprise and uncertainty and their interplay; brain responses to syntax;
tension; groove and syncopation; the cues of expressed emotion; the pleasure of sad music; preference and
complexity; what does not replicate.
Built and computed: monochord/listener.py: a variable-order listener (PPM, escape method C, long- and short-term
models combined by entropy, after IDyOM) trained on the series' 51 major-key tunes; surprise and entropy curves for the
Tune (1.98 bits a note), the corpus (1,788 notes), Part 42's drafts (kept 3.1, rejected 3.8) and chains, random notes
(3.9); probe tones; dynamic expectation; a Saffran-style stream (transitional probability 1 inside words, 0.4 across);
the Longuet-Higgins and Lee syncopation index. Published findings (Salimpoor, Cheung, Witek, Juslin and Laukka) are
quoted beside the model's numbers, not reproduced.
Variation 46: the Tune with three endings: expected (last C 1.2 bits), delayed (the deceptive turn 6.3, then the C
0.9), denied (F♯, 10.9).
Frontier: predictive-processing accounts; models as listeners (open: how much of pleasure surprise and uncertainty
predict).
Reading: Meyer (1956); Huron (2006); Salimpoor et al. (2011); Cheung et al. (2019); Witek et al. (2014).
Build the film
python -m videos.music.music46.compute # the part's numbers, into .cache/music46
python tools/build.py music46 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py music46 Hook # one chapter, silent, with a contact sheet
Scenes: videos/music/music46. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.music.music46.compute # numbers and sounds (under a minute)
EXPLAINER_TTS=silent python tools/build.py music46 -q l --fps 15 # a silent-narration preview, with the sounds
python tools/qa_sound.py music46 --sync # the sound gates
python tools/dead_air.py renders/music46_480p.mp4 --sound music46 # no empty screen; no sound over a still one
python tools/lecture_length.py music46 # 30 to 60 minutes, listening included
python tools/build.py music46 # 1080p30, narrated
python -m pytest -q tests/music # Monochord against its references; this part's claims and clips
python -m videos.music.labs 46 # the lab (writes a figure and a short WAV)