TExcelTAD

The Labelling Loop: Active vs Random Sampling

The previous lesson showed that query strategies pick the examples a model gets wrong. That does not yet prove they save labels: a model trained on hard, unusual examples might generalise worse than one trained on a random sample. The only honest test is the full loop, run round by round against random sampling, with the accuracy measured on a fixed random test set. This lesson runs that experiment, reads the resulting learning curves, and adds the two things a real labelling loop needs: batches with diversity, and a rule for when to stop.

The loop as an experiment

L0=random seed set of n0 labels,U0=the rest of the poolfor r=0,1,⋯:fr=train⁡(Lr),record acc⁡(fr,test)Qr=the b examples of Ur with the highest score under frLr+1=Lr∪{(x,y):x∈Qr},Ur+1=Ur∖Qr\begin{aligned} &\mathcal{L}_0 = \text{random seed set of } n_0 \text{ labels}, \quad \mathcal{U}_0 = \text{the rest of the pool} \\ &\text{for } r = 0, 1, \dots: \quad f_r = \operatorname{train}(\mathcal{L}_r), \quad \text{record } \operatorname{acc}(f_r, \text{test}) \\ &\qquad Q_r = \text{the } b \text{ examples of } \mathcal{U}_r \text{ with the highest score under } f_r \\ &\qquad \mathcal{L}_{r+1} = \mathcal{L}_r \cup \{(\mathbf{x}, y) : \mathbf{x} \in Q_r\}, \quad \mathcal{U}_{r+1} = \mathcal{U}_r \setminus Q_r \end{aligned}

until ∣L∣\lvert \mathcal{L} \rvert reaches the budget. In a simulation the oracle is a lookup of the pool's known labels; in production it is an annotation tool and a person. The rules that make the comparison fair:

  • Same seed set for every strategy within a repetition, so they start from the same model.
  • A fixed random test set that is never in the pool. Active selection makes the labelled set unrepresentative, so it cannot be used for evaluation.
  • Several repetitions with different seeds, averaged. One run of active learning is noisy, because each round depends on the previous picks.
  • The same model and hyperparameters for all strategies (here a logistic regression with C=10C = 10).

Active vs random on the digits

The pool is the 1,257 training images of the digits, the test set the usual 540. Each run starts from 20 random labels and adds 20 per round up to 200. Four strategies, three seeds each; the table and the plot show the mean test accuracy.

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression

X, y = load_digits(return_X_y=True)
X = X / 16.0
X_pool, X_test, y_pool, y_test = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)

def score(P, strategy, rng):
    if strategy == "random":
        return rng.random(len(P))
    top2 = np.sort(P, axis=1)[:, -2:]
    if strategy == "least confidence":
        return 1 - top2[:, 1]
    if strategy == "margin":
        return -(top2[:, 1] - top2[:, 0])
    return -(P * np.log(np.clip(P, 1e-12, 1))).sum(1)             # entropy

def run(strategy, seed, start=20, batch=20, budget=200):
    rng = np.random.default_rng(seed)
    labelled = list(rng.choice(len(y_pool), start, replace=False))   # random seed set
    curve = []
    while True:
        model = LogisticRegression(C=10, max_iter=3000).fit(X_pool[labelled], y_pool[labelled])
        curve.append(model.score(X_test, y_test))
        if len(labelled) >= budget:
            return np.array(curve)
        pool = np.setdiff1d(np.arange(len(y_pool)), labelled)
        s = score(model.predict_proba(X_pool[pool]), strategy, rng)
        labelled += list(pool[np.argsort(-s, kind="stable")[:batch]])   # the oracle labels them

sizes = np.arange(20, 201, 20)
strategies = ["random", "least confidence", "margin", "entropy"]
curves = {s: np.mean([run(s, seed) for seed in range(3)], axis=0) for s in strategies}
print("labels   " + "  ".join(f"{s:>16s}" for s in strategies))
for n in (20, 60, 100, 140, 200):
    i = n // 20 - 1
    print(f"{n:6d}   " + "  ".join(f"{curves[s][i]:16.3f}" for s in strategies))
for s in strategies:
    reached = sizes[curves[s] >= 0.90]
    print(f"{s:16s} first reaches 0.90 test accuracy at {reached[0] if len(reached) else '>200'} labels")

fig, ax = plt.subplots(figsize=(6, 3.6))
for s in strategies:
    ax.plot(sizes, curves[s], marker="o", ms=3, label=s)
