Zipf's and Heaps' Laws: The Statistics of Vocabulary
Why a vocabulary's rank–frequency curve and its growth curve are one power law seen twice — and why a straight line through a log–log plot is the wrong way to measure it
Overview & Motivation
Count the words in any body of text and two shapes appear. Sort the word types from most to least frequent and plot each type’s count against its rank on log–log axes: the points fall near a straight line of negative slope. That is Zipf’s law, . Now read the same text from the beginning and track how many distinct types we have seen after tokens: on log–log axes this growth curve is also nearly straight, with slope below one. That is Heaps’ law, .
The site’s shared finance corpus — 300 synthetic earnings calls, MD&A sections, and 8-K filings — is a good place to look. It has tokens and types, and of those types occur exactly once. Its ten most frequent words are and, in, the, of, for, percent, to, as, a, was: a handful of function words carries a large share of the text ( of tokens; the top hundred words carry ), while most of the vocabulary is rare. The table below samples the curve at log-spaced ranks.
| rank | 1 | 4 | 19 | 84 | 372 | 779 | 1634 | 3425 |
|---|---|---|---|---|---|---|---|---|
| count | 3362 | 1060 | 363 | 160 | 29 | 6 | 1 | 1 |
These two laws are the first fact about text as data, and almost everything later on this site leans on them. A vocabulary that keeps growing is why subword tokenizers exist; the mass of once-seen words is why language models need smoothing; the heavy head is why stopword lists and IDF weighting work. This topic makes the two laws precise and asks three questions about them:
- Are they the same law? Yes, in a precise sense. The rank–frequency curve is the tail of the type-count distribution turned on its side, and under i.i.d. sampling a Zipf exponent forces a Heaps exponent (Karlin’s theorem).
- Where could they come from? Two answers: Zipf is the maximum-entropy law at a fixed mean log-rank, and the Pitman–Yor process generates both laws from a single discount parameter . That process is exactly how the finance corpus generates its content words.
- How do we measure them? Not by drawing a line through a log–log plot. We show how badly that goes, develop the maximum-likelihood alternative, and test both on a corpus where we know the right answer.
Before any algebra, try the laboratory. In panel A, pick different windows of ranks and watch the fitted slope of the same corpus swing from to . In panel B, turn the Pitman–Yor discount and watch one knob move both exponents.
One restaurant's level is random — K_n / n^d converges to a random limit — so the points can sit off the exact mean while their slope still tracks d. The naive slope ignores the θ/d offset of Theorem 3 and overshoots.
Rank–frequency is a tail turned sideways
Throughout, a corpus is a token sequence over a vocabulary of word types.
Definition 1 (Counts and ranks).
The count of a type is its number of tokens. Sorting the observed types by decreasing count gives the rank–frequency curve , with ties ordered arbitrarily.
Definition 2 (Frequency spectrum and tail count).
The frequency spectrum is , the number of types seen exactly times. The tail count is . Types with are the hapax legomena; there are of them.
In the finance corpus , , . The tail count is a staircase that starts at (every type) and steps down: , , . Draw that staircase with on the horizontal axis, then reflect it across the diagonal, and you get the rank–frequency plot. The next proposition says this is not an analogy but an identity.
Proposition 1 (Rank is the tail count).
If ties are ranked last, the rank of any type with count is . Equivalently, and are generalized inverses of each other.
Proof.
The types ranked at or above a type with are exactly the types with count greater than , together with every type whose count equals — ranking ties last places at the end of its tie block. Their number is , which is therefore the rank of .
∎The identity converts statements about the spectrum into statements about the rank plot. In particular it ties the two exponents together.
Corollary 1 (The exponent map α = 1 + 1/s).
If over a range of counts, then over the corresponding ranks : a rank–frequency exponent . If instead the spectrum itself is a power law, , then , with the same exponent.
Proof.
The first statement inverts Proposition 1: solves to . For the second, , where is the Hurwitz zeta function. Since decreases, comparing the sum with integrals gives
∎So a spectrum exponent and a rank exponent are two names for one number: . The companion harness checks Proposition 1 exactly on all corpus types, and checks the exponent map on -draw power-law samples with . We will use the map constantly, because the clean estimator in the final section works with counts while the classical picture is drawn with ranks.
Zipf as a probability law
To reason about sampling we need Zipf’s law as a distribution, not just a fitted curve.
Definition 3 (Zipf law).
For the Zipf law on the positive integers is with and . The truncated Zipf law on is with , for any real .
Proposition 2 (An infinite Zipf law needs s > 1).
if and only if . At the partial sums satisfy , where is the Euler–Mascheroni constant.
Proof.
For the terms are positive and decreasing, so by the integral test (see Series Convergence) the partial sum lies within of . That integral stays bounded as exactly when . For the terms do not tend to zero, so the series diverges. At , , and the gap between the sum and the integral decreases to the constant , with remainder .
∎This sets the stage for the first honest caveat. Fitted Zipf exponents for word frequencies in real text sit near — on exactly the boundary where an infinite vocabulary cannot be normalized. A Zipf law with must have a finite vocabulary, or a steeper tail somewhere beyond the ranks we can observe.
Why would word frequencies take this shape at all? One answer comes from information theory. Suppose all we fix is the mean of , which we can think of as a budget for how far down the ranking a typical token reaches. The least committal distribution with that budget is Zipf’s.
Theorem 1 (Zipf maximizes entropy at fixed mean log-rank).
Fix and . Among distributions on with , the Shannon entropy has a unique maximizer: the truncated Zipf law , where is the unique real solution of .
Proof.
The exponent exists and is unique. Let for the truncated Zipf law with exponent . Since is a log-partition function in , and . The variance is positive because is not constant on when , so is continuous and strictly decreasing. As the mass moves to and ; as it moves to and . Hence maps one-to-one onto .
Optimality. Let be any feasible distribution. Gibbs’ inequality — the nonnegativity of the KL divergence, (see Shannon Entropy & Mutual Information) — gives . Substituting ,
The same computation with shows that , so . Equality forces , that is .
∎The exponent is the Lagrange multiplier on the log-rank constraint: the price of spreading probability toward high ranks. The harness solves the constrained problem from scratch with a generic optimizer, for and (the mean log-rank of Zipf with ). Starting from the uniform distribution, the optimizer lands on the Zipf law to within , root-finding recovers to , and fifty random feasible perturbations of the Zipf law all lower the entropy. Maximum entropy explains the shape if we accept the constraint; it does not explain why language would fix . We take it as one well-defined route to the power law, not as a theory of language.
Zipf implies Heaps
Now we connect the two laws. Draw tokens independently from a Zipf law. Type is still unseen after draws with probability , so the expected vocabulary size is
Each term is close to for the common types (they are surely seen) and close to for the rare ones (they are probably unseen). The crossover happens near the rank where , that is . So the vocabulary should grow like . To make this exact we need one tool for comparing sums with integrals.
Lemma 1 (Sums of unimodal functions).
Let be integrable on , nondecreasing on and nonincreasing on , with . Then
If is nonincreasing (), then .
Proof.
Let . Lower bound: for , rises on , so ; for , falls on , so . These intervals cover except , whose integral is at most . Upper bound: for , ; for , . These intervals are disjoint, and the two remaining terms and are each at most . The monotone case is the same argument with : the upper bound uses for every , and the lower bound uses , which misses only .
∎Theorem 2 (Zipf implies Heaps (Karlin 1967)).
Let tokens be i.i.d. with , , , and set . Then
In particular and : Heaps’ law holds with , and the absolute error is at most about one word type.
Proof.
Step 0: the integral. Let and substitute , so and :
Integrate by parts with antiderivative for . The boundary term vanishes as , and as because and . What remains is (see Improper Integrals & Special Functions). Hence .
Step 1: Poissonize. Replace by . The function is decreasing with , so the monotone case of Lemma 1 gives .
Step 2: de-Poissonize. Since , we have , so . For the other side, , hence and
using . As a function of , is unimodal with maximum , and the substitution of Step 0 gives . Lemma 1 bounds by that integral plus , so . Combining with Step 1 gives both inequalities. Taking logarithms, , and .
∎The theorem is sharper than its usual statement: the error is about one type, not a vanishing fraction. The harness computes on the full infinite Zipf law (an exact sum over the first two million ranks plus the tail’s Taylor series) and checks each step: the Step 1 sandwich, the sign and size of the Step 2 gap, and the slope. The ratio looks like this:
| 1.25 | 0.9915 | 0.9986 | 0.9998 | 1.0000 | 1.0000 |
| 1.5 | 0.9847 | 0.9966 | 0.9992 | 0.9998 | 1.0000 |
| 2.0 | 0.9651 | 0.9887 | 0.9964 | 0.9989 | 0.9996 |
| 3.0 | 0.9165 | 0.9609 | 0.9818 | 0.9915 | 0.9961 |
Convergence is slowest for large . That is what the bound predicts: a one-type error weighed against types, which is a small vocabulary when is large.
Remark.
Heaps’ law needs an open vocabulary. Theorem 2 uses the infinite support in an essential way. A Zipf law truncated at types has , so its growth curve must flatten. With and , the expected vocabulary is , , , and at . The local log–log slope falls from above to below . A fixed word list cannot keep up with text whose vocabulary keeps growing — the problem that subword tokenization, a later topic, solves.
The same argument says how much of the vocabulary we have seen only once.
Corollary 2 (The hapax share estimates β).
Under the hypotheses of Theorem 2, the expected number of types seen exactly once is . Consequently .
Proof.
. In the Poissonized version each term is with , . As grows, falls from to and first rises and then falls, so is unimodal with maximum . The substitution of Step 0 gives , and Lemma 1 bounds the sum to within . To de-Poissonize,
using . Multiplying by and summing, the total error is at most with . By Lemma 1 and the same substitution, both sums are , so the error is . Dividing by Theorem 2’s gives the limit .
∎At the harness finds hapax shares , , and for , , and , against , , and . Once-seen words are not noise to discard. Their share measures the growth rate of the vocabulary, and their mass is what smoothing, a later topic, must reserve for words not yet seen.
Pitman–Yor plants both laws
Theorem 2 assumes a Zipf law. A generative model that produces one is more satisfying, and the Pitman–Yor process is the standard choice. It is also exactly how the site’s finance corpus generates its content words.
Definition 4 (Pitman–Yor restaurant).
Fix a discount and a strength . Customer sits at table . Given occupied tables with occupancies , customer
- opens a new table with probability , or
- joins table with probability .
Tables are word types and customers are tokens, so is the vocabulary after tokens. At this is the Chinese restaurant process of the Dirichlet process (see Bayesian Nonparametrics). The process is also defined for , but we need only .
The discount takes a little from every occupied table and gives it to the new-table probability. The more tables already exist, the more likely another one opens — rich vocabularies get richer. At new tables open at the rate , so the vocabulary grows only logarithmically. With it grows as a power.
Theorem 3 (Exact expected type count).
For and ,
As , , the Dirichlet-process rate, where is the digamma function.
Proof.
By Definition 4, . The right side is affine in , so taking expectations gives
Put . Then , and the recursion becomes with . Telescoping,
using . For the asymptotic, Lemma 2 below with gives , and . At the recursion reads , which sums to the stated series and its digamma form.
∎Lemma 2 (Wendel's inequality).
For and : . In particular as .
Proof.
Write and apply Hölder’s inequality with exponents and : . Applying the same inequality at the point with step gives , that is . Dividing by gives the lower bound, and both bounds tend to .
∎Read Theorem 3 carefully: it is , not , that is a clean power law, and its variable is , not . Write for Theorem 3’s constant. Then the ratio of the shifted count to is exactly Lemma 2’s middle term at , so it lies between and at every . As a power of itself it is clean only asymptotically. At and the shifted count is of at and from on, but above at and above at . The offset vanishes relative to eventually, but it is large at corpus scale — for the finance corpus’s restaurants (, ). There, , , , and at , which is only , , , and of the asymptote . The harness confirms the closed form solves the recursion to , matches Monte-Carlo means over 200 restaurants, and agrees with the corpus module’s own sampler.
What about Zipf? The rank–frequency limit is deeper, and we cite it rather than prove it.
Theorem 4 (Pitman–Yor limits (Pitman 2006)).
For a Pitman–Yor restaurant with , almost surely:
- , a strictly positive, finite random limit (the -diversity);
- the ranked table frequencies satisfy for a random — a Zipf law with ;
- the share of tables with exactly customers converges, (the Sibuya law), whose tail is .
These are Theorem 3.8, Corollary 3.9, and Lemma 3.11 of Pitman’s Combinatorial Stochastic Processes (2006). The proof runs through Kingman’s representation of exchangeable partitions and regular variation, which is beyond this topic. The harness checks the statements on restaurants of customers with . The block-size shares for fall within four binomial standard errors of . For the limits are , , , , . The fitted power-law spectrum exponent lands within of .
Everything now fits together. The Sibuya tail has spectrum exponent . By Corollary 1 that is a rank exponent — exactly item 2. Theorem 3 says — exactly what Theorem 2 requires of a Zipf law with that . And is Corollary 2’s hapax share. One parameter sets both laws. Panel B of the laboratory turns that parameter. Item 1 also explains something you will see there: a single restaurant’s type count follows with a random constant. Its points can sit visibly off the exact mean — at the displayed restaurant has types at , against an expected — while their slope still tracks .
Estimating the exponent
The classical recipe for “measuring Zipf’s law” is to fit a least-squares line to the log–log rank plot and report minus its slope. On the finance corpus, the answer depends heavily on which ranks we fit:
| ranks | 1–10 | 10–100 | 100–1000 | 1000–3425 | 1–1000 | 1–3425 |
|---|---|---|---|---|---|---|
| dense OLS slope | −0.871 | −0.554 | −1.807 | −0.821 | −1.300 | −1.464 |
These are the windows in panel A of the laboratory. The slope over ranks – is more than three times the slope over –. Nothing in the recipe says which window is correct. Least squares also assumes independent, equal-variance errors around the line, while neighboring points on a rank plot are strongly dependent and the tail is a staircase of tied counts. The method has no valid standard error to report.
The alternative, developed by Clauset, Shalizi, and Newman (2009), works with counts rather than ranks. By Corollary 1, a rank exponent corresponds to a spectrum exponent . So we model each type’s count as a draw from a discrete power law and estimate by maximum likelihood.
Definition 5 (Discrete power law).
For an integer and , the discrete power law is for , normalized by the Hurwitz zeta function .
Proposition 3 (The power-law MLE exists and is unique).
Let be type counts with log-likelihood . Then is strictly concave on and
If — that is, not every count equals — the maximum-likelihood estimate exists, is unique, and solves the score equation .
Proof.
is a log-partition function. Its first derivative is and its second is . Hence , and the score has the stated form. The map is continuous and strictly decreasing. As the mass concentrates on , so it tends to . As it tends to : for any level , the finitely many carry bounded total weight while , so the probability of tends to . Hence has exactly one root when , and by concavity it is the maximum.
∎With fixed, this is a one-parameter exponential family with sufficient statistic . Consistency and asymptotic normality, with Fisher information , follow from the general theory (see Maximum Likelihood Estimation). Clauset et al.’s working standard error is . The cutoff is chosen by minimizing the Kolmogorov–Smirnov distance between the empirical and fitted tail distributions — a sensible heuristic, not a theorem.
The harness checks the estimator against a reference implementation. On -draw samples with the MLE lands within four standard errors of the truth and agrees with scipy.stats.fit to . On the corpus, the score equation holds to for . It also measures the least-squares alternatives on 40 random power-law samples with (so ). Least squares on the log–log frequency histogram is badly biased, with mean error more than twenty times the MLE’s. Least squares on the rank plot does better, but its error is still more than twice the MLE’s (Simple & Multiple Linear Regression covers the assumptions both fits break). On the corpus’s full text, the KS rule selects and gives , so . In panel A that estimate is the fixed dashed line through , placed there by Proposition 1.
Finance case study: a corpus with a planted answer
Where this goes next
- Open vocabulary → subword units. The Remark after Theorem 2 shows that no fixed word list keeps up with Heaps growth. Subword tokenization, the next topic in this track, responds by making the vocabulary a set of reusable pieces.
- Once-seen mass → smoothing. Corollary 2 says roughly a fraction of the types seen so far are hapaxes. Their count divided by the number of tokens, , estimates how often the next token will be a word never seen before — the missing mass that Good–Turing estimation, in the later n-gram smoothing topic, assigns to unseen words. Kneser–Ney smoothing turns out to approximate a hierarchical Pitman–Yor model (Teh 2006) — the same discount , now at every context.
- The head → stopwords and IDF. The few types that dominate the rank plot are the stopword list. The long tail is where inverse document frequency is large (see The Vector Space Model and TF-IDF).
Honest caveats
Implementation
The companion notebook (notebookPath) imports zipf_heaps_vocabulary_statistics.py, which owns every number on this page. Running it as a script executes a harness of 27 assertion-based tests, one or more per claim, in about three seconds on a laptop CPU. The tests cover:
- Proposition 1 exactly, on every corpus type, and the exponent map of Corollary 1 on random samples.
- The convergence of , and the maximum-entropy theorem against a generic constrained optimizer.
- Each step of Karlin’s proof, the saturation of a finite vocabulary, and the hapax-share corollary.
- Theorem 3’s closed form against its recursion, Monte-Carlo means, and the finance corpus’s own sampler, plus the Sibuya shares of Theorem 4.
- The MLE against
scipy.stats.fit, its score equation, and its advantage over least squares. - The three beats of the finance case study.
The laboratory reads its data from a JSON file that one of those tests requires to equal the module’s viz_payload() exactly, so the figure cannot drift from the code.
References & Further Reading
- paper Central Limit Theorems for Certain Infinite Urn Schemes — Samuel Karlin (1967) Journal of Mathematics and Mechanics 17: 373–401. The occupancy asymptotics behind Theorem 2
- paper Notes on the Occupancy Problem with Infinitely Many Boxes: General Asymptotics and Power Laws — Alexander Gnedin, Ben Hansen, and Jim Pitman (2007) Probability Surveys 4: 146–71. A modern survey of Karlin's scheme
- paper The Two-Parameter Poisson–Dirichlet Distribution Derived from a Stable Subordinator — Jim Pitman and Marc Yor (1997) Annals of Probability 25 (2): 855–900
- book Combinatorial Stochastic Processes — Jim Pitman (2006) Lecture Notes in Mathematics 1875. Theorem 3.8, Corollary 3.9, and Lemma 3.11 give Theorem 4
- paper Power-Law Distributions in Empirical Data — Aaron Clauset, Cosma Rohilla Shalizi, and M. E. J. Newman (2009) SIAM Review 51 (4): 661–703. The discrete power-law MLE and the case against log–log least squares
- paper Zipf's Law, Power Laws and Maximum Entropy — Matt Visser (2013) New Journal of Physics 15 (4): 043021. Zipf as maximum entropy under a log constraint
- paper Note on the Gamma Function — J. G. Wendel (1948) American Mathematical Monthly 55 (9): 563–64. Lemma 2
- book Human Behavior and the Principle of Least Effort — George Kingsley Zipf (1949) Cambridge, MA: Addison-Wesley
- book Information Retrieval: Computational and Theoretical Aspects — H. S. Heaps (1978) New York: Academic Press
- paper A Formal Derivation of Heaps' Law — D. C. van Leijenhorst and Th. P. van der Weide (2005) Information Sciences 170: 263–72
- paper Two Regimes in the Frequency of Words and the Origins of Complex Lexicons: Zipf's Law Revisited — Ramon Ferrer i Cancho and Ricard V. Solé (2001) Journal of Quantitative Linguistics 8 (3): 165–73
- paper Zipf's Word Frequency Law in Natural Language: A Critical Review and Future Directions — Steven T. Piantadosi (2014) Psychonomic Bulletin & Review 21: 1112–30
- book Word Frequency Distributions — R. Harald Baayen (2001) Dordrecht: Kluwer. Large-number-of-rare-events statistics
- paper Producing Power-Law Distributions and Damping Word Frequencies with Two-Stage Language Models — Sharon Goldwater, Thomas L. Griffiths, and Mark Johnson (2011) Journal of Machine Learning Research 12: 2335–82
- paper A Hierarchical Bayesian Language Model Based on Pitman–Yor Processes — Yee Whye Teh (2006) COLING/ACL 2006, 985–92. Kneser–Ney as an approximation to hierarchical Pitman–Yor