Contents
Figure 1: Markov Chains Explained: Build a Text Generator and a Weather Model — a pen mid-word, which is roughly how a Markov chain writes: one word at a time, with no memory of the paragraph
Your phone suggests the next word before you finish typing. Ever wondered how it guesses, and why it sometimes guesses so badly? A Markov chain sits behind the simplest version of that trick.
I built my first one on a pile of my own old emails. The output sounded like me after three sleepless nights: mostly nonsense, weirdly confident. It also hooked me for good.
Let me show you how to build one yourself.
What Is a Markov Chain?
A Markov chain models a system that hops between states, where the next state depends only on the current one. The system doesn't care how it got here. It looks at where it stands now and picks its next move.
Andrey Markov studied these chains in the early 1900s, and they still power plenty of modern tools [1]. The core rule has a fancy name: the Markov property, or "memorylessness."
Think of a board game where you roll dice to move. Your next square depends on your current square and the roll. Your previous ten turns don't matter at all.
The Three Pieces You Need
Every Markov chain contains the same parts:
- States: the situations the system can occupy (Sunny, Cloudy, Rainy).
- Transition probabilities: the odds of moving from one state to another.
- Starting state: where the chain begins.
You organize the probabilities in a transition matrix. Each row covers one current state, and each row's probabilities must sum to 1. If a row sums to 0.9, you lost 10% of your universe somewhere.
Build a Weather Model
Weather makes the friendliest first example. Let's invent a tiny three-state climate. I made these numbers up, so please don't plan a picnic around them.
| Today ↓ / Tomorrow → | Sunny | Cloudy | Rainy |
|---|---|---|---|
| Sunny | 0.7 | 0.2 | 0.1 |
| Cloudy | 0.3 | 0.4 | 0.3 |
| Rainy | 0.2 | 0.3 | 0.5 |
Read it row by row. After a sunny day, tomorrow stays sunny 70% of the time. After a rainy day, rain sticks around 50% of the time, which feels about right for my city in monsoon season.
Simulate It in Python
You only need the standard library:
import random
transitions = {
"Sunny": {"Sunny": 0.7, "Cloudy": 0.2, "Rainy": 0.1},
"Cloudy": {"Sunny": 0.3, "Cloudy": 0.4, "Rainy": 0.3},
"Rainy": {"Sunny": 0.2, "Cloudy": 0.3, "Rainy": 0.5},
}
def simulate(start, days):
state = start
history = [state]
for _ in range(days):
options = transitions[state]
state = random.choices(
list(options), weights=list(options.values())
)[0]
history.append(state)
return history
print(simulate("Sunny", 10))
Run it a few times. You get a different forecast every run, but sunny stretches tend to cluster together, just like real weather.
Answer Questions With Math
You can also skip the simulation and calculate directly. Suppose today is sunny. What's the chance of rain two days from now? Add up every path that ends in rain:
- Sunny → Sunny → Rainy: 0.7 × 0.1 = 0.07
- Sunny → Cloudy → Rainy: 0.2 × 0.3 = 0.06
- Sunny → Rainy → Rainy: 0.1 × 0.5 = 0.05
The total is 0.18, so an 18% chance. Matrix multiplication does this bookkeeping for you, because squaring the transition matrix gives you two-step probabilities.
The Long Run: Stationary Distributions
Here's where things get interesting. Run the weather chain for a few hundred days, and the share of sunny, cloudy, and rainy days settles into fixed proportions. The starting state stops mattering.
We call that the stationary distribution. For our made-up climate, it works out to about 46% sunny, 28% cloudy, and 26% rainy [2]. You can check this yourself with NumPy:
import numpy as np
P = np.array([[0.7, 0.2, 0.1],
[0.3, 0.4, 0.3],
[0.2, 0.3, 0.5]])
print(np.linalg.matrix_power(P, 50)[0])
Raising the matrix to a high power forces every row toward the same answer. FYI, this convergence only happens when the chain can reach every state and doesn't cycle in a rigid pattern. Most friendly examples behave, but you can build chains that don't.
Build a Text Generator
Now for the fun one. A text generator treats each word as a state. The transition probabilities come from counting which words follow which in your training text.
Step 1: Build the Chain
from collections import defaultdict
def build_chain(text):
words = text.split()
chain = defaultdict(list)
for current, following in zip(words, words[1:]):
chain[current].append(following)
return chain
For every word, the code stores a list of the words that came after it. Duplicates stay in the list on purpose. If "coffee" follows "morning" four times and "sunshine" follows once, random choice picks "coffee" 80% of the time. No explicit probabilities needed.
Step 2: Generate Text
import random
def generate(chain, start, length=25):
word = start
output = [word]
for _ in range(length - 1):
options = chain.get(word)
if not options:
break
word = random.choice(options)
output.append(word)
return " ".join(output)
Feed build_chain a long text file, like a novel from Project Gutenberg or your own blog posts. Then call generate with a starting word. The chain stops early if it reaches a word that never had a successor, which usually means the last word of your text.
Why the Output Sounds Weird
Your first results will read like a sentence that lost its train of thought. That happens because the chain remembers only one word. It knows "the" often precedes "cat," but it has no clue what the sentence was about.
You fix this by raising the order of the chain. An order-2 chain uses the last two words as its state:
def build_chain_order2(text):
words = text.split()
chain = defaultdict(list)
for a, b, c in zip(words, words[1:], words[2:]):
chain[(a, b)].append(c)
return chain
IMO, order 2 is the sweet spot for small texts. Order 3 and above start copying your source almost word for word, because few unique continuations exist. Ever noticed how a small dataset makes a clever model look like a plagiarist? Same effect.
Markov Chains vs. Modern Language Models
Large language models do the same basic job: predict what comes next. So how do they differ from your Markov chain?
- Memory: a Markov chain sees one or two words, while a transformer reads thousands of tokens at once.
- Generalization: a Markov chain can only repeat patterns it saw, while a neural network learns abstract relationships.
- Cost: a Markov chain trains in seconds on a laptop, while a large model needs serious hardware.
- Transparency: you can read every probability in a Markov chain, but you can't do that with a neural network.
The Markov chain loses on quality, but it wins on simplicity and speed. I still reach for one when I need quick prototypes or lightweight autocomplete. :)
Where Markov Chains Show Up
You meet these models in more places than you'd expect:
- Google's PageRank treats a web surfer clicking random links as a Markov chain [3].
- Speech recognition historically used hidden Markov models to match sounds to words [4].
- Finance models use chains to describe credit ratings and market regimes.
- Game design uses them for procedural music, names, and dialogue.
- MCMC methods sample from complicated probability distributions in Bayesian statistics.
Different fields, same core trick: describe a messy process as probabilistic jumps between states. That MCMC line is the one that matters most in practice, because it is how the Bayesian network inference from my last post gets computed when exact answers are too expensive, and it is close cousin to the random walks in simulated annealing.
Common Beginner Mistakes
I made all of these, so you don't have to:
- Rows that don't sum to 1. Your simulation then crashes or quietly produces garbage. Always check.
- Forgetting dead ends. A word with no successor breaks text generation unless you handle it.
- Using too little training text. A chain trained on three sentences just recites those three sentences.
- Assuming memorylessness fits everything. Real weather depends on more than yesterday. If history matters, add it to your state.
Best Book to Read
| Cover | Book | Description | Get it |
|---|---|---|---|
![]() |
Markov Chains: From Theory to Implementation and Experimentation | a short, code-first treatment that walks through transition matrices, stationary distributions and real applications without burying you in measure theory [5]. | View on Amazon |
As an Amazon Associate I earn from qualifying purchases. Links on this page are affiliate links, and I may earn a commission at no extra cost to you.
Read it after your weather model converges. Watching a matrix power flatten into identical rows makes the stationary distribution chapter click in a way that a proof alone rarely does.
Wrapping Up
A Markov chain models a system as states plus transition probabilities, and it predicts the next step from the current state alone. You built two versions: a weather model that settles into a stable long-run pattern, and a text generator that mimics any source you feed it.
Pick a text you love and train a chain on it. Try orders 1, 2, and 3, and watch the output shift from gibberish to suspiciously familiar. Then email me the best sentence it produces. If it sounds more coherent than my morning meetings, I'll call that a win.
If you enjoyed watching probabilities turn into behaviour, the Monte Carlo Tree Search post takes the same idea into game playing, where random playouts get averaged into a decision.
Frequently Asked Questions
What is a Markov chain in plain English?
A Markov chain is a system that moves between states, where the chance of the next state depends only on the current one. It forgets the path that led here, which is why the rule is called memorylessness or the Markov property.
What is a transition matrix?
A transition matrix holds the probability of moving from each state to every other state. One row per current state, one column per next state, and every row must sum to exactly 1, because something has to happen next.
What is a stationary distribution?
A stationary distribution is the long-run share of time a chain spends in each state. Run the chain long enough and the starting state stops mattering; for the three-state weather example the shares settle near 46% sunny, 28% cloudy and 26% rainy.
Why does my Markov text generator produce nonsense?
An order-1 chain only remembers one word, so it can follow local word habits but has no idea what the sentence is about. Raising the order to two or three words fixes most of it, at the cost of copying longer stretches of the training text.
Are Markov chains still used, or are language models better?
Both are used, for different jobs. Markov chains train in seconds, need no GPU, and expose every probability, which makes them ideal for prototypes, simulation and teaching. Language models produce far better text but cost far more to run.
Sources
[1]Grinstead and Snell, Introduction to Probability (free textbook) - chapter 11 develops Markov chains from the original 1906 motivation, with exercises that match the weather example here: math.dartmouth.edu[2]J. R. Norris, Markov Chains (Cambridge, 1997) - the rigorous treatment of stationary distributions, irreducibility and convergence, for when the friendly version is not enough: doi.org[3]Brin and Page, The Anatomy of a Large-Scale Hypertextual Web Search Engine (1998) - the PageRank paper that models a random surfer as a Markov chain: infolab.stanford.edu[4]Lawrence Rabiner, A Tutorial on Hidden Markov Models and Selected Applications in Speech Recognition (1989) - the canonical introduction to the hidden-state version used in speech: ieeexplore.ieee.org[5]Paul A. Gagniuc, Markov Chains: From Theory to Implementation and Experimentation (2017) - worked implementations of transition matrices and long-run behaviour, including text-style examples: wiley.com
