Markov chains: the transition matrix, the stationary distribution and PageRank
The Markov property, the transition matrix and the evolution of a distribution in a weather model, the stationary distribution and the ergodic theorem, Markov’s analysis of vowels applied to Mácha’s Máj, PageRank and text generation.
Series AI basics Part 38 of 52
- Map of artificial intelligence: what is what and how it all fits together
- A brief history of artificial intelligence: from Turing to language models
- Data, model, training, inference: the basic terms on a single example
- How to read mathematical notation: symbols, indices, sums and quantifiers
- Sets and relations: the building blocks of definitions in AI
- Functions and mappings: why every AI model is a function
- Logic and proofs: the rules AI reasons by
- Graphs and trees: the structure that both search and neural networks stand on
- Linear algebra for machine learning: vectors, matrices and why AI mostly multiplies
- Derivatives, the gradient and the chain rule: how a model finds out which way to learn
- Gradient descent: how a model learns
- What probability is: from rolling dice to the Kolmogorov axioms
- Conditional probability and Bayes’ theorem: how to update your estimate when you learn something new
- Random variables and the cumulative distribution function: one function that tells you everything about a distribution
- Probability density and probability mass functions: why a continuous variable has zero probability at a point
- Expected value, variance and covariance: where a distribution lies, how wide it is and what goes with what
- Overview of probability distributions: Bernoulli, binomial, Poisson, uniform, normal and exponential
- Law of large numbers and central limit theorem: why averages behave so predictably
- Statistics and parameter estimation: maximum likelihood, MAP and confidence intervals
- Information theory: entropy, cross-entropy and KL divergence — where loss functions come from
- State-space search: BFS, DFS, UCS and A* with animations
- Games and adversaries: minimax, alpha-beta pruning and Monte Carlo tree search
- Constraint satisfaction: backtracking, constraint propagation and AC-3 on sudoku and a map of Czech regions
- Logic and knowledge systems: forward and backward chaining, resolution and expert systems
- Planning: STRIPS, the blocks world, heuristics from relaxation and planning in AI agents
- Local search and simulated annealing: a travelling salesman through the Czech regional capitals
- Genetic algorithms: population, crossover, mutation and selection on a backpack for a hike
- Evolution strategies and genetic programming: from the one-fifth rule to Kepler’s law
- Ant colony optimization: how a pheromone trail finds a short path
- Particle swarm optimisation: inertia, personal experience and the swarm’s experience
- Neuroevolution: evolving the weights and shape of neural networks, and the NEAT algorithm
- Fuzzy sets and membership functions: how to write down “somewhat warm”
- Fuzzy logic and probability: why “somewhat warm” does not mean “probably warm”
- Fuzzy logic: t-norms, implications and IF–THEN rules
- Fuzzy control: Mamdani and Sugeno from a fan to a pole on a cart
- Fuzzy clustering: the fuzzy c-means algorithm and points between clusters
- Neuro-fuzzy systems (ANFIS): fuzzy rules that learn from data
- Markov chains: the transition matrix, the stationary distribution and PageRank
- Hidden Markov models: the Viterbi algorithm and the dishonest casino
- Bayesian networks: why the grass is wet and what it means for the sprinkler
- The Kalman filter: how to estimate where a car is and how fast it goes from imprecise measurements
- Types of machine learning: supervised, unsupervised, semi-supervised and more
- Prompts, context and RAG: how to give a model the right information
- Variational autoencoders (VAE): new images from a continuous latent space
- Generative adversarial networks (GAN): the forger versus the detective
- Diffusion models: how pure noise becomes an image
- Markov decision processes: states, actions, rewards and the Bellman equations
- Q-learning and DQN: learning the value of actions, from a table to a neural network
- Policy gradient and PPO: learning the policy directly
- How an AI agent works: a language model in a loop with tools
- Programming with AI agents: the task, tests and review
- Evaluating and securing AI systems: how to measure and how to keep watch
Full series syllabus 52 of 83 topics published
- What the Markov property is and how a transition matrix describes the whole chain.
- Why an irreducible chain settles on its stationary distribution regardless of where it starts.
- How PageRank grew out of Markov chains and what they have in common with language models.
Useful to know first: Conditional probability and Bayes’ theorem: how to update your estimate when you learn something new, Linear algebra for machine learning: vectors, matrices and why AI mostly multiplies
In 1913 the Russian mathematician Andrey Markov sat over Pushkin’s Eugene Onegin and did something a literary scholar would call barbaric: he counted how often a vowel is followed by another vowel. He wanted to show that the law of large numbers holds even for events that depend on each other — and along the way he invented a model that today ranks pages in a search engine, forecasts the weather, generates text and stands behind a whole family of artificial intelligence algorithms. This part opens the module on probabilistic models.
It follows on from the parts Conditional probability and Bayes’ theorem and Linear algebra for machine learning.
1. A process without memory
Definition — Markov chain
Let (Ω, 𝓕, P) be a probability space, S a finite non-empty set (the set of states) and X0, X1, X2, … : Ω → S a sequence of random variables (Xt is the state at time t ∈ ℕ0). The sequence (Xt)t ≥ 0 is a Markov chain if and only if for every t ∈ ℕ0 and all states i0, …, it−1, i, j ∈ S such that P(Xt = i, Xt−1 = it−1, …, X0 = i0) > 0 the Markov property holds:
P(Xt+1 = j | Xt = i, Xt−1 = it−1, …, X0 = i0) = P(Xt+1 = j | Xt = i).
A Markov chain is homogeneous if and only if there are numbers pij ∈ [0, 1] (i, j ∈ S) such that
P(Xt+1 = j | Xt = i) = pij for all t ∈ ℕ0 and i, j ∈ S with P(Xt = i) > 0.
In words: the distribution of the next state depends only on the current state, not on the path by which the chain got there; for a homogeneous chain it does not depend on the time t either. The distribution π0(i) = P(X0 = i) is called the initial distribution.
The future depends only on the present, not on how we got there. Whoever knows today’s state knows everything about tomorrow that can be known — history adds nothing more. It is a simplification, but a very useful one: instead of the whole past you only need to remember one number.
What the Markov property buys you shows in the probability of a whole trajectory. In general it factors by the chain rule into a product of conditional probabilities, each of which depends on the entire past. The Markov property strikes everything except the last state out of each condition:
P(X0 = x0, …, XT = xT) = π0(x0) · ∏t=1T P(xt | xt−1)
- P(X0 = x0, …)
- the probability that the chain goes through exactly this sequence of states
- π0(x0)
- the initial distribution — the matrix does not say where the chain starts; this has to come from outside
- ∏t=1T
- a product over the steps — the steps follow one another and each one has to “work out”, which is why they multiply
- P(xt | xt−1)
- the transition probability of one step, i.e. the entry of the transition matrix in row xt−1 and column xt — thanks to the Markov property it depends only on the previous state, not on the whole history; without it this would read P(xt | x0, …, xt−1)
2. The transition matrix
Definition — transition matrix
Let n ≥ 1. A matrix A = (aij) ∈ ℝn×n is stochastic if and only if
- aij ≥ 0 for all i, j ∈ {1, …, n};
- ∑j=1n aij = 1 for every i ∈ {1, …, n} (every row sums to 1).
Let (Xt)t ≥ 0 be a homogeneous Markov chain with set of states S = {1, …, n} and the numbers pij from the definition above. Its transition matrix is
P = (pij)i,j=1n ∈ ℝn×n, pij = P(Xt+1 = j | Xt = i).
The transition matrix is stochastic: for a fixed i the row (pi1, …, pin) is the probability distribution of the state Xt+1 given Xt = i. Conversely, every stochastic matrix together with an initial distribution π0 determines a homogeneous Markov chain. (Using the same letter P for probability and for the matrix is standard; the context always makes clear which is which.)
A row of the matrix is “what happens tomorrow if today is this”. It has to add up to one, because something has to happen tomorrow.
A toy weather model with three states: after a sunny day it is sunny again with probability 0.6, cloudy with 0.3 and rainy with 0.1; after a cloudy day 0.3, 0.4, 0.3; after a rainy one 0.2, 0.4, 0.4 (always in the order sunny, cloudy, rain). As a graph:
The same information as a matrix — the row is today’s weather, the column tomorrow’s:
| Today ↓ / tomorrow → | sunny | cloudy | rain | row sum |
|---|---|---|---|---|
| sunny | 0.6 | 0.3 | 0.1 | 1 |
| cloudy | 0.3 | 0.4 | 0.3 | 1 |
| rain | 0.2 | 0.4 | 0.4 | 1 |
Example — the probability of one trajectory
Today is sunny (π0 = (1, 0, 0)). What is the probability that the next three days will be sunny, cloudy, rain? By the formula for a trajectory
P = π0(sunny) · psunny→sunny · psunny→cloudy · pcloudy→rain = 1 · 0.6 · 0.3 · 0.3 = 0.054
(colours as in the formula for a trajectory above).
That is 5.4%. The sum over all 33 = 27 possible triples of days is 1 — precisely because every row of the matrix sums to 1.
3. How the distribution evolves
Theorem — distribution after t steps
Let (Xt)t ≥ 0 be a homogeneous Markov chain with set of states S = {1, …, n} and transition matrix P ∈ ℝn×n. For t ∈ ℕ0 let πt = (πt(1), …, πt(n)) ∈ ℝ1×n be the row vector of the distribution of Xt, i.e. πt(i) = P(Xt = i). Then for every t ∈ ℕ0
- πt+1 = πt P, i.e. πt+1(j) = ∑i=1n πt(i) pij for every j ∈ S;
- πt = π0 Pt;
- for every m ∈ ℕ and i, j ∈ S with P(Xt = i) > 0, P(Xt+m = j | Xt = i) = (Pm)ij.
So the entry (i, j) of the matrix Pm is the probability of moving from i to j in m steps. Point 1 is the law of total probability with the partition by the value of Xt; point 2 follows from it by induction.
If today is sunny, tomorrow’s distribution is (0.6, 0.3, 0.1). The day after it is the average of the matrix rows weighted by this distribution — (0.47, 0.34, 0.19). One matrix multiplication per day, nothing more.
πt+1(j) = ∑i πt(i) · pij
- πt+1(j)
- the probability that tomorrow the state will be j — one component of the new row vector
- ∑i
- a sum over all of today’s states — you can reach j from anywhere and these paths exclude each other, so their probabilities add up (the law of total probability)
- πt(i)
- how likely it is that today we are in i — the weight of the path through i
- pij
- the probability of moving from i to j — by the Markov property, today’s state is all you need to know
Example — the distribution for the day after tomorrow
Tomorrow (after a sunny today) π1 = (0.6, 0.3, 0.1). For the day after tomorrow, component by component — a column of the matrix multiplied by the vector π1:
- sunny: 0.6 · 0.6 + 0.3 · 0.3 + 0.1 · 0.2 = 0.36 + 0.09 + 0.02 = 0.47,
- cloudy: 0.6 · 0.3 + 0.3 · 0.4 + 0.1 · 0.4 = 0.18 + 0.12 + 0.04 = 0.34,
- rain: 0.6 · 0.1 + 0.3 · 0.3 + 0.1 · 0.4 = 0.06 + 0.09 + 0.04 = 0.19.
In each line the first factor is π1(i) and the second pij (colours as in the formula above). The sum is 1 again. In three days the same procedure gives (0.422, 0.353, 0.225).
An interesting thing: after about a week it does not matter whether the sun is shining or it is raining today. Both distributions meet at the same values and do not change any further. The chain has “forgotten” where it started.
Theorem — how fast the chain forgets
Let P ∈ ℝn×n (n ≥ 2) be the transition matrix of a homogeneous Markov chain and assume that
- P has n mutually distinct (in general complex) eigenvalues λ1, …, λn, numbered so that λ1 = 1 and |λ2| ≥ |λ3| ≥ … ≥ |λn|;
- |λk| < 1 for all k = 2, …, n.
For k = 2, …, n let uk ∈ ℂ1×n be a left eigenvector belonging to λk (ukP = λkuk), and let π ∈ ℝ1×n be the left eigenvector belonging to λ1 = 1 whose components sum to 1 — the stationary distribution (definition below). Then for every initial distribution π0 there are numbers a2, …, an ∈ ℂ such that for all t ∈ ℕ0
πt = π0Pt = π + a2λ2tu2 + … + anλntun.
Reason. Eigenvectors belonging to distinct eigenvalues form a basis, so π0 = a1π + ∑k≥2 akuk, and multiplying by Pt multiplies the k-th component by λkt. For k ≥ 2 the components of uk sum to 0 (from ukP1 = uk1, where 1 is the column of ones, and λk ≠ 1), so comparing the sums gives a1 = 1.
The deviation πt − π therefore shrinks to zero roughly like |λ2|t, where λ2 is the second largest eigenvalue in absolute value.
πt ≈ π + a2u2 · λ2t
- πt
- the distribution after t days
- π
- the stationary distribution — it belongs to the eigenvalue 1, which does not change when raised to a power; that is why it is the only part that survives
- a2u2
- the initial deviation in the direction of the second eigenvector — this is the only place where it shows where the chain started (sun or rain); in the sunny component it is positive for a sunny start and negative for a rainy one
- λ2t
- every day the deviation is multiplied by λ2 — the speed of forgetting; the remaining terms with smaller |λ| vanish even faster, which is why we may leave them out
Example — the eigenvalues of the weather matrix
The sum of the eigenvalues is the trace of the matrix, 0.6 + 0.4 + 0.4 = 1.4, and their product is the determinant, which comes out as 0.01. One eigenvalue is 1 (the rows sum to 1), so the other two satisfy λ2 + λ3 = 0.4 and λ2λ3 = 0.01. They are the roots of λ2 − 0.4λ + 0.01 = 0:
λ2,3 = 0.2 ± √0.03 = 2 ± √3/10, so λ2 ≈ 0.373 and λ3 ≈ 0.027.
The deviation of the probability of sunshine from its stationary value 0.393, for a sunny start, is 0.0286, 0.0107 and 0.0040 after 3, 4 and 5 days — each day about 0.373 times smaller (colours as in the formula above). After a week it is 0.0006, and −0.0005 for a rainy start: the two beginnings differ only in the fourth decimal place. The deviation shrinks to one hundredth in t days, where 0.373t = 0.01, so
t = ln 0.01/ln 0.373 ≈ 4.7 days.
4. The stationary distribution
Definition — stationary distribution
Let P = (pij) ∈ ℝn×n be the transition matrix of a homogeneous Markov chain with set of states S = {1, …, n}. A row vector π = (π1, …, πn) ∈ ℝ1×n is a stationary distribution of the chain if and only if
- πj ≥ 0 for every j ∈ S and ∑j=1n πj = 1 (π is a distribution on S);
- π P = π, i.e. πj = ∑i=1n πi pij for every j ∈ S.
Condition 2 says that π is a left eigenvector of the matrix P with eigenvalue 1. In words: if X0 has the distribution π, then by the theorem on the distribution after t steps every Xt has the distribution π too — a step of the chain does not change the distribution.
Definition — irreducible and aperiodic chain
Let (Xt)t ≥ 0 be a homogeneous Markov chain with a finite set of states S and transition matrix P. For i, j ∈ S and m ∈ ℕ let pij(m) = (Pm)ij denote the probability of moving from i to j in m steps.
- The chain is irreducible if and only if ∀ i, j ∈ S ∃ m ∈ ℕ : pij(m) > 0.
- Let i ∈ S be a state for which the set R(i) = {m ∈ ℕ : pii(m) > 0} is non-empty. The period of the state i is d(i) = gcd R(i), the greatest common divisor of the lengths of all paths that return to i.
- A state i is aperiodic if and only if d(i) = 1. The chain is aperiodic if and only if all its states are aperiodic.
In an irreducible chain all states have the same period, so it is enough to check one state.
The weather is both straight away: all entries of P are positive (m = 1 suffices) and pii > 0, so a return is possible in 1 step and the period is 1. By contrast, a chain with two states that regularly alternates between them (p12 = p21 = 1) is irreducible but has period 2: π0Pt for the start (1, 0) keeps jumping between (1, 0) and (0, 1) forever, even though the stationary distribution (½, ½) exists.
Theorem — the ergodic theorem for finite chains
Let (Xt)t ≥ 0 be a homogeneous Markov chain with a finite set of states S = {1, …, n} and transition matrix P that is irreducible and aperiodic. Then
- the chain has exactly one stationary distribution π = (π1, …, πn), and πj > 0 for every j ∈ S;
- for every initial distribution π0, limt→∞ π0Pt = π (componentwise);
- for every initial distribution and every state j ∈ S, with probability 1 limT→∞ |{t ∈ {0, …, T − 1} : Xt = j}|/T = πj, i.e. the fraction of time spent in state j tends to πj;
- for every state j ∈ S the mean return time to j is mj = E[min{t ≥ 1 : Xt = j} | X0 = j] = 1/πj.
If every kind of weather can sooner or later lead to every other and the chain does not go round in a regular circle, it settles on one distribution — regardless of where it began. The stationary distribution also tells you what share of days over a long period will have which weather.
For our model the stationary distribution comes out exactly as (24/61, 22/61, 15/61) ≈ (0.393, 0.361, 0.246): in the long run 39% of days are sunny, 36% cloudy and it rains on 25%. After a rainy day we wait for the next rain 1/0.246 ≈ 4.07 days on average.
Example — the stationary distribution of the weather by hand
We are looking for π = (a, b, c) with πP = π. Column by column of the matrix:
- a = 0.6a + 0.3b + 0.2c, so 4a = 3b + 2c,
- b = 0.3a + 0.4b + 0.4c,
- c = 0.1a + 0.3b + 0.4c, so 6c = a + 3b.
The equations are dependent (adding all three gives a + b + c = a + b + c), so we drop the middle one. From the third, a = 6c − 3b; substituting into the first gives 24c − 12b = 3b + 2c, so b = 22c/15 and a = 6c − 66c/15 = 24c/15. The ratio is a : b : c = 24 : 22 : 15, and the condition a + b + c = 1 gives
π = (24/61, 22/61, 15/61) ≈ (0.393, 0.361, 0.246).
By the ergodic theorem, the mean return time to rain is mrain = 1/πrain = 61/15 ≈ 4.07 days.
And a simulation of one random run shows the ergodic theorem in action:
| Simulation | sunny | cloudy | rain |
|---|---|---|---|
| 30 days | 0.533 | 0.333 | 0.133 |
| 1 year (365 days) | 0.411 | 0.356 | 0.233 |
| 10 years (3,650 days) | 0.401 | 0.360 | 0.239 |
| stationary distribution | 0.393 | 0.361 | 0.246 |
The simulation draws each day separately from the row of today’s state: a random number u from [0, 1) is compared with the running sums of the row. After a sunny day u < 0.6 leads to sunny, 0.6 ≤ u < 0.9 to cloudy and the rest to rain:
stav = sunny
for den in 1 … N:
u = random number from [0, 1)
j = 0
while u ≥ P[stav][j]: # subtract probabilities until u “falls” into a bin
u = u − P[stav][j]
j = j + 1
stav = j
počet[stav] += 1
podíly = počet / N # by the ergodic theorem → π
The stationary distribution itself can be computed without any drawing, by repeated multiplication by the matrix:
import numpy as np
P = np.array([[0.6, 0.3, 0.1],
[0.3, 0.4, 0.3],
[0.2, 0.4, 0.4]])
pi = np.ones(3) / 3
for _ in range(100): # power method: π ← π P
pi = pi @ P
print(pi.round(3)) # [0.393 0.361 0.246]
5. Markov, Onegin and Máj
Markov went through the first 20,000 letters of Eugene Onegin and marked each one as a vowel or a consonant. 43.2% of them were vowels. If the letters followed one another independently, a vowel would follow a vowel in 43.2% of cases too. But Markov counted only 12.8%, while after a consonant it was 66.3%. The letters depend on each other — and yet the share of vowels in a long text reliably converges. That was his proof that the law of large numbers does not need independence.
Let us repeat it on the first stanza of Máj (May), the poem by Karel Hynek Mácha (“Byl pozdní večer – první máj…”). It has 311 letters, 37.6% of them vowels. The estimate of the transition matrix from the counts of pairs:
| After a… | vowel | consonant |
|---|---|---|
| vowel | 0.051 | 0.949 |
| consonant | 0.575 | 0.425 |
The stanza contains only 6 pairs of vowels in a row — Czech likes to alternate them with consonants even more than Russian does. And the stationary distribution of this chain comes out at 37.7% vowels: a chain estimated from the text “settles” practically on the share that is actually in the text (the only difference comes from the first and the last letter).
p̂ij = nij/∑k nik
- p̂ij
- the estimate of the transition probability — the hat says that it is a number computed from data, not the true value
- nij
- how many times in the text i was directly followed by j — we count pairs of neighbouring letters, because a Markov chain looks only one step back
- ∑k nik
- how many times i was followed by anything — dividing makes the row sum to 1, as a stochastic matrix requires
Example — counting pairs in the first stanza
311 letters give 310 neighbouring pairs. Vowel–vowel 6, vowel–consonant 111, consonant–vowel 111, consonant–consonant 82. Hence
p̂vow→vow = 6/117 = 0.051, p̂vow→con = 111/117 = 0.949,
p̂con→vow = 111/193 = 0.575, p̂con→con = 82/193 = 0.425
(colours as in the formula above; 117 = 6 + 111 pairs start with a vowel, 193 = 111 + 82 with a consonant).
A chain with two states has a stationary distribution given by a simple formula:
πvow = pcon→vow/pvow→con + pcon→vow
- πvow
- the long-run share of vowels
- pcon→vow
- the flow into vowels — the more often a consonant is followed by a vowel, the more vowels there are
- pvow→con
- the flow out of vowels — the faster the text leaves a vowel, the fewer of them there are
Example — Máj and Onegin by the formula
Máj (colours as in the formula above):
πvow = 0.575/0.949 + 0.575 = 0.377.
More precisely: there are as many vowel→consonant transitions as consonant→vowel ones (111), so
πvow = 111/193/111/117 + 111/193 = 1/193/117 + 1 = 117/310.
The actual share of vowels is 117/311 — it differs only in the denominator, because the last letter of the stanza (“r”) starts no pair.
Onegin: from Markov’s numbers (a vowel after a vowel 12.8%, so vowel→consonant 87.2%; a vowel after a consonant 66.3%) we get
πvow = 0.663/0.872 + 0.663 = 0.432
— exactly the 43.2% of vowels that Markov counted directly.
6. PageRank: the random surfer
In 1998 Sergey Brin and Larry Page, the founders of Google, proposed a way to rank web pages by importance. They imagined a surfer who clicks on links at random and asked: on which pages will they spend the most time?
Definition — PageRank
Let N ≥ 1 be the number of pages, numbered 1, …, N, and let L ⊆ {1, …, N} × {1, …, N} be the set of links: (i, j) ∈ L if and only if page i links to page j. For every page i let ki = |{j : (i, j) ∈ L}| be the number of its outgoing links, and let d ∈ (0, 1) be the damping factor (usually d = 0.85). The random surfer chain is the homogeneous Markov chain with states {1, …, N} and transition matrix P = (pij), where
- pij = 1 − d/N + d/ki, if (i, j) ∈ L;
- pij = 1 − d/N, if ki ≥ 1 and (i, j) ∉ L;
- pij = 1/N for all j, if ki = 0 (a page without links — the surfer jumps anywhere).
Every row sums to ki · d/ki + N · 1 − d/N = 1 (or N · 1/N = 1), so the matrix is stochastic. PageRank is the stationary distribution PR = (PR(1), …, PR(N)) of this chain, i.e. PR · P = PR and ∑j PR(j) = 1.
In words: with probability d the surfer clicks on one of the links of the current page (all equally likely), otherwise they jump to any of the N pages. Because all pij > 0, the chain is irreducible and aperiodic, and by the ergodic theorem PageRank is unique.
An important page is one that important pages link to. The definition looks circular, but the stationary distribution resolves it: it is exactly “how much time I will spend there if I keep clicking forever”. The occasional jump to anywhere stops the surfer from getting stuck in a small ring of pages.
The highest is C (0.374), which almost every page links to. A is more interesting: it has a single incoming link and is still second (0.342) — because that link comes from C, and C links nowhere else. B, which only A links to, gets half of A’s weight (0.171). Pages D, E and F, which mostly link to one another, stay around 0.04. The real PageRank computed the same thing for billions of pages, with the power method.
The equation π = πP written out for one page gives the familiar form of PageRank:
PR(j) = 1 − d/N + d ∑i→j PR(i)/ki
- PR(j)
- the PageRank of page j — the share of time the surfer spends on it; the sum over all pages is 1
- 1 − d/N
- the contribution of random jumps — every page gets the same amount, even one that nothing links to; thanks to it the chain is irreducible and aperiodic
- d
- the probability that the surfer clicks on a link instead of jumping elsewhere — 0.85 in the original paper by Brin and Page
- ∑i→j
- a sum only over the pages that link to j — a link is a “vote” for the target page
- PR(i)/ki
- the vote of page i weighs as much as i itself is important, and it is split among all its ki links — a page with a thousand links gives each of them very little
Example — checking A, B and C
For N = 6 and d = 0.85, 1 − d/N = 1 − 0.85/6 = 0.025. Only the link from C leads to A, and C has a single link (kC = 1); only the link from A leads to B, and A has two (colours as in the formula above):
- PR(A) = 0.025 + 0.85 · 0.37351/1 = 0.34248,
- PR(B) = 0.025 + 0.85 · 0.34248/2 ≈ 0.1706,
- PR(C) = 0.025 + 0.85 · (PR(A)/2 + PR(B)/1 + PR(D)/2 + PR(E)/3 + PR(F)/1) = 0.025 + 0.85 · 0.41001 = 0.37351.
The values from the power method satisfy the equation — that is how you can tell the iteration has finished.
PR = [1/N] * N # start uniformly
repeat:
nové = [(1 − d)/N] * N # random jumps
for i in stránky:
if i has no links: # dead end: jump anywhere
nové[j] += d · PR[i]/N for all j
else:
for j in odkazy[i]:
nové[j] += d · PR[i]/k_i
PR = nové
until PR barely changes
7. Chains, text and language models
A chain whose states are letters can be left to generate. From the pairs of letters in the first stanza of Máj we estimate what follows which letter, and then we draw at random. This is what 90 characters look like:
lal kou lasvavzvný dnkyl plásnětičaskol dnou ta javu snáscezepráro pl h jin trů bo kylalav
Nonsense — but nonsense that “sounds Czech”: it alternates vowels and consonants, has short words and syllables such as “lás” or “kol”. Claude Shannon did the same experiment with English in 1948 and showed that with a longer context (triples of letters, pairs of words) the text looks more and more natural.
Example — the “l” row of the bigram model
We convert the text of the stanza to lower case and replace punctuation with a space. In it, the letter “l” is followed by another character 31 times: 13 times by a space, 7 times by “a”, 6 times by “á”, twice by “o” and once each by “i”, “h”, “u”. By the estimation formula, then,
P(space | l) = 13/31 ≈ 0.42, P(a | l) = 7/31 ≈ 0.23, P(á | l) = 6/31 ≈ 0.19,
P(o | l) = 2/31 ≈ 0.06 and the others 1/31 ≈ 0.03
(colours as in the estimation formula for p̂ij in the section on Máj).
Generation then does the same as the weather simulation: from the row of the current character it draws the next character. After “l” the word is most often at its end — “byl”, “lhal”, “kol”, “bol”.
Definition — n-gram model
Let V be a finite non-empty set of symbols (the vocabulary) and n ≥ 2 an integer. An n-gram model of order n is a collection of probability distributions q(· | v) on V, one for every context v = (v1, …, vn−1) ∈ Vn−1. A sequence of symbols W1, W2, … with values in V is generated by the model so that for every t ≥ n and w ∈ V
P(Wt = w | W1, …, Wt−1) = q(w | Wt−n+1, …, Wt−1),
i.e. the next symbol depends only on the n − 1 previous ones. The sequence Yt = (Wt−n+2, …, Wt) ∈ Vn−1 (t ≥ n − 1) is then a homogeneous Markov chain with set of states Vn−1: its state is the last n − 1 symbols. For n = 2 (bigrams) the state is a single symbol and q(w | v) is directly the transition probability pvw.
The memory of a chain can be “stretched” by packing more of the past into the state. A language model with a context window is formally a Markov chain too: its state is the whole text in the window. The difference is that there are astronomically many states, so the transition probabilities are not in a table but are computed by a neural network.
Example — how many states an n-gram model has
With a vocabulary of V symbols, an n-gram model has |V|n−1 states and |V| probabilities in each row. The stanza of Máj uses 32 different characters (letters and the space):
- bigrams (n = 2): 32 states, a 32 × 32 matrix = 1,024 numbers — more than the stanza has characters, so most of them come out as zero;
- trigrams: 322 = 1,024 states and over 32 thousand numbers — the stanza does not contain most pairs of letters at all, and their rows stay empty;
- a language model with a vocabulary of 50,000 tokens and a window of 1,000 tokens: 50,0001,000 ≈ 104,699 states.
That is why a longer context needs either enormous data or a model that does not take the probabilities from a table but estimates them with a function — a neural network.
8. Where Markov chains lead
- Hidden Markov models — what if we cannot see the state, only its effects? That is the subject of the next part.
- Markov decision processes add actions and rewards: reinforcement learning is built on them.
- Markov chain Monte Carlo methods (MCMC) construct a chain whose stationary distribution is the one we want to sample from — typically a posterior distribution in Bayesian statistics. The Metropolis criterion from the part on simulated annealing is exactly such a chain.
9. Summary
- A Markov chain has no memory: the next state depends only on the current one. It is described by a stochastic transition matrix P.
- The distribution evolves by multiplication by the matrix, πt = π0 Pt.
- An irreducible aperiodic chain settles on a unique stationary distribution π = π P, regardless of the start; for the weather (0.393, 0.361, 0.246).
- Markov demonstrated the dependence of letters on Onegin; in Máj a vowel follows a vowel in only 5% of cases.
- PageRank is the stationary distribution of the random surfer; n-gram models and today’s language models alike are Markov chains with a large state.
Want to get your hands on it? Have an AI agent build a word bigram model from the whole of Máj or from your own e-mails and generate sentences from it — and then try trigrams.
Do you see it differently? Write to support@coden-app.com.