Software Engineering

Two extractions tell you what is missing: estimating the total of an API that returns samples

When a source returns a different sample on every request, the overlap between two extractions estimates the total. Capture-recapture, Chapman's correction and the assumptions that mislead.

Rodrigo Lucas · · 11 min read

A public records API I was using for analysis always came back with the same round number of millions of rows. That looked odd to me, because real data rarely lands on such a round number, and a number like that is usually a server limit rather than the size of the world.

The suspicion turned out to be right. The API was returning only a sample of the table, and each request brought a different sample, so any number I computed depended on the day of the download. The way out came from ecology, from the method biologists use to count fish in a lake without draining the lake, where the overlap between two samples tells you how much is missing. The same calculation works for any source you cannot read in full, whether it is an API with a row cap, pagination that stops before the end, a sampled log or a scraper that never gets everything, as long as you remember that the estimate is only as good as the assumptions behind it.

How to tell the source returns a sample#

The round number was only the first sign, and a fairly silly one. The second showed up when I compared two extractions made two days apart. They swapped half of their rows, and the total for an entire year varied by 19% between one and the other. If it were just new data arriving, the old months would not change.

So I looked only at the keys present in both extractions and saw that, in the months already closed, the values were identical. The table behind it was stable and what changed was the cut, and the overlap between the two extractions was the size you would expect from two independent samples of the same table. The server drew those millions of rows anew on every request, which is why downloading again updated nothing.

The check fits in a few lines and only needs a stable key per record.

import pandas as pd

a = pd.read_csv("extraction_a.csv.gz")
b = pd.read_csv("extraction_b.csv.gz")

only_a = set(a.id) - set(b.id)
only_b = set(b.id) - set(a.id)
both = set(a.id) & set(b.id)

print(len(a), len(b))              # exact same size? suspicious
print(len(only_a), len(only_b), len(both))

# on the shared keys, does the content match?
shared = a[a.id.isin(both)].merge(b, on="id", suffixes=("_a", "_b"))
print((shared.value_a != shared.value_b).sum())  # 0 = stable table, varying cut

If the size is identical, the keys swap a lot and the content of the shared keys does not change, you are looking at different samples of a table that is standing still.

The idea that comes from ecology#

Imagine you want to know how many fish there are in a lake. You catch 100, mark each one and release them. Days later, you catch 120 and, of those, 20 are marked. If the fish mixed well, the proportion of marked fish in the second catch (20 out of 120, one sixth) should be similar to the proportion of marked fish in the whole lake (100 out of N), which puts N close to 600.

That is the Lincoln-Petersen estimator, named after a Danish biologist who marked fish in 1896 and an American who estimated bird populations from leg bands in 1930. The most common notation uses three counts.

  • n is how many were marked in the first capture;
  • K is how many were caught in the second;
  • k is how many in the second were already marked.
N ≈ n * K / k

What makes this work is that the overlap measures coverage, and coverage is what lets you know how much is missing without ever seeing what is missing. If the two samples barely intersect, each one saw a small slice of something large. If they intersect a lot, it is because both have already seen almost everything.

Chapman's correction for small overlap#

The original formula has two practical problems. If k is zero, it divides by zero, and with a small overlap it becomes unstable, because one recapture more or less changes the result a lot. In 1951, Chapman proposed an adjusted version, derived from the hypergeometric distribution, which is the one I usually use.

N ≈ (n + 1) * (K + 1) / (k + 1) - 1

For the variance, the formula used with the Chapman estimator is attributed to Seber (1970).

Var(N) ≈ (n + 1)(K + 1)(n - k)(K - k) / ((k + 1)^2 (k + 2))

With the variance you can put an interval around the number. That matters because, from here on, the total you publish is an estimate, and for a lot of analysis an estimate is enough, as long as it is called an estimate and comes with the interval next to the point, and in code the calculation looks like this.

import math

def chapman(n: int, K: int, k: int) -> tuple[float, float]:
    """Total estimate and standard error (Chapman 1951, Seber variance)."""
    N = (n + 1) * (K + 1) / (k + 1) - 1
    var = (n + 1) * (K + 1) * (n - k) * (K - k) / ((k + 1) ** 2 * (k + 2))
    return N, math.sqrt(var)

N, se = chapman(n=100, K=120, k=20)
print(round(N), round(N - 1.96 * se), round(N + 1.96 * se))

In the lake example, Chapman gives 581 instead of 600, because the correction pulls the estimate down when the overlap is small. With samples of millions of rows and overlaps of hundreds of thousands, the difference between the two formulas disappears, but Chapman's still does not break in the edge cases.