ax.axhline(0.90, color="grey", lw=0.8, ls="--")
ax.set_xlabel("labelled examples"); ax.set_ylabel("test accuracy (540 images)")
ax.set_title("Active vs random sampling, digits, mean of 3 seeds")
ax.legend(); fig.tight_layout()
labels             random  least confidence            margin           entropy
    20              0.570             0.570             0.570             0.570
    60              0.838             0.836             0.860             0.731
   100              0.892             0.904             0.922             0.860
   140              0.917             0.933             0.933             0.918
   200              0.923             0.959             0.952             0.950
random           first reaches 0.90 test accuracy at 120 labels
least confidence first reaches 0.90 test accuracy at 100 labels
margin           first reaches 0.90 test accuracy at 80 labels
entropy          first reaches 0.90 test accuracy at 140 labels

Read the curves by asking how many labels each strategy needs for a target accuracy, here 0.90:

  • Margin sampling reaches 0.90 at 80 labels; random sampling needs 120. That is 40 labels, a third of the budget, saved for the same accuracy. At 100 labels margin is at 0.922 against 0.892.
  • Least confidence is in between (100 labels) and ends highest at 200 labels (0.959 against random's 0.923).
  • Entropy is worse than random at first: 0.731 at 60 labels against 0.838, and it reaches 0.90 last, at 140. With 10 classes and a weak early model, the examples with the flattest probability vectors are often odd, badly written digits that teach the model little about the typical case. It recovers later, when the model is good enough for its uncertainty to mean something.
  • All four start from the same 0.570 (same seed set) and end within a few points of each other; the differences live in the steep part of the curve, which is exactly where labels are expensive.

The ranking is specific to this data, model and batch size. On another problem entropy may win; the point of the experiment is that you run it, with a simulation on data that is already labelled, before trusting a strategy with your labelling budget.

Batches need diversity

Real annotation runs in batches: you send 40 or 400 images to the labelling team, not one. With a large batch, the top bb by uncertainty are often near-duplicates from the same confusion (the previous lesson's entropy top 20 covered only 5 digits). A simple fix: take the 4b4b most uncertain candidates, cluster them into bb groups with k-means, and take the most uncertain example of each cluster. Here with batches of 40 labels:

python · try it yourself
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.cluster import KMeans

X, y = load_digits(return_X_y=True)
X = X / 16.0
X_pool, X_test, y_pool, y_test = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)

def margin_score(P):
    top2 = np.sort(P, axis=1)[:, -2:]
    return -(top2[:, 1] - top2[:, 0])

def pick(strategy, pool, P, batch, rng):
    if strategy == "random":
        return rng.choice(pool, batch, replace=False)
    s = margin_score(P)
    if strategy == "margin, top b":
        return pool[np.argsort(-s, kind="stable")[:batch]]
    cand = np.argsort(-s, kind="stable")[:4 * batch]              # the 4b most uncertain ...
    groups = KMeans(batch, n_init=1, random_state=0).fit_predict(X_pool[pool[cand]])
    best = [cand[groups == g][np.argmax(s[cand[groups == g]])] for g in range(batch)]
    return pool[best]                                             # ... one per cluster

def run(strategy, seed, start=20, batch=40, rounds=4):
    rng = np.random.default_rng(seed)
    labelled = rng.choice(len(y_pool), start, replace=False)
    accs, distinct = [], []
    for r in range(rounds + 1):
        model = LogisticRegression(C=10, max_iter=3000).fit(X_pool[labelled], y_pool[labelled])
        accs.append(model.score(X_test, y_test))
        if r == rounds:
            return accs, np.mean(distinct)
        pool = np.setdiff1d(np.arange(len(y_pool)), labelled)
        new = pick(strategy, pool, model.predict_proba(X_pool[pool]), batch, rng)
        distinct.append(len(set(y_pool[new])))
        labelled = np.concatenate([labelled, new])

print("labels:                 " + "  ".join(f"{20 + 40 * r:5d}" for r in range(5)) + "   digits per batch")
for strategy in ("random", "margin, top b", "margin + diversity"):
    res = [run(strategy, seed) for seed in range(3)]
    accs = np.mean([a for a, _ in res], axis=0)
    print(f"{strategy:22s}  " + "  ".join(f"{a:5.3f}" for a in accs) + f"   {np.mean([d for _, d in res]):.1f}")
labels:                    20     60    100    140    180   digits per batch
random                  0.570  0.848  0.901  0.932  0.938   9.8
margin, top b           0.570  0.851  0.909  0.928  0.952   9.1
margin + diversity      0.570  0.892  0.933  0.945  0.964   9.7

With batches of 40, plain top-bb margin sampling is barely better than random after one round (0.851 against 0.848), because its 40 picks repeat the same few confusions (9.1 distinct digits per batch against 9.8 for random). Adding diversity gives 0.892 after one round and stays ahead at every budget, ending at 0.964 against 0.938 for random. Clustering is the simplest diversity method; core-set selection (greedy k-center on embeddings) and BADGE (k-means++ on gradient embeddings) are the stronger versions used with deep networks.

When to stop

The loop stops when the budget is spent, but a better rule saves the rest of the budget when more labels stop helping. Common signals:

Signal How to measure Stop when
Accuracy on a held-out labelled set a small random set labelled once at the start the gain per round falls below what one round of labels is worth
Stabilising predictions agreement between consecutive models on a fixed unlabelled "stop set" agreement above about 0.99 for several rounds
Falling uncertainty the maximum or mean uncertainty score in the pool no example is very uncertain any more
Cost the labelling budget or deadline money or time runs out

Running it for real

  • Annotation tooling. Label Studio, Prodigy and similar tools accept a ranked queue from your script; the model is retrained between rounds, often nightly. modAL, scikit-activeml and small-text are Python libraries that package the strategies.
  • Annotator cost is not constant. Uncertain examples are also the hard ones for humans: they take longer and get more disagreement. Measure cost per label, and consider cost-aware strategies (uncertainty per second of annotation).
  • Label quality. Ask for two annotators on the hardest picks, and keep the annotation guidelines versioned with the data.
  • Model change. The labels were chosen for one model. A different model trained later on the same actively chosen set may do worse than on a random set of the same size. Keep a random slice in each batch (for example 10 to 20 %) to hedge.

Advantages and limits

Advantages Limits
Fewer labels for the same accuracy, often 20 to 50 % fewer in the steep part of the curve The gain depends on data, model and strategy; it can be zero or negative (entropy above)
Labels go to the cases the model gets wrong, which also surfaces label-guideline problems early Needs infrastructure: retraining, scoring, an annotation queue
Works with any model that gives scores The labelled set is biased towards hard cases; evaluation needs a separate random set
Combines with semi-supervised learning: label the uncertain, pseudo-label the confident Cold start: the first rounds depend on a decent random seed set

Pitfalls

  • One run, one seed. Active learning curves are noisy; compare means over several seeds and look at the spread.
  • Evaluating on the labelled set or on a test set taken from the pool after selection.
  • Tuning the strategy on the test set. Choosing a strategy or batch size by test accuracy, as these examples do for brevity, is a decision made with test data; in a project, use a validation slice.
  • Huge batches without diversity, which waste labels on near-duplicates.
  • Forgetting the human. A strategy that picks the most confusing examples can exhaust annotators and lower label quality.

Practice

  1. In the first experiment, how many labels does margin sampling save over random sampling to reach 0.90, and what fraction of random's labels is that?
  2. Why do all four strategies have exactly the same accuracy (0.570) at 20 labels?
  3. Your batch size is 500 and labelling one batch takes a week. Which part of this lesson matters most, and why?
Answers
  1. Random sampling needs 120 labels, margin 80: 40 labels saved, a third of 120.
  2. Each repetition uses the same random seed set of 20 labels for every strategy (the seed set depends only on the seed), so round 0 trains the same model; the strategies differ only from the first query on.
  3. Diversity in batch mode. With 500 picks per round and few rounds, top-bb uncertainty would spend much of each batch on near-duplicates of the same confusions; clustering or core-set selection spreads the batch over the pool. A stopping rule also matters more: each extra round costs a week.

Test yourself

What is the fair way to compare an active learning strategy with random sampling?

  1. Compare accuracy on the actively labelled examples
  2. Run both loops from the same seed set, measure on a fixed random test set, and average several seeds
  3. Run each once with different models
  4. Compare the number of rounds

In the digits experiment, which strategy was worse than random sampling in the early rounds?

  1. Margin
  2. Least confidence
  3. Entropy
  4. None

Why does batch-mode active learning add a diversity step?

  1. To make training faster
  2. The top-b uncertain examples are often near-duplicates, so labelling all of them wastes budget
  3. To reduce the number of classes
  4. Because k-means is a classifier

What does a learning curve in this lesson plot?

  1. Training loss against epochs
  2. Test accuracy against the number of labelled examples
  3. Precision against recall
  4. The learning rate against steps