Active Learning: Query Strategies
Semi-supervised learning accepts the labels you have and squeezes more out of unlabelled data. Active learning changes which labels you get. When labelling is the expensive step (a radiologist's minute, a lawyer's hour, a lab assay), it pays to let the model choose which examples a human labels next. The idea, introduced in ML Foundations, is that a model learns little from examples it already classifies confidently and much from those it is unsure about. A query strategy turns "unsure" into a number for every unlabelled example; the highest scores go to the annotator.
This lesson defines the classic strategies and compares what they pick. The next lesson runs the full labelling loop and measures whether they beat random sampling.
The setting: pool-based active learning
There is a small labelled set , a large unlabelled pool , and an oracle (the annotator) who can label any example at a cost. Each round: train on , score every , send the best to the oracle, move them into . Two other settings exist: stream-based (examples arrive one at a time and the model decides on the spot whether to ask for a label) and query synthesis (the model creates the input to be labelled, rarely practical).
Uncertainty sampling
Let be the model's predicted probabilities, sorted so that is the most likely class and the second. The three classic uncertainty scores pick
For two classes all three choose the same examples (those with closest to 0.5). With more classes they differ. Least confidence looks only at the top class; margin looks at the decision between the top two, which is where a classifier's mistakes happen; entropy looks at the whole distribution and prefers examples spread over many classes. (Entropy is derived in the Mathematics track.)
For a probabilistic classifier, the uncertain points lie along the decision boundary. In the lab, a logistic regression on two blobs: the shading fades where is near 0.5, and that band is exactly where uncertainty sampling queries. Turn the noise up and see how the band widens.
Query by committee
Uncertainty sampling trusts one model's probabilities, which may be badly calibrated. Query by committee (QBC) trains several models (different algorithms, or the same one on bootstrap samples) and queries where they disagree. With the number of members voting for class , the vote entropy is
A soft alternative is the average KL divergence of each member's probabilities from the committee mean, . Disagreement measures how much the data so far leaves the answer open (version-space uncertainty), not just one model's doubt.
Other families
| Strategy | Picks | Cost |
|---|---|---|
| Uncertainty (LC, margin, entropy) | examples the current model is least sure about | one prediction per pool example |
| Query by committee | examples on which several models disagree | models |
| Diversity (core-set, k-center, cluster-based) | examples that cover the pool, far from what is already labelled | distances to the pool |
| Hybrid (uncertainty + diversity, e.g. BADGE) | uncertain examples that are also different from each other | both |
| Expected model change | examples whose label would change the weights most (largest expected gradient) | a gradient per candidate |
| Expected error reduction | examples whose label would most reduce the expected error on the pool | retrain per candidate and label: expensive |
From scratch: three scores on four predictions
Four 3-class predictions and the three uncertainty scores. The margin score is negated, so that for every strategy a higher score means "query this first".
import numpy as np
def least_confidence(P): return 1 - P.max(1)
def margin(P):
top2 = np.sort(P, axis=1)[:, -2:]
return -(top2[:, 1] - top2[:, 0]) # negated: a small margin is a high score
def entropy(P): return -(P * np.log(np.clip(P, 1e-12, 1))).sum(1)
P = np.array([[0.90, 0.05, 0.05], # A: confident
[0.50, 0.49, 0.01], # B: torn between two classes
[0.40, 0.30, 0.30], # C: spread over all three
[0.36, 0.33, 0.31]]) # D: almost uniform
names = "ABCD"
print("point least-confidence margin score entropy")
for n, lc, m, h in zip(names, least_confidence(P), margin(P), entropy(P)):
print(f" {n} {lc:.3f} {m:6.3f} {h:.3f}")
for f in (least_confidence, margin, entropy):
s = f(P)
print(f"{f.__name__:16s} ranks: {' > '.join(names[i] for i in np.argsort(-s))}")point least-confidence margin score entropy
A 0.100 -0.850 0.394
B 0.500 -0.010 0.742
C 0.600 -0.100 1.089
D 0.640 -0.030 1.097
least_confidence ranks: D > C > B > A
margin ranks: B > D > C > A
entropy ranks: D > C > B > A
All three agree that A (0.90 on one class) is the least interesting. They disagree on the rest. Least confidence and entropy rank D first: its probabilities are almost uniform. Margin ranks B first: B is a coin toss between two classes (0.50 against 0.49), and that is exactly the kind of example that decides where a boundary goes. C, spread over three classes, is second for entropy and least confidence but third for margin. Which behaviour is better depends on the task, and the next lesson measures it.
With scikit-learn: what each strategy picks
Now real scores on the digits. The model is a logistic regression trained on 30 labels (3 per digit); the pool is the other 1,227 training images. Each strategy picks its top 20. Because this is a demo, the pool's true labels are known, so we can check how many of the picked images the current model gets wrong (a rough sign of informativeness) and how many different digits they cover (a sign of diversity). The committee has five different classifiers trained on the same 30 labels.
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.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
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)
rng = np.random.default_rng(0)
lab = np.concatenate([rng.choice(np.where(y_pool == c)[0], 3, replace=False) for c in range(10)])
unl = np.setdiff1d(np.arange(len(y_pool)), lab)
model = LogisticRegression(C=10, max_iter=3000).fit(X_pool[lab], y_pool[lab])
P = model.predict_proba(X_pool[unl])
top2 = np.sort(P, axis=1)[:, -2:]
scores = {"least confidence": 1 - P.max(1),
"margin": -(top2[:, 1] - top2[:, 0]),
"entropy": -(P * np.log(np.clip(P, 1e-12, 1))).sum(1)}
committee = [LogisticRegression(C=10, max_iter=3000), KNeighborsClassifier(1),
DecisionTreeClassifier(random_state=0), GaussianNB(), SVC()]
votes = np.stack([m.fit(X_pool[lab], y_pool[lab]).predict(X_pool[unl]) for m in committee])
share = np.stack([(votes == c).mean(0) for c in range(10)], axis=1) # vote share per class
scores["committee (vote entropy)"] = -(share * np.log(np.clip(share, 1e-12, 1))).sum(1)
b = 20
wrong = model.predict(X_pool[unl]) != y_pool[unl] # known only because this is a demo
print(f"current model: {model.score(X_test, y_test):.3f} test accuracy, wrong on {wrong.mean():.3f} of the pool")
picked = {}
for name, s in scores.items():
q = np.argsort(-s, kind="stable")[:b]
picked[name] = set(q)
print(f"{name:25s} top {b}: {wrong[q].mean():.2f} misclassified, {len(set(y_pool[unl][q]))} distinct digits")
rand = [wrong[rng.choice(len(unl), b, replace=False)].mean() for _ in range(200)]
print(f"{'random (mean of 200 draws)':25s} top {b}: {np.mean(rand):.2f} misclassified")
names = list(picked)
print("overlap of the top-20 sets:")
for i, a in enumerate(names):
print(f" {a:25s}" + " ".join(f"{len(picked[a] & picked[c]):3d}" for c in names))current model: 0.789 test accuracy, wrong on 0.213 of the pool
least confidence top 20: 0.75 misclassified, 7 distinct digits
margin top 20: 0.70 misclassified, 8 distinct digits
entropy top 20: 0.70 misclassified, 5 distinct digits
committee (vote entropy) top 20: 0.65 misclassified, 7 distinct digits
random (mean of 200 draws) top 20: 0.21 misclassified
overlap of the top-20 sets:
least confidence 20 4 13 3
margin 4 20 1 0
entropy 13 1 20 4
committee (vote entropy) 3 0 4 20
The current model is wrong on 21.3 % of the pool, so 20 random picks contain about 4 mistakes (0.21). Every strategy finds the model's mistakes far more often: 0.65 to 0.75 of their picks are misclassified, three times the random rate. That is what makes them useful: each label corrects something the model gets wrong. But they pick different images. Least confidence and entropy share 13 of 20; margin shares only 4 with least confidence and 1 with entropy; the committee, which looks at disagreement between models rather than one model's probabilities, shares 0 to 4 with the others. And the picks are not diverse: entropy's 20 cover only 5 of the 10 digits, because the most uncertain images tend to come from the same few confusable digits. Labelling 20 near-duplicates teaches the model less than 20 varied images, which is why batch-mode active learning adds diversity (next lesson).
Vote entropy can only take a few values with five voters (for example 0 for a unanimous vote, for five different answers), so many pool images tie; np.argsort(..., kind="stable") breaks ties by pool order. A soft disagreement measure such as the KL version avoids ties.
Pitfalls
- Uncalibrated probabilities. Uncertainty sampling ranks by the model's confidence; if the model is confidently wrong on a whole region, that region is never queried. QBC, ensembles or calibration help.
- Outliers look uncertain. A corrupted image or an example from no class gets a high entropy and wastes a label. Combine uncertainty with density (prefer uncertain examples in dense regions) or filter outliers first.
- Redundant batches. The top by uncertainty are often near-copies of each other. Add a diversity term in batch mode.
- Cold start. With very few labels the model's uncertainty is meaningless; start with a random or diversity-based seed set covering all classes.
- The labelled set is no longer a random sample. Never estimate accuracy on actively chosen labels; keep a separate random test set.
Practice
- For a binary classifier, show that least confidence, margin and entropy pick the same example.
- Point B, , has a lower entropy (0.742) than point C, , with 1.089. Why might B still be the more useful label?
- A committee of 5 models votes 3 for class 2 and 2 for class 7. Compute the vote entropy.
Answers
- With two classes, and with . Least confidence , margin and entropy are all monotone in on , and all are most uncertain at . So all three order the examples identically.
- B sits right on the boundary between two classes: its label decides on which side of that boundary such images fall, which changes the classifier. C is unsure about all three classes, which may just mean an unusual image, and its label may move the boundary less.
- (natural logarithm).
Test yourself
Which strategy queries the example with the smallest difference between the two most likely classes?
- Least confidence
- Margin sampling
- Entropy sampling
- Random sampling
What does query by committee measure?
- The confidence of the best model
- The disagreement between several models trained on the labelled data
- The distance to the nearest labelled example
- The training loss
In the digits example, entropy's top 20 covered only 5 of the 10 digits. What problem does this show?
- Entropy is computed wrongly
- The most uncertain examples are often similar to each other, so a batch of them is redundant
- The pool is too small
- Logistic regression cannot output probabilities
Why should accuracy never be estimated on the actively labelled examples?
- They are too few
- They were chosen because they are hard, so they are not a random sample of the data the model will see
- They have no labels
- They are used for the committee