Khush Shah

Active Learning: Labelling Fewer Points

Khush Shah 22 min read Machine Learning, Python, Tutorials

Labels are usually the expensive part of a machine-learning project: someone has to look at each example and say what it is. Active learning lets the model choose which examples get labelled, so that each label teaches it as much as possible. In this post, first published as Active Learning Classification, I build the loop from scratch with scikit-learn on a two-dimensional XOR-style problem, watch the decision boundary form as the points are chosen, and compare five ways of choosing points over 20 runs each. A committee of three models reached 95% test accuracy with about 42 labels on average, against about 58 for random sampling, and 98% with about 60 against 126. Uncertainty sampling with a single model did well in most runs but got stuck for good in one of the 20, and that failure deserves as much attention as the saving.

Active Learning

Active learning is a machine learning technique that involves iteratively selecting the most informative samples from a large unlabelled dataset and adding them to a smaller labelled dataset. The goal of active learning is to reduce the amount of labelled data required for training while maintaining or improving the performance of a machine learning model.

The active learning process typically involves the following steps:

  • Initialise the learning algorithm

  • Select unlabelled samples

  • Request labels

  • Incorporate labelled samples

  • Evaluate model performance

Active learning has been applied in various domains and has proven to be effective in scenarios where labelled data is limited or costly to obtain like Text Classification, Image recognition etc.

Kinds of active learning

The literature sorts active learning along a few lines (Settles, 2009, is the standard survey). These are the terms you will meet:

Term What it means
Pool-based A fixed pool of unlabelled points is available, and the learner scores all of them before choosing which to label. This post is pool-based.
Stream-based Points arrive one at a time, and the learner decides on the spot whether to ask for the label or let the point go.
Uncertainty sampling Ask for the points the current model is least sure about, measured from its predicted class probabilities: least confidence, margin or entropy.
Committee disagreement Train several models and ask for the points on which they disagree most. This is query by committee, the main strategy here.
Expected model change Ask for the points whose labels would change the model most, for example those with the largest expected gradient.
Diversity (core-set) sampling Choose points that cover the input space, so that the labelled set represents the whole pool rather than one corner of it.
Cold start With only a few labels the model is poor, and so is its sense of what it does not know. Most methods start from a small random sample, as this post does with 10 points.
Batch mode Retraining after every label is slow, so points are chosen in batches (5 per round here). The top few points by any score are often close together and so redundant, which wastes labels unless the batch is also made diverse.

The loop

Every round of pool-based active learning goes round the same loop. The models only ever train on the labelled set; the pool is the rest of the training data, whose labels the learner may not look at until it asks for them. The oracle is whoever supplies a label on request: in practice a person, here a look-up in labels I already have.

Show code
import matplotlib.pyplot as plt
from matplotlib.patches import FancyArrowPatch, FancyBboxPatch

fig, ax = plt.subplots(figsize=(8, 3.8))
ax.set_xlim(-0.05, 10.05)
ax.set_ylim(0.3, 5.0)
ax.axis("off")

width, height = 2.9, 1.3
boxes = {
    "train": (1.5, 4.1, "1. Train the committee\non the labelled set"),
    "score": (5.0, 4.1, "2. Score every point\nin the pool"),
    "pick": (8.5, 4.1, "3. Pick the 5 points\nwith the top scores"),
    "ask": (6.8, 1.2, "4. Ask the oracle\nfor their labels"),
    "add": (3.2, 1.2, "5. Add them to the\nlabelled set"),
}
for cx, cy, text in boxes.values():
    ax.add_patch(FancyBboxPatch((cx - width / 2, cy - height / 2), width, height,
                                boxstyle="round,pad=0.02,rounding_size=0.15",
                                facecolor="#EEF3FA", edgecolor="#26324F", linewidth=1.6))
    ax.text(cx, cy, text, ha="center", va="center", fontsize=12.5, color="#17171A")


def arrow(start, end):
    ax.add_patch(FancyArrowPatch(start, end, arrowstyle="-|>", mutation_scale=22,
                                 linewidth=1.8, color="#26324F", shrinkA=2, shrinkB=2))


arrow((1.5 + width / 2, 4.1), (5.0 - width / 2, 4.1))
arrow((5.0 + width / 2, 4.1), (8.5 - width / 2, 4.1))
arrow((8.5, 4.1 - height / 2), (6.8 + 0.5, 1.2 + height / 2))
arrow((6.8 - width / 2, 1.2), (3.2 + width / 2, 1.2))
arrow((3.2 - 0.5, 1.2 + height / 2), (1.5, 4.1 - height / 2))
ax.text(5.0, 2.65, "repeat until the\nlabel budget is spent", ha="center", va="center",
        fontsize=12, style="italic", color="#444444")
fig.tight_layout()
plt.show()
A loop of five boxes joined by arrows. 1: train the committee on the labelled set. 2: score every point in the pool. 3: pick the 5 points with the top scores. 4: ask the oracle for their labels. 5: add them to the labelled set, and back to 1. The middle of the loop reads: repeat until the label budget is spent.
One round of pool-based active learning. Each pass round the loop labels 5 more points.

The code needs NumPy, scikit-learn, Plotly for the interactive figures and matplotlib for the animations. matplotlib writes the animations with ffmpeg; if there is none on the PATH, the cell below falls back to the copy that ships with the imageio-ffmpeg package.

# import necessary libraries
import base64
import os
import shutil
import tempfile

# libraries for data visualisation
import plotly.express as px
import plotly.graph_objects as go
import plotly.io as pio
import matplotlib.pyplot as plt

pio.renderers.default = "plotly_mimetype+notebook_connected"

# matplotlib runs "ffmpeg" from the PATH to write the animations. If there is none,
# use the copy that the imageio-ffmpeg package ships (pip install imageio-ffmpeg).
if shutil.which("ffmpeg") is None:
    import imageio_ffmpeg
    plt.rcParams["animation.ffmpeg_path"] = imageio_ffmpeg.get_ffmpeg_exe()

# libraries for data loading and processing
import numpy as np
import pandas as pd

# libraries for the models
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score

# libraries for displaying animation
import matplotlib.animation as animation
from IPython import display

The problem: an XOR pattern

I draw 1,010 points uniformly in the square $[-2, 2]^2$ and label a point 1 when $xy > 0$ (the top-right and bottom-left quadrants) and 0 otherwise. This is the XOR pattern in two dimensions: the label says whether the signs of the two coordinates agree. No straight line separates the classes, so a linear model such as logistic regression can do no better than a coin, however many labels it gets. Trees, which split on one coordinate at a time, fit it easily. 80% of the points (808) form the training pool, and the other 202 are a test set that is never used to choose points.

rng = np.random.default_rng(42)
x = rng.uniform(-2, 2, size=(1010, 2))
y = (x[:, 0] * x[:, 1] > 0).astype(int)

