π± Autocomplete
π² Your smartphone predicts words
Complete this sentence: "I would like a cup of ...".
You probably think of "coffee" or "tea". If you type this sentence on a smartphone, autocomplete suggests "coffee" too, with "the" and "course" next to it:

How does your smartphone know that?
Take out your smartphone and open the keyboard by going to a notes app or a chat app. Make sure you see the autocomplete options at the top of your keyboard; sometimes you first have to type a word yourself. Now tap one of the suggestions that appear, about ten times in a row.
- What kind of sentence do you get?
- Does the sentence make grammatical sense? Or does it sound like nonsense?
- Do you end up in a loop?
- Does it use words that you often use yourself?
You can also try it with the autocomplete below:
π How does autocomplete work?
The classic autocomplete model in this chapter knows no grammar and understands no meaning. It does only one thing: counting. In a large amount of text, it counts how often each word came after the previous few words. From those counts it computes the probability of every possible next word, and it shows you the three most likely candidates.
That is how a keyboard knows that "a cup of" is often followed by "coffee": in the texts it was trained on, that word simply came after "a cup of" very often. The other two suggestions fit the last word: "of the" and "of course" are very common.
The probabilities that autocomplete computes are conditional probabilities: the probability of a word given the previous words. So what autocomplete actually computes is: "what is the probability of 'coffee' if the previous words are 'a cup of'?"
In the rest of this chapter we build such a model ourselves, in two steps: first counting, then turning the counts into probabilities. After that, we let the model write complete sentences, and we look at why those so often go wrong.
Many keyboards also learn from the way you write and adjust their suggestions slightly. That is why you may have seen words that you typically use come back in the suggestions.
π N-grams: counting words
To count, the model needs text: the training text. A real keyboard trains on millions of sentences. We take just one, long enough to follow the recipe and short enough to work everything out yourself:
The dog of the man of the neighbors of the cat bit the man of the cat of the neighbors
The recipe has two steps:
- π’ Count how often each word combination occurs in the text.
- π Turn the counts into probabilities: how often did each word follow the same previous words?
π’ Step 1: count how often words follow each other
Suppose the model looks back one word. Then it has to know how often each pair of words occurs in the text: how often "dog" follows "the", how often "of" follows "dog", and so on. You count that by sliding a window of two words over the text. At each position of the window, the tally for that pair of words goes up by one.
Do it yourself in the demo below: slide the window over the text with the arrows, or play it, and watch the table grow row by row.
Look at the table once the window has reached the end of the text. The word "the" occurs seven times as the first word of a pair: it is followed once by "dog" and twice each by "man", "neighbors" and "cat". After "of", on the other hand, always comes "the", all five times.
The markers β¨startβ© and β¨endβ© count too, so that the model also knows which word opens a sentence (after β¨startβ©) and after which word a sentence can stop (before β¨endβ©).
Such pairs of words are called bigrams. If the window counts three words at a time, we speak of trigrams, and in general of n-grams.
An n-gram is a series of consecutive items from a sequence, for example words in a text.
Special cases:
- A 1-gram is also called a unigram
- a 2-gram a bigram
- and a 3-gram a trigram.
The sentence "the dog barks loudly" has:
- 4 unigrams: "the", "dog", "barks" and "loudly"
- 3 bigrams: "the dog", "dog barks" and "barks loudly"
- 2 trigrams: "the dog barks" and "dog barks loudly".
Set the demo above to 1-gram: the model then simply counts how often each word occurs, without looking at the previous words. At 3-gram it counts, for every two previous words, which word followed; we come back to that further on.
Counting n-grams is useful beyond autocomplete too. The Google Books Ngram Viewer (external link) counted all the n-grams in millions of digitized books and shows, per year, how often a word or phrase occurred. For example, you can see how, in English-language books, the name the Great War gives way to World War I around 1940 (external link), or when a new word first appears.
π Step 2: turn the counts into probabilities
The counts do not yet say how likely a word is. For that, we look at the ratio per context: of all the times the context occurred, in how many cases was it followed by a particular word?
The context is the piece of text the model looks at to predict the next word: the last words. So a bigram model () looks back one word, and a trigram model () two words.
Take the context "the". It occurred seven times, and in two of those cases it was followed by "cat". So the probability of "cat" after "the" is:
Here is the number of times that word combination was counted. So you divide the tally of the bigram by the total of all the bigrams that start with the same context. That is exactly the conditional probability : the probability of a word, given the context.
Do that for every row and you get the complete probability table of the bigram model. The colored bands show which rows share the same context; the probabilities within one band add up to 100%.
Work these out yourself, without looking at the table:
- What is the probability of "of" after "cat"?
- And the probability of "the" after "of"?
That probability table is the autocomplete model. Click "the" below and you get four suggestions with exactly the probabilities from the table: "man", "neighbors" and "cat" with 28.6% each, and "dog" with 14.3%. Click a suggestion and the context (yellow) moves along to the new last word:
π Looking back two words: trigrams
One word of context is not much: after "the" the model can still go in any direction. A trigram model () therefore looks back two words. For every two previous words it counts which word followed, and it computes the probabilities in exactly the same way:
Notice that the choices become much more limited: after "the cat" only "of" or "bit" can follow, and after "cat of" always "the". That makes the suggestions fit better, but also more predictable. Try it in the box below and compare the probabilities with the trigram table:
The number counts the words in the n-gram, so including the word that is predicted. That is why a trigram model looks back only words, and a bigram model one word. The keyboard in the screenshots of this chapter looks back three words, so it works like a 4-gram model: three words of context, one word of prediction.
πͺ General formula for n-gram probabilities
You compute the probability of a word given the previous words (the context) as:
Where:
- = the word we want to predict
- = the previous words (the context)
- = the number of occurrences of that sequence of words in the training text
The sum in the denominator runs over all the words that ever followed the context. So it is simply the total number of times the context occurred, which is why the probabilities per context add up neatly to 1.
βοΈ Generating text with autocomplete
βοΈ Algorithm
With the probability table, the model can also write complete sentences, simply by predicting the next word again and again:
- Look at the context: the last words of the sentence so far.
- Look up the probabilities: take from the table all the words that ever followed that context, with their probabilities.
- Pick a word: the word with the highest probability, or roll a die according to the probabilities.
- Repeat: the chosen word moves into the context and the process starts again, until the model picks β¨endβ©.
Try it yourself with the autocomplete below, trained on fairy tales. Notice how the context (the yellow words) shifts after each chosen word, and how the probabilities of the suggestions change. With the dice button (Randomize) you let the model choose the rest of the sentence itself, each time drawing a random word according to the probability distribution:
πΊοΈ The model as a map
The bigram model of our example sentence fits in a single drawing. Each word is a state (a circle) and each arrow a possible next word, labeled with its probability from the probability table: the thicker the arrow, the higher the probability. Generating a sentence is then simply a walk over the map, from β¨startβ© to β¨endβ©.
Walk through it yourself by clicking an arrow, let the algorithm always follow the highest probability, or let it roll a die. You can also have the map built from a sentence of your own:
Set the map to Highest probability, press Play, and you immediately see why you ended up in a loop on your smartphone: after "of" always comes "the", after "the" the model picks "man", and after "man" comes "of" again, forever. With Random, the model rolls a die at every step according to the probabilities on the arrows, and you get a different sentence every time. The dice button (Randomize) in the autocomplete boxes works the same way.
Such a map of states and arrows with probabilities is called a Markov chain. In the in-depth section further on, we take a closer look at them.
π The importance of training data
The suggestions autocomplete gives depend entirely on the text it was trained on. A model trained on news articles will predict very different words from a model trained on song lyrics.
Try it yourself:
- In the demo below, switch between different data sources. What kind of sentences do you get when you train on the King James Bible? On Cowboy songs? Or on the poems of Emily Dickinson? What happens if you switch data sources halfway through?
- Now switch to the "Probability table" tab to look at the n-gram table. The contexts you just used are at the top. Also try typing words in the search box ("Search for a word...") to look for specific occurrences.
- Change the n-gram size and see how the table and the suggestions change: they look back more words (higher ) or fewer words (lower ) to make their prediction.
- In the Model menu, choose "Your own dataset" and paste a text of your own: for example a long document you wrote, the lyrics of your favorite artist, or a copy-paste of part of this course. You will see which suggestions the model makes based on your writing. Generate new sentences with it.
Note: with a higher you look at more context, but you have less data per context (many n-grams occur only once, and then the model simply copies the training text). With a lower you have more data per context, but less coherence. This is a common trade-off in machine learning (ML), which you already saw when choosing the number of neighbors in k-nearest neighbors.
πͺ Strengths and limitations
β Strengths
- β‘ Simple and fast: the model is just a lookup table. Generating suggestions needs no expensive computations, so it is very fast, even on your smartphone.
- π Transparent: by looking at the n-gram table, you can see exactly why a word was suggested. Every word has a clear, explainable probability.
- π οΈ Easy to update: to adapt the model to new text, you only have to count the n-grams again. No complex retraining is needed.
- π± Works with little data: even a limited amount of text already gives useful suggestions, because the model simply counts word frequencies.
- π΄ Works offline: the model is compact enough to run locally on your phone, without an internet connection.
π¨ Limitations
-
π§ Short memory: this classic autocomplete model looks only at the last words and ignores everything that came before. Try it on your smartphone: delete the words at the start of your sentence one by one. As long as the suggestions stay exactly the same, your keyboard is not looking at those words. The keyboard in these screenshots only looks at the last three.