Applying it to data#

The translation is direct. Each record in the table behind the API is a fish, the primary key is the mark and each extraction is a fishing trip. Counting n, K and k becomes a COUNT with a JOIN.

With more than two samples, I treated the union of all previous ones as the first capture and the new sample as the second, so each round answers how much of what just arrived I already knew. It is practical, but it throws away information. Schnabel generalized the method to multiple captures in 1938, and there are models that allow a different capture chance per individual (log-linear, jackknife), with ready-made implementations in R.

-- n: keys already seen in the history
-- K: keys in the new sample
-- k: keys in the new sample that were already in the history
SELECT
  (SELECT count(*) FROM history)                         AS n,
  (SELECT count(*) FROM new_sample)                      AS K,
  (SELECT count(*) FROM new_sample s
     JOIN history h ON h.id = s.id)                      AS k;

After estimating, the new sample goes into the history, and coverage is how many distinct keys I already have divided by the estimated total. In my case, coverage went from 62% with one sample to 85% with two and 91.2% with three. Each new sample brought fewer unseen keys, which is what the math predicts, and that curve also tells you when to stop collecting. Each sample is a heavy request on someone else's server, so if the third brought 6 points of coverage and the fourth brought 1, the fifth is not worth the cost.

The history by key also solved a storage problem. Keeping each whole extraction would mean keeping snapshots that are always incomplete, of roughly 1 GB each. Merging by key (with validity columns, to record when each version of the row was seen), the database stores each record once and grows only with what is new. The side effect is that the numbers change as samples come in, and a report from today may diverge from one made next week. That is why it pays to note which extraction (id and date) produced each published number, so readers can reproduce it.

There is one question coverage does not answer. At 91.2%, I know there are about 9% of records I have never seen, but I do not know which ones. If the analysis depends on a small slice, such as a category or a customer, the coverage of that slice can be far from the average.

The assumptions and what happens when they fail#

The estimator is simple because the assumptions do the heavy lifting. The ecology literature lists four, and each has an equivalent in data.

The population has to be closed between captures, meaning no fish is born, dies, enters or leaves from one fishing trip to the next. In data, the table cannot change between one extraction and the next, and that is why I limited the count to months already closed. The current month still receives rows, and mixing the two makes a new row look "not recaptured", which inflates the total.

Two assumptions are about the mark, which must not fall off and has to be recorded correctly. A mark that does not fall off, in data, is a stable key. If the server generates a new id on every response, or if the key is derived from a field that changes, no row is recaptured and the total explodes, so before any calculation confirm that the same row comes back with the same key. Correct recording corresponds to deduplication and normalization, because a key read as a number in one extraction and as text in the other breaks the JOIN without any warning.

That leaves the assumption that fails the most, in ecology and in data, which is that every individual has the same chance of being caught. If some records come out more than others (because the draw is not uniform, or because the server favors some slice), the "easy to catch" ones appear in both samples, the overlap gets bigger than it should and the total comes out low. People who applied capture-recapture to software inspections ran into this, since defects have different chances of being found, and an evaluation with data from real inspections concluded that, with few reviewers, the underestimation can be large.

I felt this assumption in practice. On the third sample, the overlap was smaller than the first two predicted, and the estimated total rose by about 8%. The method was working, and the jump showed that the sample was less uniform than I assumed. The only way to know is to collect more and see whether the estimate stops moving.

There is also an implicit assumption, that the captures are independent. In the API I was using, after a timeout the next response usually came from the cache, and there was a day when the cache served the same response for more than six hours. Two "samples" that are the same response have 100% overlap, and the estimator concludes, with full confidence, that you have already seen everything. The collection started checking the cache headers before downloading and only accepted a new sample when the response had actually changed.

Validate against a number you did not compute#

A broken assumption does not show up in the formula, and what gave me the most confidence was comparing against a published total. In one slice, the total from a single sample matched the published number exactly. In two others, it was 18% and 43% below. That alone already exposed the API's cut, because a complete total would not be 43% below a published number for the same slice.

You still need the estimate, because an outside number rarely covers every slice the analysis needs. But it catches what the calculation alone lets through. A biased draw pulls the total down without leaving a trace in the counts, and only an independent reference shows the gap. So if there is an official statistic or a report with the total for some slice, it is worth bringing it into the analysis before you publish the first estimate.

References#

updated on

01 blog

related

02 blog

Who writes

Contact

Let's swap ideas

Get the next articles

No spam, one email when a new article ships. Unsubscribe anytime.