x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=1)
print(f"{len(x_train)} training points, {len(x_test)} test points, {y.mean():.1%} of all points in class 1")
808 training points, 202 test points, 51.2% of all points in class 1

Four helpers draw the figures: plot_cluster shades the plane by a model's prediction (or by the true label when there is no model) and draws the points on top, plot_contour computes that shading on a grid, plot_accuracy draws accuracy curves, and plotAnimation collects one frame per round and turns the frames into an MP4 video.

def plot_cluster(x, y, model=None, samples=None, name=None):
    x_min, x_max = x[:, 0].min() - 0.5, x[:, 0].max() + 0.5
    y_min, y_max = x[:, 1].min() - 0.5, x[:, 1].max() + 0.5

    xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.05), np.arange(y_min, y_max, 0.05))

    if model is None:
        Z = np.empty(xx.ravel().shape, dtype=np.int8)
        for i in range(xx.ravel().shape[0]):
            Z[i] = 1 if xx.ravel()[i] * yy.ravel()[i] > 0 else 0
    else:
        Z = model.predict(np.c_[xx.ravel(), yy.ravel()])

    Z = Z.reshape(xx.shape)

    fig = go.Figure()

    # Plot decision boundaries
    fig.add_trace(go.Contour(
        x=np.arange(x_min, x_max, 0.05),
        y=np.arange(y_min, y_max, 0.05),
        z=Z,
        colorscale='RdYlBu',
        contours_coloring='heatmap',
        opacity=0.75,
    ))

    if model is None:
        # Plot data points when no model is provided
        fig.add_trace(go.Scatter(
            x=x[:, 0],
            y=x[:, 1],
            mode='markers',
            marker=dict(color='orange', line=dict(color='black', width=1)),
        ))
    else:
        # Plot data points with labels when a model is provided
        fig.add_trace(go.Scatter(
            x=x[:, 0],
            y=x[:, 1],
            mode='markers',
            marker=dict(color=y, colorscale='RdYlBu', line=dict(color='black', width=1))
        ))

    if samples is not None:
        # Plot additional samples if available
        fig.add_trace(go.Scatter(
            x=samples[:, 0],
            y=samples[:, 1],
            mode='markers',
            marker=dict(color='white', colorscale='RdYlBu', line=dict(color='black', width=1))
        ))

    if name:
        fig.update_layout(title=name)

    fig.update_layout(
        xaxis=dict(range=(x_min, x_max)),
        yaxis=dict(range=(y_min, y_max)),
        width=700,
        height=600
    )

    fig.show()
def plot_contour(x, model=None):
    x_min, x_max = x[:, 0].min() - 0.5, x[:, 0].max() + 0.5
    y_min, y_max = x[:, 1].min() - 0.5, x[:, 1].max() + 0.5

    xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.05), np.arange(y_min, y_max, 0.05))

    if model is None:
        Z = np.empty(xx.ravel().shape)
        for i in range(xx.ravel().shape[0]):
            Z[i] = 1 if xx.ravel()[i] * yy.ravel()[i] > 0 else 0
    else:
        Z = model.predict(np.c_[xx.ravel(), yy.ravel()])

    Z = Z.reshape(xx.shape)
    return (xx, yy, Z)
def plot_accuracy(labels, overall_accuracy, models_accuracy_list, classifiers, y_title):
    fig = px.line()
    for i in range(len(models_accuracy_list)):
        fig.add_scatter(x=labels, y=models_accuracy_list[i], name=classifiers[i])
    fig.add_scatter(x=labels, y=overall_accuracy, name="Committee (majority vote)")
    fig.update_layout(xaxis_title="Labelled points", yaxis_title=y_title)
    fig.show()
class plotAnimation:
    def __init__(self, x, y, model_name=None):
        self.x_whole = x
        self.y_whole = y
        self.model_name = model_name

        self.xlim = (x[:, 0].min() - 0.5, x[:, 0].max() + 0.5)
        self.ylim = (x[:, 1].min() - 0.5, x[:, 1].max() + 0.5)

        self.data = []
        self.contour = []

    def update(self, model, x, y, samples, pool_acc, test_acc):
        self.data.append((x, y, samples, pool_acc, test_acc))
        self.contour.append(plot_contour(self.x_whole, model))

    def animate(self, i):
        # Start every frame from an empty axis, so that frames do not pile up on each other.
        self.ax.clear()
        self.ax.contourf(self.contour[i][0], self.contour[i][1], self.contour[i][2], cmap=plt.cm.RdYlBu, alpha=0.8)

        x, y, samples, pool_acc, test_acc = self.data[i]
        scat = self.ax.scatter(x[:, 0], x[:, 1], c=y, cmap="RdYlBu", edgecolors="k")
        legend1 = self.ax.legend(*scat.legend_elements(), loc="upper right", title="Classes")
        self.ax.add_artist(legend1)

        scat = self.ax.scatter(samples[:, 0], samples[:, 1], color="white", edgecolors="k")
        self.ax.legend([scat], ["Next batch"], loc="lower right")

        self.ax.set_xlim(self.xlim)
        self.ax.set_ylim(self.ylim)
        self.ax.set_xlabel("x")
        self.ax.set_ylabel("y")

        title = f"round {i}: {len(y)} labels\npool accuracy {pool_acc:.3f}, test accuracy {test_acc:.3f}"
        if self.model_name:
            title = self.model_name + ", " + title
        else:
            title = title[0].upper() + title[1:]
        self.ax.set_title(title)

        return self.ax

    def save(self, path):
        # H.264 at constant quality 28, 640 x 480 pixels, two frames a second, no audio track.
        self.fig, self.ax = plt.subplots(figsize=(6.4, 4.8), dpi=100)
        anim = animation.FuncAnimation(self.fig, self.animate, frames=len(self.data), interval=500, blit=False, repeat=False)
        writer = animation.FFMpegWriter(fps=2, codec="h264", extra_args=["-crf", "28", "-pix_fmt", "yuv420p", "-an"])
        anim.save(path, writer=writer, dpi=100)
        plt.close(self.fig)

    def show(self):
        with tempfile.TemporaryDirectory() as folder:
            path = os.path.join(folder, "animation.mp4")
            self.save(path)
            with open(path, "rb") as file:
                video = base64.b64encode(file.read()).decode("ascii")
        display.display(display.HTML(f'<video controls src="data:video/mp4;base64,{video}"></video>'))
plot_cluster(x, y, None, None)
The true labels: class 1 (blue) where x and y have the same sign, class 0 (red) where they differ.

Before any active learning, here is what each model can do when it is given all 808 training labels. That is the ceiling the active learner is trying to reach with far fewer.

full_models = {
    "Logistic regression": LogisticRegression(),
    "RBF SVM": SVC(kernel="rbf", C=10),
    "Decision tree": DecisionTreeClassifier(random_state=1),
    "Random forest": RandomForestClassifier(n_estimators=100, random_state=1),
}
for name, model in full_models.items():
    model.fit(x_train, y_train)
    print(f"{name:<20} test accuracy with all {len(x_train)} labels: {model.score(x_test, y_test):.3f}")