After only "a cup of" you get exactly the same suggestions as after the whole sentence. So a sentence such as "My goldfish lives in a cup of" also gets the same suggestions, even though "water" would make much more sense there.

-
π No grasp of grammar: the model does not understand grammar or sentence structure. The sentences are often locally consistent (every group of a few consecutive words could occur in a real sentence), but globally nonsense.

A typical autocomplete sentence that makes sense locally, but tells no coherent story as a whole: "I am home now I love you too my friend I hope you have a great day of the week". -
π Infinite loops: if you always pick the most likely word, you can end up in a loop, such as "the man of the man of the man ..." on the map above. The same happens on a smartphone: "of the" is often followed by "week", and "the week" by "of" again, so you generate "of the week of the week of the week..." forever.
-
π Language confusion: the model can switch languages when it comes across words that exist in more than one language, such as "of", which is also a Dutch word (meaning "or").
-
π³οΈ Sparsity: word combinations that do not occur in the training data get a probability of exactly 0. The model then cannot suggest anything at all, even if the combination would make perfect sense. In that case, the demos on this page (and classic keyboards) fall back on a shorter n-gram: if the trigram model does not know the last two words, it looks at the last word only.
In the chapter on large language models, we will see how modern language models reduce many of these limitations. They use much longer context windows (external link) and generalize over word combinations they have never seen exactly, although they still make mistakes too.
π Markov chains
The map of states and arrows from the previous part is a mathematical object with a name of its own.
A Markov chain is a system that jumps from state to state, where the probability of the next state depends only on the current state and not on earlier states.
This is called the Markov property:
Here is the word at time and the previous word. In other words: the past does not matter, only the present determines the future.
The bigram model is the simplest Markov chain: each state is one word. But a trigram model is one too. You just have to choose the states differently.
Every n-gram autocomplete model is actually a Markov chain. The states are the contexts (the previous words) and the transitions are the probabilities of the next words. For a trigram model, "the cat" is therefore one state, with arrows to the states "cat of" and "cat bit". As with Bayesian networks, this is about conditional independence: once the "parents" (in this case the previous words) are known, the next word does not depend on words far in the past.
Note that a Markov chain always meets an important condition: all the outgoing probabilities from each state add up to 100%. They have to, because the probabilities of all the possible next words together form a complete probability distribution. You can see it on the map: the four arrows out of "the" together carry 14.3% + 28.6% + 28.6% + 28.6% β 100% (the exact values, 1/7 and 2/7, add up to exactly 100%).
The same math appears far beyond autocomplete. For example, PageRank (external link), the original algorithm behind Google's search engine, describes a surfer who clicks links at random as a Markov chain over web pages, and ranks pages by how often that surfer ends up on them.
π΅βπ« Perplexity
π² The probability of a sentence
Suppose you have two autocomplete models: one trained on news articles and one trained on the Bible. Which model is better at predicting a news item? We need a way to compare language models.
The idea: a good model finds the sentences of a news item likely, a bad model finds them surprising. You can compute how likely a model finds a sentence from the probabilities in its table. Pretend that you generate the sentence word by word, and look up for each word the probability the model gives it. The probability of the whole sentence is then the product of all those probabilities (the chain rule from the chapter on probability).
For the bigram model of our example sentence, the probability of "the cat bit the neighbors" is:
The markers β¨startβ© and β¨endβ© make sure that the first word and the end of the sentence get a probability too. So the probability of this sentence is 1 in 49. A sentence with unusual word combinations gets a much lower probability, because it contains unlikely n-grams.
π The problem with longer sentences
This approach has a problem. Look at the table below, with the probabilities of five sentences according to a model trained on the comedies of Oscar Wilde. All five start with "Life is", and two of them are longer versions of another one. What do you notice?
A longer sentence always gets a lower probability, simply because we multiply more probabilities (each at most 1, most of them smaller). That is not fair: a longer sentence is not by definition harder to predict.
π― Perplexity: how unexpected is a sentence for a model?
We need a measure that corrects for the length of the text: the perplexity. The idea: do not look at the probability of the whole sentence, but at how much choice the model had, on average, at each word.
Back to "the cat bit the neighbors". Its probability was 1 in 49, over six prediction steps. If the model had had the same amount of choice at every step, how many words would it have chosen from each time? Choosing six times in a row from words gives a probability of 1 in . So , or . On average, the model chose from fewer than two words per step: for the model, the sentence was quite predictable. That number, the average number of words the model seems to choose from at each step, is the perplexity.
Perplexity measures how well a language model can predict a text: the average number of words the model seems to choose from at each step. For a text with prediction steps, you take the -th root of the inverse of the probability of the text:
Or, shorter, with the product sign :
Where:
- = the -th word in the text
- = the previous words before word
- = the number of prediction steps: every predicted word, β¨endβ© included
- = the product of all the probabilities
The -th root turns the product into an average per word (a geometric mean (external link), because you multiply probabilities instead of adding them). That way every word counts equally, whether the text is short or long.
The lower the perplexity, the better the model predicts the text.
A perplexity of 10 means that the model is, on average, as uncertain as if it had to choose from 10 equally likely words at every step. A perplexity of 2 means that the model predicts the text so well that it considers only 2 options per step on average.
Now look at the same sentences again, this time with the perplexity column added. Click a row to see the full calculation. You will notice that the perplexity differs much less between short and long sentences than the probability does:
Note that this formula uses a language model to estimate the probability . In this chapter we use our n-gram Markov chain for that, but you can use other language models here too. Neural language models such as GPT, which you will get to know in the chapter on large language models, achieve much lower perplexity scores, because they use thousands of words of context instead of just two.
πΉοΈ Demos
Experiment further with the full simulators and demos featured above.




π£οΈ Feedback
Just like machine learning algorithms, we also love learning from your feedback to improve the course.
Let us know how informative and how difficult you found this chapter, and where it could be better.