Logistic regression  test accuracy with all 808 labels: 0.460
RBF SVM              test accuracy with all 808 labels: 0.980
Decision tree        test accuracy with all 808 labels: 0.985
Random forest        test accuracy with all 808 labels: 0.985

Logistic regression gets 46%, no better than a coin, because its decision boundary is a single straight line, and every straight line through the square gets about half of the points wrong. The other three models reach 98% or more. So the committee in this post is an RBF-kernel SVM, a random forest and a decision tree. The first version of this post had logistic regression in place of the SVM. That made it a poorly specified committee member: it is wrong on about half the points whatever it is shown, so it disagrees with the other two over much of the pool, and vote entropy then points at its mistakes rather than at the places where the boundary is really uncertain. The SVM can fit the pattern, and it draws a smooth boundary where the trees draw steps, so it disagrees with them in more useful places.

The forest below, trained on everything, is the target. Its boundary lies on the two axes, and the 3 test points it gets wrong all sit within 0.003 of the y-axis.

plot_cluster(x_test, y_test, model=full_models["Random forest"])
A random forest trained on all 808 labels, drawn over the 202 test points.

Starting Active Learning

The query strategy: query by committee

The strategy in this post is query by committee (Seung, Opper and Sompolinsky, 1992) with vote entropy as the measure of disagreement (Dagan and Engelson, 1995). Several models, the committee, are trained on the same labelled set; each one votes on every point in the pool; and the points they disagree on most are labelled next. For a point $x$, if $V(c, x)$ of the $C$ members vote for class $c$, the vote entropy is

$$\mathrm{VE}(x) = -\sum_{c} \frac{V(c, x)}{C} \log_2 \frac{V(c, x)}{C}.$$

With three members and two classes it can take only two values: 0 when the vote is unanimous, and $-\tfrac{2}{3}\log_2\tfrac{2}{3} - \tfrac{1}{3}\log_2\tfrac{1}{3} \approx 0.918$ when it splits 2 to 1. vote_entropy computes it for every point in the pool from a table of votes, one column per model.

def vote_entropy(votes):
    entropy_list = []
    for x in votes:
        unique_values, counts = np.unique(x, return_counts=True)
        p = counts / x.shape[0]
        entropy_list.append(-np.sum(p * np.log2(p)))
    return np.array(entropy_list)

For comparison, three uncertainty-sampling scores (Lewis and Gale, 1994) computed from one model, the committee's random forest, through predict_proba: least confidence (one minus the top class probability), margin (the gap between the top two probabilities, negated so that a smaller gap scores higher) and the entropy of the predicted probabilities. For every score, higher means more uncertain.

def least_confidence(proba):      # proba: (n_pool, n_classes)
    return 1.0 - proba.max(axis=1)

def margin(proba):
    s = np.sort(proba, axis=1)
    return -(s[:, -1] - s[:, -2])  # smaller margin = more uncertain = higher score

def entropy(proba, eps=1e-12):
    return -(proba * np.log(proba + eps)).sum(axis=1)

Because vote entropy has only two values, "the five points with the highest score" really means "any five of the points the committee disagrees on", and there are usually many more than five of those. The first version of this post took the last five of np.argsort(entropy_list), which breaks those ties by position in the array: arbitrary, and the same every time. select_samples shuffles the candidates with the seeded generator before sorting, so ties are broken at random but reproducibly. The random forest's probabilities tie too (they are fractions of 50 trees), and the same function handles them.

def select_samples(scores, samples, rng):
    shuffled = rng.permutation(len(scores))                        # random order for ties
    order = np.argsort(-np.asarray(scores)[shuffled], kind="stable")  # highest score first
    return shuffled[order[:samples]]
# The committee's prediction: the majority vote of its members, one row per point.
def output_list(stack):
    output_list = np.array([int(np.bincount(x).argmax()) for x in stack])
    return output_list

One function per run

run(seed, strategy) runs the whole experiment once and returns a dictionary whose "test" entry is the test-accuracy curve, one value per round. Every strategy trains the same committee on whatever it has labelled so far and is scored the same way, by the test accuracy of the committee's majority vote, so the strategies differ only in which points they ask for. A run starts from 10 random labelled points (drawn again in the rare case that they miss a class: the SVM needs at least two, and a model that has never seen a class can never predict it), adds 5 points per round for 60 rounds, and so ends with 310 labels, 38% of the pool. For a given seed, every strategy starts from the same 10 points. The random forest has 50 trees rather than scikit-learn's default of 100, to keep the 100 runs further down to a couple of minutes.

Two more arguments change the setting: samples is the batch size and data the data set, for the batch-size comparison and the real-data example near the end. With detail=True it also records each member's accuracy, the pool accuracy and how many pool points the committee disagrees on, and with animations it hands each member's decision boundary to a plotAnimation every round.

N_START = 10   # labelled points at the start
SAMPLES = 5    # points labelled per round
ROUNDS = 60    # rounds per run: 10 + 5 * 60 = 310 labels at the end
N_TREES = 50   # trees in the committee's random forest

classifiers = ("RBF SVM", "Random forest", "Decision tree")


def make_committee(seed):
    return [SVC(kernel="rbf", C=10),
            RandomForestClassifier(n_estimators=N_TREES, random_state=seed),
            DecisionTreeClassifier(random_state=seed)]


UNCERTAINTY = {"least confidence": least_confidence, "margin": margin, "entropy": entropy}


def choose_samples(strategy, models, x_pool, rng, samples=SAMPLES):
    if strategy == "random":
        # without replacement, so that every round adds `samples` different points
        return rng.choice(len(x_pool), size=samples, replace=False)
    if strategy == "committee":
        votes = np.stack([model.predict(x_pool) for model in models], axis=-1)
        return select_samples(vote_entropy(votes), samples, rng)
    proba = models[1].predict_proba(x_pool)    # the committee's random forest
    return select_samples(UNCERTAINTY[strategy](proba), samples, rng)
XOR = (x_train, y_train, x_test, y_test)


def run(seed, strategy, rounds=ROUNDS, samples=SAMPLES, data=XOR, detail=False, animations=None):
    x_train, y_train, x_test, y_test = data
    rng = np.random.default_rng(seed)
    detail = detail or animations is not None

    # 1. Initialise: the committee and a random starting set that holds every class.
    n_classes = len(np.unique(y_train))
    start = rng.choice(len(x_train), size=N_START, replace=False)
    while len(np.unique(y_train[start])) < n_classes:
        start = rng.choice(len(x_train), size=N_START, replace=False)
    labelled = np.zeros(len(x_train), dtype=bool)
    labelled[start] = True
    models = make_committee(seed)

    history = {"labels": [], "test": [], "pool": [], "disagree": [],
               "model_test": [[] for _ in models], "model_pool": [[] for _ in models]}
    for round_no in range(rounds + 1):
        x_training, y_training = x_train[labelled], y_train[labelled]
        for model in models:
            model.fit(x_training, y_training)

        # 5. Evaluate: the committee's majority vote on the test set.
        test_votes = np.stack([model.predict(x_test) for model in models], axis=-1)
        history["labels"].append(int(labelled.sum()))
        history["test"].append(accuracy_score(y_test, output_list(test_votes)))
        if detail:
            pool_votes = np.stack([model.predict(x_train) for model in models], axis=-1)
            history["pool"].append(accuracy_score(y_train, output_list(pool_votes)))
            unlabelled_votes = pool_votes[~labelled]
            history["disagree"].append(int(np.sum(unlabelled_votes.min(axis=1) != unlabelled_votes.max(axis=1))))
            for i in range(len(models)):
                history["model_test"][i].append(accuracy_score(y_test, test_votes[:, i]))
                history["model_pool"][i].append(accuracy_score(y_train, pool_votes[:, i]))

        if round_no == rounds:
            break

        # 2. Select: score the unlabelled pool and pick `samples` points.
        pool = np.flatnonzero(~labelled)
        picked = pool[choose_samples(strategy, models, x_train[pool], rng, samples)]

        if animations is not None:
            for i, anim in enumerate(animations):
                anim.update(models[i], x_training, y_training, x_train[picked],
                            history["model_pool"][i][-1], history["model_test"][i][-1])

        # 3 and 4. Request the labels and incorporate them: the oracle is a look-up in
        # y_train, and the picked points move from the pool to the labelled set.
        labelled[picked] = True

    history = {key: np.array(value) for key, value in history.items()}
    history["models"] = models
    history["labelled"] = labelled
    return history

The five steps from the introduction map onto the code like this:

  1. Initialise the learning algorithm: make_committee builds the three models, and the first lines of run draw the starting set of 10 labelled points.
  2. Select unlabelled samples: choose_samples scores the pool, with vote_entropy for the committee or with least_confidence, margin or entropy for the random forest, and select_samples takes the top 5 with random tie-breaks. The baseline draws 5 at random, without replacement.
  3. Request labels: the oracle. Here the labels are already in y_train, so asking is a look-up; in a real project this is where a person labels the 5 points.
  4. Incorporate labelled samples: labelled[picked] = True moves the points from the pool to the labelled set, and the next round retrains on it.
  5. Evaluate model performance: output_list takes the committee's majority vote on the test set, and accuracy_score scores it, once per round.

Results

One run, watched

First a single run (seed 0) of query by committee and one of random sampling, recording each model's accuracy and, for the animations, its decision boundary at every round. Two accuracies are tracked. Test accuracy is measured on the 202 held-out points. Pool accuracy is measured on all 808 training points, labelled or not; the first version of this post called it "training accuracy", but most of those points are never labelled, so it says how well the models know the whole pool, not how well they fit what they were shown.

anim_model = [plotAnimation(x, y, model_name=name) for name in classifiers]
active = run(0, "committee", animations=anim_model)
random_run = run(0, "random", detail=True)

disagree = active["disagree"][:-1]     # the last round chooses nothing
print(f"Pool points the committee disagrees on: {disagree[0]} at {active['labels'][0]} labels, "
      f"{disagree[10]} at {active['labels'][10]} labels; none for the first time at "
      f"{active['labels'][np.argmax(disagree == 0)]} labels, and none in {np.sum(disagree == 0)} of the {ROUNDS} rounds")
Pool points the committee disagrees on: 393 at 10 labels, 34 at 60 labels; none for the first time at 105 labels, and none in 36 of the 60 rounds

The committee disagrees on fewer and fewer points as the labels come in, and in this run it stops disagreeing altogether. The animation below shows the committee's random forest, one frame per round. The shading is its prediction, the coloured dots are the points labelled so far, and the white dots are the 5 points the committee asks for next. Things to look for:

  • At 10 labels the forest's boundary is blocky and wrong over large areas (test accuracy 0.574).
  • The white dots go where the members disagree, and that is where the classes meet. By round 10 (60 labels) almost every query sits on or near one of the two axes, most of them close to the origin, and the boundary has tightened onto the axes (test accuracy 0.990).
  • The corners of the square, where every model agrees, get almost no labels in the early rounds.
  • From round 19 (105 labels) the committee agrees on every point left in the pool in most rounds. Then every vote entropy is 0, the random tie-break makes the whole choice, and the white dots scatter across the square: query by committee has become random sampling, which is why the labelled points fill in evenly in the later frames.
anim_model[1].show()
The committee's random forest during one run of query by committee, one frame per round (60 rounds, 30 seconds).
os.makedirs("activeLearning", exist_ok=True)
anim_model[0].save("activeLearning/committee-svm.mp4")
anim_model[2].save("activeLearning/committee-decision-tree.mp4")

The same run seen through the other two members: the RBF SVM and the decision tree (MP4 videos of about 130 KB and 100 KB). The SVM's boundary is smooth, and near the edges of the square it bends away from the axes where there are no points to pin it down. The tree's boundary is made of axis-parallel steps like the forest's, but it changes more from one round to the next, because a single tree can reorganise its splits when a few points are added.

Next, the accuracy curves of the same run. Pool accuracy first: each member of the committee, then the committee's vote against random sampling with the same seed.

plot_accuracy(active["labels"], active["pool"], active["model_pool"], classifiers, y_title="Pool accuracy")
Pool accuracy (all 808 training points, labelled or not) of each committee member and of the committee's vote, one run of query by committee.
fig = px.line()
fig.add_scatter(x=active["labels"], y=active["pool"], name="Active learning (query by committee)")
fig.add_scatter(x=random_run["labels"], y=random_run["pool"], name="Random sampling")
fig.update_layout(xaxis_title="Labelled points", yaxis_title="Pool accuracy")
fig.show()
Pool accuracy of the committee's vote: query by committee against random sampling, one run.

Pool accuracy includes the points each learner was trained on, which the trees fit almost perfectly, so it runs a little high. The test set has no such overlap. The first version of this post plotted training accuracy here by mistake, where test accuracy was meant; these two figures show test accuracy, for each member and then for the committee against random sampling.

plot_accuracy(active["labels"], active["test"], active["model_test"], classifiers, y_title="Test accuracy")
Test accuracy (202 held-out points) of each committee member and of the committee's vote, one run of query by committee.
fig = px.line()
fig.add_scatter(x=active["labels"], y=active["test"], name="Active learning (query by committee)")
fig.add_scatter(x=random_run["labels"], y=random_run["test"], name="Random sampling")
fig.update_layout(xaxis_title="Labelled points", yaxis_title="Test accuracy")
fig.show()
Test accuracy of the committee's vote: query by committee against random sampling, one run.

In this run the committee's vote passed 95% test accuracy at 35 labels with query by committee and at 45 with random sampling, and after 310 labels it scored 0.990 against 0.975. Its pool accuracy reached 1.000 at 90 labels: from then on the committee labelled every point in the pool correctly, while random sampling stayed between 0.969 and 0.986.

One detail is worth a second look. At 10 labels the SVM alone gets 0.950 of the test points right, but the committee's vote gets only 0.604, because the two trees, both poor at that stage, outvote it. A majority vote is only as good as most of its members.

The final boundaries of the three members, after 310 labels:

plot_cluster(x_test, y_test, model=active["models"][0])
The committee's RBF SVM after 310 labels, drawn over the test points.
plot_cluster(x_test, y_test, model=active["models"][1])
The committee's random forest after 310 labels, drawn over the test points.
plot_cluster(x_test, y_test, model=active["models"][2])
The committee's decision tree after 310 labels, drawn over the test points.

Twenty runs, five strategies

One run proves nothing: the curves above depend on which 10 points happened to start and on every tie-break. So here are 20 runs (seeds 0 to 19) of each of the five strategies, 100 runs in all. Every run uses the same data and the same test set; the seed sets the starting points, the random draws and the tie-breaks.

strategies = {
    "Random sampling": "random",
    "Least confidence": "least confidence",
    "Margin": "margin",
    "Entropy": "entropy",
    "Query by committee": "committee",
}
seeds = range(20)
curves = {name: np.array([run(seed, strategy)["test"] for seed in seeds])
          for name, strategy in strategies.items()}
labels = active["labels"]
colours = {"Random sampling": "#8A93A6", "Least confidence": "#5C86B0", "Margin": "#5C86B0",
           "Entropy": "#5C86B0", "Query by committee": "#C75716"}
dashes = {"Random sampling": "solid", "Least confidence": "solid", "Margin": "dash",
          "Entropy": "dot", "Query by committee": "solid"}
banded = ("Random sampling", "Least confidence", "Query by committee")


def rgba(colour, alpha):
    red, green, blue = (int(colour[i:i + 2], 16) for i in (1, 3, 5))
    return f"rgba({red}, {green}, {blue}, {alpha})"


fig = go.Figure()
for name, curve in curves.items():
    mean = curve.mean(axis=0)
    se = curve.std(axis=0, ddof=1) / np.sqrt(len(curve))
    if name in banded:
        fig.add_trace(go.Scatter(x=np.concatenate([labels, labels[::-1]]),
                                 y=np.concatenate([mean + se, (mean - se)[::-1]]),
                                 fill="toself", fillcolor=rgba(colours[name], 0.2),
                                 line=dict(width=0), hoverinfo="skip", showlegend=False))
    fig.add_trace(go.Scatter(x=labels, y=mean, name=name,
                             line=dict(color=colours[name], dash=dashes[name], width=2)))
fig.add_hline(y=0.95, line=dict(color="#8A93A6", dash="dot", width=1))
fig.update_layout(xaxis_title="Labelled points", yaxis_title="Test accuracy, mean of 20 runs",
                  yaxis_range=[0.6, 1.0])
fig.show()
Test accuracy of the committee's vote against the number of labels, mean of 20 runs per strategy. Shaded bands are plus or minus one standard error; the dotted line is 95%. The three uncertainty-sampling curves are identical, so they share one band.
def labels_to_reach(curve, target, labels=labels):
    """Labels at the first round whose test accuracy reaches target, or NaN if none does."""
    reached = np.flatnonzero(curve >= target)
    return labels[reached[0]] if reached.size else np.nan


def mean_se(values):
    """Mean, standard error and count of the finite values."""
    values = np.asarray(values, dtype=float)
    values = values[np.isfinite(values)]
    return values.mean(), values.std(ddof=1) / np.sqrt(len(values)), len(values)


rows = {}
for name, curve in curves.items():
    row = {}
    for target in (0.95, 0.98):
        mean, se, n = mean_se([labels_to_reach(c, target) for c in curve])
        note = "" if n == len(curve) else f" ({n} of {len(curve)} runs)"
        row[f"Labels to reach {target:.0%}"] = f"{mean:.1f} ± {se:.1f}{note}"
    mean, se, _ = mean_se(curve[:, -1])
    row[f"Test accuracy at {labels[-1]} labels"] = f"{mean:.3f} ± {se:.3f}"
    rows[name] = row

q_mean, q_se, _ = mean_se([labels_to_reach(c, 0.95) for c in curves["Query by committee"]])
r_mean, r_se, _ = mean_se([labels_to_reach(c, 0.95) for c in curves["Random sampling"]])
print("Labels needed to reach 95% test accuracy (mean ± 1 standard error over 20 runs): "
      f"active (query by committee) {q_mean:.1f} ± {q_se:.1f}, random {r_mean:.1f} ± {r_se:.1f}")
pd.DataFrame(rows).T
Labels needed to reach 95% test accuracy (mean ± 1 standard error over 20 runs): active (query by committee) 41.8 ± 2.8, random 57.5 ± 5.1
Labels to reach 95% Labels to reach 98% Test accuracy at 310 labels
Random sampling 57.5 ± 5.1 126.0 ± 12.7 0.982 ± 0.002
Least confidence 61.1 ± 9.4 (19 of 20 runs) 77.4 ± 9.0 (19 of 20 runs) 0.975 ± 0.010
Margin 61.1 ± 9.4 (19 of 20 runs) 77.4 ± 9.0 (19 of 20 runs) 0.975 ± 0.010
Entropy 61.1 ± 9.4 (19 of 20 runs) 77.4 ± 9.0 (19 of 20 runs) 0.975 ± 0.010
Query by committee 41.8 ± 2.8 59.8 ± 3.4 0.986 ± 0.001

Query by committee needed 41.8 ± 2.8 labels to reach 95% test accuracy, against 57.5 ± 5.1 for random sampling: 27% fewer. For 98% the saving is larger, 59.8 ± 3.4 labels against 126.0 ± 12.7, or 53% fewer, because the last few per cent depend on points right next to the boundary, which random sampling rarely draws. After 310 labels both are at the ceiling that the random forest reached with all 808 labels (0.986 and 0.982, against 0.985), so active learning got there sooner, not higher.

The three uncertainty-sampling curves are not just close: they are identical. With two classes, least confidence, margin and entropy are all decreasing functions of the larger predicted probability, so they rank the pool in the same order; with the same seed they also break ties the same way, so they choose exactly the same points. They only differ with three or more classes. On average this single-model strategy did no better than random sampling at 95% and sat between the other two at 98%, and its mean curve is below random sampling's at almost every budget. The run-by-run numbers show why: in a typical run it beat random sampling (a median of 47.5 labels to reach 95%, against 60 for random sampling and 40 for query by committee), but two runs went badly.

for name in ("Random sampling", "Least confidence", "Query by committee"):
    reach = np.array([labels_to_reach(c, 0.95) for c in curves[name]])
    shown = ", ".join("never" if np.isnan(n) else str(int(n)) for n in reach)
    median = np.median(np.where(np.isnan(reach), np.inf, reach))
    print(f"{name}, labels to reach 95% in seeds 0 to 19: {shown} (median {median:g})")

stuck = [seed for seed in seeds if np.isnan(labels_to_reach(curves["Least confidence"][seed], 0.95))]
quadrants = {"x > 0, y > 0": (1, 1), "x < 0, y > 0": (-1, 1), "x < 0, y < 0": (-1, -1), "x > 0, y < 0": (1, -1)}

for seed in stuck:
    for strategy in ("least confidence", "committee"):
        result = run(seed, strategy, detail=True)
        forest = result["models"][1]
        chosen = x_train[result["labelled"]]
        print(f"\nSeed {seed}, {strategy}: test accuracy {result['test'][-1]:.3f} after {result['labels'][-1]} labels")
        for name, (sx, sy) in quadrants.items():
            n_labels = np.sum((np.sign(chosen[:, 0]) == sx) & (np.sign(chosen[:, 1]) == sy))
            inside = (np.sign(x_test[:, 0]) == sx) & (np.sign(x_test[:, 1]) == sy)
            accuracy = forest.score(x_test[inside], y_test[inside])
            confidence = forest.predict_proba(x_test[inside]).max(axis=1).mean()
            print(f"  quadrant {name}: {n_labels:3d} labels; forest's test accuracy there {accuracy:.3f}, "
                  f"mean top-class probability {confidence:.3f}")
Random sampling, labels to reach 95% in seeds 0 to 19: 45, 30, 80, 65, 80, 35, 60, 70, 75, 35, 70, 30, 115, 60, 55, 45, 65, 35, 75, 25 (median 60)
Least confidence, labels to reach 95% in seeds 0 to 19: 40, 40, 60, 220, 45, 40, 55, 90, 45, 35, 45, 45, 60, never, 85, 65, 45, 50, 50, 45 (median 47.5)
Query by committee, labels to reach 95% in seeds 0 to 19: 35, 20, 40, 60, 35, 30, 40, 65, 30, 50, 35, 40, 50, 55, 50, 65, 35, 40, 30, 30 (median 40)
Seed 13, least confidence: test accuracy 0.777 after 310 labels
  quadrant x > 0, y > 0: 104 labels; forest's test accuracy there 1.000, mean top-class probability 0.988
  quadrant x < 0, y > 0:   0 labels; forest's test accuracy there 0.000, mean top-class probability 1.000
  quadrant x < 0, y < 0:  86 labels; forest's test accuracy there 1.000, mean top-class probability 0.992
  quadrant x > 0, y < 0: 120 labels; forest's test accuracy there 0.981, mean top-class probability 0.984
Seed 13, committee: test accuracy 0.995 after 310 labels
  quadrant x > 0, y > 0:  67 labels; forest's test accuracy there 1.000, mean top-class probability 0.924
  quadrant x < 0, y > 0:  76 labels; forest's test accuracy there 1.000, mean top-class probability 0.932
  quadrant x < 0, y < 0:  90 labels; forest's test accuracy there 1.000, mean top-class probability 0.967
  quadrant x > 0, y < 0:  77 labels; forest's test accuracy there 0.981, mean top-class probability 0.945

Seed 13 shows what went wrong. Its 10 starting points held none from the top-left quadrant ($x < 0$, $y > 0$), so the forest stretched the neighbouring class over it. All 50 trees agreed, so the forest gave every point there a probability of 1 for the wrong class, and uncertainty sampling, which only asks about points the model is unsure of, never asked about any of them. After 310 labels it still had no label in that quadrant, got every test point there wrong, and was stuck at 0.777. Seed 3 was slow too, and reached 95% only at 220 labels. This is the sampling bias of uncertainty sampling: a model can be confidently wrong, and then it never asks the question that would correct it.

The committee started from the same 10 points and at first made the same mistake, with all three members voting for the wrong class across that quadrant. But the SVM's boundary is a smooth function of all the labelled points, so as labels piled up along the axes it moved, the SVM began to disagree with the trees over the empty quadrant, and the committee asked about it. With query by committee, seed 13 reached 95% at 55 labels.

Batch size

Every run so far labels 5 points per round. The batch size is a trade-off. With a batch of 1 the committee is retrained after every label, so every choice uses everything learnt so far, but whoever does the labelling waits for a retrain before each point. With a batch of 20 there are few rounds, but all 20 points are chosen by the same committee: none of them benefits from the labels of the others, and points from the same disputed patch can be redundant.

Here is query by committee with batches of 1, 5 and 20, over the same 20 seeds and with the same budget: 160 labels after the 10 starting points (160 divides by 1, 5 and 20), so every run ends at 170 labels. The runs with a batch of 5 are the 20 runs above, cut at 170 labels: with the same seed, run makes the same choices whatever the number of rounds, so there is nothing to re-run.

BATCH_LABELS = 160   # labels added after the 10 starting ones, so every run ends at 170
batch_sizes = (1, 5, 20)
batch_curves, batch_axis = {}, {}
for batch in batch_sizes:
    rounds = BATCH_LABELS // batch
    if batch == SAMPLES:
        batch_curves[batch] = curves["Query by committee"][:, :rounds + 1]   # the same runs, cut at 170 labels
    else:
        batch_curves[batch] = np.array([run(seed, "committee", rounds=rounds, samples=batch)["test"]
                                        for seed in seeds])
    batch_axis[batch] = N_START + batch * np.arange(rounds + 1)
def mean_band_figure(curves_by_name, axis_by_name, colour_by_name, y_title):
    fig = go.Figure()
    for name, curve in curves_by_name.items():
        mean = curve.mean(axis=0)
        se = curve.std(axis=0, ddof=1) / np.sqrt(len(curve))
        x_axis = axis_by_name[name]
        fig.add_trace(go.Scatter(x=np.concatenate([x_axis, x_axis[::-1]]),
                                 y=np.concatenate([mean + se, (mean - se)[::-1]]),
                                 fill="toself", fillcolor=rgba(colour_by_name[name], 0.2),
                                 line=dict(width=0), hoverinfo="skip", showlegend=False))
        fig.add_trace(go.Scatter(x=x_axis, y=mean, name=name, line=dict(color=colour_by_name[name], width=2)))
    fig.add_hline(y=0.95, line=dict(color="#8A93A6", dash="dot", width=1))
    fig.update_layout(xaxis_title="Labelled points", yaxis_title=y_title, yaxis_range=[0.6, 1.0])
    return fig


batch_names = {batch: f"Batch of {batch}" for batch in batch_sizes}
fig = mean_band_figure({batch_names[b]: batch_curves[b] for b in batch_sizes},
                       {batch_names[b]: batch_axis[b] for b in batch_sizes},
                       {batch_names[1]: "#5C86B0", batch_names[5]: "#C75716", batch_names[20]: "#8A93A6"},
                       "Test accuracy, mean of 20 runs")
fig.show()
Query by committee with batches of 1, 5 and 20 points per round: test accuracy of the committee's vote, mean of 20 runs each, with bands of plus or minus one standard error. The dotted line is 95%.
rows = {}
for batch in batch_sizes:
    row = {}
    for target in (0.95, 0.98):
        reach = np.array([labels_to_reach(c, target, batch_axis[batch]) for c in batch_curves[batch]])
        mean, se, n = mean_se(reach)
        row[f"Labels to reach {target:.0%}"] = f"{mean:.1f} ± {se:.1f}" + ("" if n == len(reach) else f" ({n} runs)")
        mean, se, _ = mean_se((reach - N_START) / batch)
        row[f"Rounds to reach {target:.0%}"] = f"{mean:.1f} ± {se:.1f}"
    mean, se, _ = mean_se(batch_curves[batch][:, -1])
    row[f"Test accuracy at {batch_axis[batch][-1]} labels"] = f"{mean:.3f} ± {se:.3f}"
    rows[batch_names[batch]] = row
pd.DataFrame(rows).T
Labels to reach 95% Rounds to reach 95% Labels to reach 98% Rounds to reach 98% Test accuracy at 170 labels
Batch of 1 31.1 ± 1.8 21.1 ± 1.8 44.2 ± 3.6 34.2 ± 3.6 0.986 ± 0.001
Batch of 5 41.8 ± 2.8 6.3 ± 0.6 59.8 ± 3.4 9.9 ± 0.7 0.986 ± 0.001
Batch of 20 62.0 ± 3.9 2.6 ± 0.2 92.0 ± 4.6 4.1 ± 0.2 0.986 ± 0.001

Smaller batches spent fewer labels and more rounds. To reach 98% test accuracy, query by committee needed 44.2 ± 3.6 labels in batches of 1, 59.8 ± 3.4 in batches of 5 and 92.0 ± 4.6 in batches of 20; but those took 34.2, 9.9 and 4.1 rounds, and every round is a retrain of the committee and a hand-over between the model and the labeller. Even in batches of 20 it needed fewer labels than random sampling (126.0 ± 12.7), and by 170 labels all three batch sizes are level, at 0.986 against 0.972 for random sampling. Which batch size is right depends on which is dearer: a label, or a round trip to the labeller. The batch of 20 is also coarse: it can only stop at 30, 50, 70 labels and so on, which rounds its numbers up a little.

A real data set: handwritten digits

XOR is a toy, chosen so that the boundary is easy to see. To check that the result is not an artefact of it, I ran the same code on real data: the handwritten digits that ship with scikit-learn (1,797 images of 8 × 8 pixels, so 64 features with values from 0 to 16), keeping only the 3s, 5s and 8s, three digits whose shapes overlap. A stratified 80/20 split (random_state=1) gives a pool of 431 images and a test set of 108. Everything else is as before: the same committee, a start of 10 random points (holding all three classes), batches of 5, and seeds 0 to 19, with 30 rounds, so 160 labels at the end. I chose the digits and the settings before running anything and did not try others.

Three strategies: random sampling, query by committee, and margin sampling from the committee's random forest. With three classes, least confidence, margin and entropy no longer rank the pool the same way; I ran margin only. With three members and three classes vote entropy can take three values: 0, 0.918 for a 2 to 1 split and $\log_2 3 \approx 1.585$ when all three disagree, in which case the majority vote goes to the smallest digit.

from sklearn.datasets import load_digits

digits_x, digits_y = load_digits(return_X_y=True)
keep = np.isin(digits_y, (3, 5, 8))
xd_train, xd_test, yd_train, yd_test = train_test_split(
    digits_x[keep], digits_y[keep], test_size=0.2, random_state=1, stratify=digits_y[keep])
DIGITS = (xd_train, yd_train, xd_test, yd_test)
print(f"{len(xd_train)} pool images, {len(xd_test)} test images")

# The ceiling: each member, and the committee's vote, with all the pool's labels.
committee = make_committee(0)
for name, model in zip(classifiers, committee):
    model.fit(xd_train, yd_train)
    print(f"{name:<14} test accuracy with all {len(xd_train)} labels: {model.score(xd_test, yd_test):.3f}")
votes = np.stack([model.predict(xd_test) for model in committee], axis=-1)
print(f"{'Committee':<14} test accuracy with all {len(xd_train)} labels: {accuracy_score(yd_test, output_list(votes)):.3f}")
431 pool images, 108 test images
RBF SVM        test accuracy with all 431 labels: 1.000
Random forest  test accuracy with all 431 labels: 1.000
Decision tree  test accuracy with all 431 labels: 0.944
Committee      test accuracy with all 431 labels: 1.000
DIGIT_ROUNDS = 30   # 10 + 5 * 30 = 160 labels at the end
digit_strategies = {"Random sampling": "random", "Margin": "margin", "Query by committee": "committee"}
digit_curves = {name: np.array([run(seed, strategy, rounds=DIGIT_ROUNDS, data=DIGITS)["test"] for seed in seeds])
                for name, strategy in digit_strategies.items()}
digit_axis = N_START + SAMPLES * np.arange(DIGIT_ROUNDS + 1)
fig = mean_band_figure(digit_curves, {name: digit_axis for name in digit_curves},
                       {"Random sampling": "#8A93A6", "Margin": "#5C86B0", "Query by committee": "#C75716"},
                       "Test accuracy, mean of 20 runs")
fig.show()
Digits 3, 5 and 8: test accuracy of the committee's vote against the number of labels, mean of 20 runs per strategy, with bands of plus or minus one standard error. The dotted line is 95%.
rows = {}
for name, curve in digit_curves.items():
    row = {}
    for target in (0.95, 0.98):
        mean, se, n = mean_se([labels_to_reach(c, target, digit_axis) for c in curve])
        row[f"Labels to reach {target:.0%}"] = f"{mean:.1f} ± {se:.1f}" + ("" if n == len(curve) else f" ({n} of {len(curve)} runs)")
    mean, se, _ = mean_se(curve[:, -1])
    row[f"Test accuracy at {digit_axis[-1]} labels"] = f"{mean:.3f} ± {se:.3f}"
    rows[name] = row
pd.DataFrame(rows).T
Labels to reach 95% Labels to reach 98% Test accuracy at 160 labels
Random sampling 39.8 ± 3.5 74.5 ± 4.4 0.984 ± 0.002
Margin 29.2 ± 1.6 38.5 ± 2.1 0.994 ± 0.001
Query by committee 30.0 ± 1.5 44.5 ± 2.1 0.994 ± 0.002

On real data the result holds. Query by committee needed 30.0 ± 1.5 labels to reach 95% test accuracy, against 39.8 ± 3.5 for random sampling (25% fewer), and 44.5 ± 2.1 against 74.5 ± 4.4 to reach 98% (40% fewer). Margin sampling did as well or a little better here, with 29.2 ± 1.6 and 38.5 ± 2.1, and it did not get stuck in any of the 20 runs. After 160 labels, 37% of the pool, both active strategies were at 0.994 against 0.984 for random sampling, close to the 1.000 that the committee reaches with all 431 labels. The test set is small, though: one image is 0.9 percentage points, so 95% means at most 5 mistakes and 98% at most 2, and these numbers are rougher than the XOR ones.

Conclusion

On this problem, active learning with a committee needed about a quarter fewer labels than random sampling to reach 95% test accuracy (41.8 ± 2.8 against 57.5 ± 5.1, mean ± one standard error over 20 runs), and about half as many to reach 98% (59.8 ± 3.4 against 126.0 ± 12.7). The labels went where they were most useful, along the two axes where the classes meet, and the animation shows the boundary settling onto those axes within about 60 labels.

It did not help everywhere:

  • At the start. Every strategy starts from the same 10 points, and up to about 30 labels query by committee and random sampling are level: the models are too poor for their disagreement to mean much yet. This is the cold start.
  • Once the committee agrees. In the single run the committee agreed on the whole pool in most rounds from 105 labels on, and then query by committee was random sampling by another name. Three members voting on two classes give a coarse score that runs out of information quickly.
  • At the end. After 310 labels every strategy is close to the ceiling that a random forest reaches with all 808 labels. Active learning reaches a target sooner; it does not raise the ceiling.
  • With a single, overconfident model. Uncertainty sampling from the random forest alone was stuck at 0.777 in one run of 20, because the forest was confidently wrong over a whole quadrant it had never seen.

This is a toy problem: two-dimensional, noise-free, with a boundary that trees fit exactly and an oracle that never makes mistakes. The size of the saving is specific to it, but the saving itself is not: on three of scikit-learn's handwritten digits, query by committee needed 25% fewer labels than random sampling to reach 95% and 40% fewer to reach 98%. And the batch size matters: in batches of 1 it reached 98% with 44.2 labels on XOR, in batches of 20 with 92.0, at the price of 34 rounds of retraining against 4.

When not to use active learning

Active learning is not free, and on some problems a random sample is the better buy. The cell below measures how far the labelled set drifts from the pool: the share of the points chosen in the first 10 rounds (50 per run) that lie within 0.2 of one of the axes, where the classes meet.

Show code
def near_an_axis(points, distance=0.2):
    return np.mean(np.min(np.abs(points), axis=1) < distance)


chosen_share = {}
for strategy in ("committee", "random"):
    shares = []
    for seed in seeds:
        start = run(seed, strategy, rounds=0)["labelled"]
        after = run(seed, strategy, rounds=10)["labelled"]
        shares.append(near_an_axis(x_train[after & ~start]))
    chosen_share[strategy] = np.mean(shares)
print(f"Points within 0.2 of an axis: {chosen_share['committee']:.1%} of those chosen by query by committee, "
      f"{chosen_share['random']:.1%} of those chosen by random sampling (mean of 20 runs), "
      f"{near_an_axis(x_train):.1%} of the pool")
Points within 0.2 of an axis: 47.0% of those chosen by query by committee, 16.5% of those chosen by random sampling (mean of 20 runs), 17.9% of the pool
  • Sampling bias. The labelled set is chosen by the model, so it is not a sample of the data: 47% of the points query by committee asked for lay within 0.2 of an axis, against 18% of the pool. That is the point of it, but it has costs. The labelled set cannot be used to estimate accuracy or the class balance (this post keeps a separate random test set for that), it may serve a different kind of model poorly, and a model that is confidently wrong about a region is never shown it, as seed 13 was above.
  • A noisy oracle. The queried points sit where the classes meet, which is where a person is most likely to give the wrong label. Here the oracle is a look-up and never errs. With a real labeller, active learning puts its labels, and so the labelling errors, right on the boundary, where one wrong label moves the model most.
  • Retraining cost. Every round retrains the whole committee: the 100 runs of the five-strategy comparison fitted 18,300 models (100 runs, 61 trainings each, 3 models per training), and the batch-size comparison showed that the cheaper, larger batches cost labels. With trees on a few hundred points that takes seconds; with a large neural network, the retraining between rounds can cost more than the labels it saves.

If labels are cheap, the labels are unreliable, the model is slow to retrain, or the labelled set must also serve other models and analyses, a random (or stratified) sample is the safer choice.

Takeaways

  • Query by committee with vote entropy reached 95% test accuracy on this XOR problem with 41.8 ± 2.8 labels, against 57.5 ± 5.1 for random sampling, and 98% with 59.8 ± 3.4 against 126.0 ± 12.7 (20 runs each). The saving comes from labelling the points where the classes meet, and it grows as the target rises; on three classes of real handwritten digits it was 25% fewer labels at 95% and 40% fewer at 98%.
  • Check the details that a single run hides: draw the random baseline without replacement, break ties at random with a seeded generator (three votes on two classes give only two possible scores), measure accuracy on a test set rather than on the pool, and average over many seeds with an interval. For two classes, least confidence, margin and entropy are one strategy, not three.
  • Active learning trusts the model to know where it is wrong. A single overconfident model can ignore a whole region for good (one run in 20 stuck at 0.777); a committee of different kinds of model, each able to fit the problem, is more robust, and a member that cannot fit it, like logistic regression on XOR, only adds noise.

References

  1. B. Settles, Active Learning Literature Survey, Computer Sciences Technical Report 1648, University of Wisconsin–Madison, 2009. The standard survey: pool-based and stream-based settings, uncertainty sampling, query by committee, expected model change and more.
  2. H. S. Seung, M. Opper and H. Sompolinsky, "Query by committee", Proceedings of the Fifth Annual Workshop on Computational Learning Theory (COLT), 1992, pp. 287–294. doi:10.1145/130385.130417.
  3. I. Dagan and S. P. Engelson, "Committee-based sampling for training probabilistic classifiers", Proceedings of the 12th International Conference on Machine Learning (ICML), 1995, pp. 150–157. Introduces vote entropy as the measure of committee disagreement.
  4. D. D. Lewis and W. A. Gale, "A sequential algorithm for training text classifiers", Proceedings of SIGIR, 1994. arXiv:cmp-lg/9407020. The origin of uncertainty sampling.
  5. O. Sener and S. Savarese, "Active Learning for Convolutional Neural Networks: A Core-Set Approach", ICLR, 2018. arXiv:1708.00489. Diversity (core-set) sampling.
  6. scikit-learn documentation: RandomForestClassifier.predict_proba (the mean of the trees' class fractions) and SVC.
  7. T. Danka and P. Horvath, "modAL: A modular active learning framework for Python", 2018. arXiv:1805.00979. Code and documentation at github.com/modAL-python/modAL. A library with pool-based and stream-based active learning, uncertainty sampling and query by committee, for further reading.
  8. scikit-learn documentation: load_digits, a copy of the test set of the UCI Optical Recognition of Handwritten Digits data set (E. Alpaydin and C. Kaynak, 1998).