TExcelTAD
Home › ML Projects: 15 End-to-End Builds › Project 9: Transfer Learning Classifier

Project 9: Transfer Learning Classifier

The steel mill of Project 8 opens a second line, line B, for cast aluminium plates: darker, with a grainy surface instead of streaks, and the same four classes (ok, scratch, spot, crack). The line-A model works well, so the first idea is to reuse it. The inspectors can label a few patches per class this week, not 1,200. Which way to a usable line-B classifier needs the fewest labels: the line-A model as it is, ImageNet features, fine-tuning, or training from scratch? The level is intermediate; the main skills are measuring a domain shift, frozen-feature transfer, partial and full fine-tuning, a learning curve over the label budget and choosing the source model.

The ResNet-18 transfer lesson showed ImageNet features winning easily on photographed textures, and the training-strategies mini project compared three strategies on text. This project differs in two ways: there are two candidate sources, a large general model (ImageNet ResNet-18) and a tiny model from the neighbouring task (the line-A CNN), and the target images are small, grey and unlike photos. The result is not the one the textbooks lead you to expect, which is the point of measuring.

ImageNet ResNet-1811.7 M params, photos line-A CNN23,780 params, steel no sourcerandom weights frozen features + LR (Step 3)layer4 fine-tuned (Step 4) as it is (Step 1), frozen + LR,all layers fine-tuned (Step 5) classical features (Step 2)CNN from scratch (Step 5) line B classifier5 to 50 labels/class

Goal and success criteria

Criterion Target Measured on
test accuracy on line B at least 0.85 800 line-B test patches (40 % ok, as in Project 8)
escape rate on line B (defects passed as ok) at most 0.05 at the plain argmax the same
label budget at most 50 labelled patches per class
deliverable a learning curve for every strategy and a recommendation: which source, how many labels

This is a comparison study, like the strategies mini project: every strategy and budget is reported on the same test set, and every choice inside a strategy (regularisation C, the best epoch) is made on a separate validation set of 20 patches per class. No number is tuned on the test set. The recommended model then gets its own acceptance test on new line-B data, as in Project 8, before it inspects anything.

The data

The generator is Project 8's make_defect, unchanged; line="B" draws the cast surface: mean grey 95 instead of 135, blob-like grain (noise blurred in both directions) instead of streaks. The defects are drawn the same way, so the classes mean the same thing on both lines. From a generator seeded with 9:

  • a labelled pool of 50 patches per class; the budget "n per class" always takes the first n of each class, so a larger budget contains the smaller ones and the curves differ only by the extra labels;
  • a validation set of 20 per class (balanced, so its accuracy is not directly comparable with the test accuracy);
  • a test set of 800 patches with the usual shares (40 % ok).

Line A comes from Project 8's seed (8), so the line-A model below is exactly Project 8's model. In a real plant the line-B patches would be labelled by the same inspectors with the same guideline, which is what makes the line-A model a sensible source at all (ground truth and annotation).

Step 1: does the line-A model work on line B?

Always measure the shift before planning the fix (distribution shift). The program rebuilds Project 8's CNN (same data, same recipe, recorded: PyTorch, CPU, about 10 s) and tests it on both lines.

python · try it yourself
import numpy as np, cv2

CLASSES = ["ok", "scratch", "spot", "crack"]

def make_defect(rng, c, size=48, line="A"):
    """One grey surface patch (uint8, size x size) of class c from production line "A" or "B".
    Also returns the defect's length in pixels and its contrast in grey levels (0, 0 for "ok")."""
    if line == "A":                                   # brushed steel: horizontal streaks
        streak = cv2.GaussianBlur(rng.normal(0, 1, (size, size)), (0, 0), sigmaX=8, sigmaY=0.7)
        img = 135 + 9 * streak / streak.std() + rng.normal(0, 5, (size, size))
    else:                                             # cast aluminium: darker and grainy
        grain = cv2.GaussianBlur(rng.normal(0, 1, (size, size)), (0, 0), sigmaX=1.5)
        img = 95 + 10 * grain / grain.std() + rng.normal(0, 4, (size, size))
    img += np.linspace(-1, 1, size)[None, :] * rng.uniform(-12, 12)    # uneven lighting
    m = np.zeros((size, size), np.float32)
    length, contrast = 0.0, 0.0
    if c == 1:                                        # scratch: long, straight, thin, bright
        length = rng.uniform(18, 40); a = rng.uniform(0, np.pi)
        cx, cy = rng.uniform(14, size - 14, 2)
        dx, dy = np.cos(a) * length / 2, np.sin(a) * length / 2
        cv2.line(m, (int(cx - dx), int(cy - dy)), (int(cx + dx), int(cy + dy)), 1.0, 1, cv2.LINE_AA)
        contrast = rng.uniform(12, 45)
    elif c == 2:                                      # spot: small, round, dark
        r = rng.uniform(1.5, 5); length = 2 * r
        cv2.circle(m, tuple(int(v) for v in rng.uniform(8, size - 8, 2)), int(round(r)), 1.0, -1, cv2.LINE_AA)
        m = cv2.GaussianBlur(m, (0, 0), 0.8)
        contrast = -rng.uniform(15, 55)
    elif c == 3:                                      # crack: jagged dark random walk
        p = rng.uniform(12, size - 12, 2); a = rng.uniform(0, 2 * np.pi)
        steps = int(rng.integers(5, 10))
        for _ in range(steps):
            a += rng.normal(0, 0.6)
            q = np.clip(p + 3 * np.array([np.cos(a), np.sin(a)]), 1, size - 2)
            cv2.line(m, (int(p[0]), int(p[1])), (int(q[0]), int(q[1])), 1.0, 1, cv2.LINE_AA)
            p = q
        length = 3.0 * steps
        contrast = -rng.uniform(15, 50)
    img = img + contrast * m
    return np.clip(img, 0, 255).astype(np.uint8), length, abs(contrast)

def make_set(rng, n, line="A", p=(0.4, 0.2, 0.2, 0.2)):
    """n patches with class shares p; returns images (n, 48, 48), labels, defect lengths, contrasts."""
    y = rng.choice(4, size=n, p=p)
    out = [make_defect(rng, int(c), line=line) for c in y]
    return np.stack([o[0] for o in out]), y, np.array([o[1] for o in out]), np.array([o[2] for o in out])

import copy
import torch
from torch import nn

def to_tensor(X):                                 # uint8 (n, 48, 48) -> float (n, 1, 48, 48), about -1..1
    return torch.tensor((X.astype(np.float32) - 128) / 32)[:, None]

def make_cnn():
    block = lambda i, o: [nn.Conv2d(i, o, 3, padding=1), nn.BatchNorm2d(o), nn.ReLU()]
    return nn.Sequential(*block(1, 16), nn.MaxPool2d(2), *block(16, 32), nn.MaxPool2d(2), *block(32, 64),
                         nn.AdaptiveMaxPool2d(1), nn.Flatten(), nn.Linear(64, 4))   # max: "is it anywhere?"

def augment(xb, aug):
    if aug in ("flips", "flips + transpose"):
        if torch.rand(1).item() < 0.5: xb = xb.flip(3)        # left-right
        if torch.rand(1).item() < 0.5: xb = xb.flip(2)        # up-down
    if aug == "flips + transpose" and torch.rand(1).item() < 0.5:
        xb = xb.transpose(2, 3)                                # streaks become vertical
    return xb

def train_cnn(Xt, yt, Xv, yv, aug="flips", epochs=12, seed=0):
    """Adam 3e-3, batches of 32; returns the model at the epoch with the best validation accuracy."""
    torch.manual_seed(seed)
    model = make_cnn(); opt = torch.optim.Adam(model.parameters(), lr=3e-3)
    best = (-1.0, None, 0)
    for epoch in range(1, epochs + 1):
        model.train()
        for idx in torch.randperm(len(yt)).split(32):
            loss = nn.functional.cross_entropy(model(augment(Xt[idx], aug)), yt[idx])
            opt.zero_grad(); loss.backward(); opt.step()
        model.eval()
        with torch.no_grad():
            acc = (model(Xv).argmax(1) == yv).float().mean().item()
        if acc > best[0]:
            best = (acc, copy.deepcopy(model.state_dict()), epoch)
    model.load_state_dict(best[1]); model.eval()
    return model, best[2]

def make_balanced(rng, per_class, line):
    """per_class patches of each class, shuffled: the labelled pool and validation set of the new line."""
    y = np.repeat(np.arange(4), per_class); rng.shuffle(y)
    return np.stack([make_defect(rng, int(c), line=line)[0] for c in y]), y

rng = np.random.default_rng(9)
XB_pool, yB_pool = make_balanced(rng, 50, "B")                  # labelled by the inspectors, 50 per class
XB_va, yB_va = make_balanced(rng, 20, "B")                      # validation: 20 per class
XB_te, yB_te, _, _ = make_set(rng, 800, line="B")               # test: 800 patches with the usual shares
BUDGETS = [5, 10, 20, 50]

def budget(n):
    """The first n labelled patches of each class: a larger budget contains the smaller ones."""
    return np.concatenate([np.flatnonzero(yB_pool == c)[:n] for c in range(4)])

rng = np.random.default_rng(8)                                  # Project 8's line A data, same seed
X_tr, y_tr, _, _ = make_set(rng, 1200)
X_va, y_va, _, _ = make_set(rng, 400)
X_te, y_te, _, _ = make_set(rng, 800)
model_a, epoch = train_cnn(to_tensor(X_tr), torch.tensor(y_tr), to_tensor(X_va), torch.tensor(y_va), aug="flips")

def evaluate(name, X, y):
    with torch.no_grad():
        pred = model_a(to_tensor(X)).argmax(1).numpy()
    print(f"{name}: accuracy {(pred == y).mean():.3f}  escape {(pred[y > 0] == 0).mean():.3f}  "
          f"false reject {(pred[y == 0] > 0).mean():.3f}  predicted per class {np.bincount(pred, minlength=4).tolist()}")

evaluate("line A test (800)", X_te, y_te)
evaluate("line B test (800)", XB_te, yB_te)
print("line B test, true per class:", np.bincount(yB_te).tolist())
print(f"mean grey: line A {X_tr.mean():.1f}, line B {XB_pool.mean():.1f}; "
      f"input after (x - 128) / 32: A {to_tensor(X_tr).mean():.2f}, B {to_tensor(XB_pool).mean():.2f}")
line A test (800): accuracy 0.984  escape 0.013  false reject 0.012  predicted per class [339, 162, 143, 156]
line B test (800): accuracy 0.282  escape 0.000  false reject 1.000  predicted per class [0, 25, 722, 53]
line B test, true per class: [317, 173, 149, 161]
mean grey: line A 134.4, line B 94.4; input after (x - 128) / 32: A 0.20, B -1.05

On line A the model is as good as in Project 8 (0.984). On line B it is useless: accuracy 0.282, below "always ok" (0.396). It calls 722 of 800 patches a spot, so nothing escapes and every good plate is rejected. The grain of line B is a field of dark blobs, which is what the model learned a spot looks like. On top, the input moved: line B is 40 grey levels darker, so after Project 8's fixed scaling its mean is -1.05 instead of 0.20, a region the network never saw. A model is a summary of its training distribution; a new line is a new distribution, even with the same classes.

Step 2: a classical baseline with few labels

Project 8's best classical features (pooled residual statistics, 23 numbers) with logistic regression, trained on each budget, C chosen on validation. This runs in your browser.

python · try it yourself
import numpy as np, cv2

CLASSES = ["ok", "scratch", "spot", "crack"]

def make_defect(rng, c, size=48, line="A"):
    """One grey surface patch (uint8, size x size) of class c from production line "A" or "B".
    Also returns the defect's length in pixels and its contrast in grey levels (0, 0 for "ok")."""
    if line == "A":                                   # brushed steel: horizontal streaks
        streak = cv2.GaussianBlur(rng.normal(0, 1, (size, size)), (0, 0), sigmaX=8, sigmaY=0.7)
        img = 135 + 9 * streak / streak.std() + rng.normal(0, 5, (size, size))
    else:                                             # cast aluminium: darker and grainy
        grain = cv2.GaussianBlur(rng.normal(0, 1, (size, size)), (0, 0), sigmaX=1.5)
        img = 95 + 10 * grain / grain.std() + rng.normal(0, 4, (size, size))
    img += np.linspace(-1, 1, size)[None, :] * rng.uniform(-12, 12)    # uneven lighting
    m = np.zeros((size, size), np.float32)
    length, contrast = 0.0, 0.0
    if c == 1:                                        # scratch: long, straight, thin, bright
        length = rng.uniform(18, 40); a = rng.uniform(0, np.pi)
        cx, cy = rng.uniform(14, size - 14, 2)
        dx, dy = np.cos(a) * length / 2, np.sin(a) * length / 2
        cv2.line(m, (int(cx - dx), int(cy - dy)), (int(cx + dx), int(cy + dy)), 1.0, 1, cv2.LINE_AA)
        contrast = rng.uniform(12, 45)
    elif c == 2:                                      # spot: small, round, dark
        r = rng.uniform(1.5, 5); length = 2 * r
        cv2.circle(m, tuple(int(v) for v in rng.uniform(8, size - 8, 2)), int(round(r)), 1.0, -1, cv2.LINE_AA)
        m = cv2.GaussianBlur(m, (0, 0), 0.8)
        contrast = -rng.uniform(15, 55)
    elif c == 3:                                      # crack: jagged dark random walk
        p = rng.uniform(12, size - 12, 2); a = rng.uniform(0, 2 * np.pi)
        steps = int(rng.integers(5, 10))
        for _ in range(steps):
            a += rng.normal(0, 0.6)
            q = np.clip(p + 3 * np.array([np.cos(a), np.sin(a)]), 1, size - 2)
            cv2.line(m, (int(p[0]), int(p[1])), (int(q[0]), int(q[1])), 1.0, 1, cv2.LINE_AA)
            p = q
        length = 3.0 * steps
        contrast = -rng.uniform(15, 50)
    img = img + contrast * m
    return np.clip(img, 0, 255).astype(np.uint8), length, abs(contrast)

def make_set(rng, n, line="A", p=(0.4, 0.2, 0.2, 0.2)):
    """n patches with class shares p; returns images (n, 48, 48), labels, defect lengths, contrasts."""
    y = rng.choice(4, size=n, p=p)
    out = [make_defect(rng, int(c), line=line) for c in y]
    return np.stack([o[0] for o in out]), y, np.array([o[1] for o in out]), np.array([o[2] for o in out])

def make_balanced(rng, per_class, line):
    """per_class patches of each class, shuffled: the labelled pool and validation set of the new line."""
    y = np.repeat(np.arange(4), per_class); rng.shuffle(y)
    return np.stack([make_defect(rng, int(c), line=line)[0] for c in y]), y

rng = np.random.default_rng(9)
XB_pool, yB_pool = make_balanced(rng, 50, "B")                  # labelled by the inspectors, 50 per class
XB_va, yB_va = make_balanced(rng, 20, "B")                      # validation: 20 per class
XB_te, yB_te, _, _ = make_set(rng, 800, line="B")               # test: 800 patches with the usual shares
BUDGETS = [5, 10, 20, 50]

def budget(n):
    """The first n labelled patches of each class: a larger budget contains the smaller ones."""
    return np.concatenate([np.flatnonzero(yB_pool == c)[:n] for c in range(4)])
from skimage.feature import hog
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline

def pooled_features(X):                                         # Project 8's position-free features, unchanged
    out = []
    for x in X.astype(np.float32):
        r = x - cv2.blur(x, (15, 3))
        h = hog(r, orientations=8, pixels_per_cell=(8, 8), cells_per_block=(1, 1), feature_vector=False).reshape(-1, 8)
        out.append(np.concatenate([h.max(0), h.mean(0), np.percentile(r, [0.5, 2, 50, 98, 99.5]),
                                   [(r < -12).sum(), (r > 12).sum()]]))
    return np.array(out)

print("pool:", np.bincount(yB_pool).tolist(), "| val:", np.bincount(yB_va).tolist(), "| test:", np.bincount(yB_te).tolist())
print(f"always 'ok' on the line B test set: {(yB_te == 0).mean():.3f}")
F_pool, F_va, F_te = pooled_features(XB_pool), pooled_features(XB_va), pooled_features(XB_te)
for n in BUDGETS:
    idx = budget(n)
    fits = [make_pipeline(StandardScaler(), LogisticRegression(C=C, max_iter=5000)).fit(F_pool[idx], yB_pool[idx])
            for C in [0.01, 0.1, 1, 10]]
    best = max(fits, key=lambda m: m.score(F_va, yB_va))         # C chosen on validation
    pred = best.predict(F_te)
    print(f"{n:2d} labels per class: C = {best[-1].C:<5} val {best.score(F_va, yB_va):.3f}  test {(pred == yB_te).mean():.3f}"
          f"  escape {(pred[yB_te > 0] == 0).mean():.3f}")
pool: [50, 50, 50, 50] | val: [20, 20, 20, 20] | test: [317, 173, 149, 161]
always 'ok' on the line B test set: 0.396
 5 labels per class: C = 0.1   val 0.412  test 0.504  escape 0.296
10 labels per class: C = 0.01  val 0.438  test 0.552  escape 0.265
20 labels per class: C = 1     val 0.475  test 0.491  escape 0.211
50 labels per class: C = 10    val 0.625  test 0.516  escape 0.126

The classical features stay around 0.5, about 0.1 above "always ok" (0.396), and do not improve with more labels: they were designed for line A. The horizontal blur that removed the streaks does nothing useful against round grains, and the "very dark pixel" counts fire on every grain. Hand-made features transfer only as far as the assumptions behind them.

Step 3: ImageNet features, frozen

The standard first move with few labels: a network pretrained on ImageNet, its classification layer removed, its 512-number pooled output used as features for logistic regression (feature extraction). The patches are grey and 48 pixels wide; ResNet-18 expects three channels with ImageNet's normalisation, and it shrinks the input 32 times, so the patch is also tried at double size (96 x 96, bilinear). Recorded, about 8 s.

python · try it yourself
import numpy as np, cv2

CLASSES = ["ok", "scratch", "spot", "crack"]

def make_defect(rng, c, size=48, line="A"):
    """One grey surface patch (uint8, size x size) of class c from production line "A" or "B".
    Also returns the defect's length in pixels and its contrast in grey levels (0, 0 for "ok")."""
    if line == "A":                                   # brushed steel: horizontal streaks
        streak = cv2.GaussianBlur(rng.normal(0, 1, (size, size)), (0, 0), sigmaX=8, sigmaY=0.7)
        img = 135 + 9 * streak / streak.std() + rng.normal(0, 5, (size, size))
    else:                                             # cast aluminium: darker and grainy
        grain = cv2.GaussianBlur(rng.normal(0, 1, (size, size)), (0, 0), sigmaX=1.5)
        img = 95 + 10 * grain / grain.std() + rng.normal(0, 4, (size, size))
    img += np.linspace(-1, 1, size)[None, :] * rng.uniform(-12, 12)    # uneven lighting
    m = np.zeros((size, size), np.float32)
    length, contrast = 0.0, 0.0
    if c == 1:                                        # scratch: long, straight, thin, bright
        length = rng.uniform(18, 40); a = rng.uniform(0, np.pi)
        cx, cy = rng.uniform(14, size - 14, 2)
        dx, dy = np.cos(a) * length / 2, np.sin(a) * length / 2
        cv2.line(m, (int(cx - dx), int(cy - dy)), (int(cx + dx), int(cy + dy)), 1.0, 1, cv2.LINE_AA)
        contrast = rng.uniform(12, 45)
    elif c == 2:                                      # spot: small, round, dark
        r = rng.uniform(1.5, 5); length = 2 * r
        cv2.circle(m, tuple(int(v) for v in rng.uniform(8, size - 8, 2)), int(round(r)), 1.0, -1, cv2.LINE_AA)
        m = cv2.GaussianBlur(m, (0, 0), 0.8)
        contrast = -rng.uniform(15, 55)
    elif c == 3:                                      # crack: jagged dark random walk
        p = rng.uniform(12, size - 12, 2); a = rng.uniform(0, 2 * np.pi)
        steps = int(rng.integers(5, 10))
        for _ in range(steps):
            a += rng.normal(0, 0.6)
            q = np.clip(p + 3 * np.array([np.cos(a), np.sin(a)]), 1, size - 2)
            cv2.line(m, (int(p[0]), int(p[1])), (int(q[0]), int(q[1])), 1.0, 1, cv2.LINE_AA)
            p = q
        length = 3.0 * steps
        contrast = -rng.uniform(15, 50)
    img = img + contrast * m
    return np.clip(img, 0, 255).astype(np.uint8), length, abs(contrast)

def make_set(rng, n, line="A", p=(0.4, 0.2, 0.2, 0.2)):
    """n patches with class shares p; returns images (n, 48, 48), labels, defect lengths, contrasts."""
    y = rng.choice(4, size=n, p=p)
    out = [make_defect(rng, int(c), line=line) for c in y]
    return np.stack([o[0] for o in out]), y, np.array([o[1] for o in out]), np.array([o[2] for o in out])
import torch
from torch import nn

def make_balanced(rng, per_class, line):
    """per_class patches of each class, shuffled: the labelled pool and validation set of the new line."""
    y = np.repeat(np.arange(4), per_class); rng.shuffle(y)
    return np.stack([make_defect(rng, int(c), line=line)[0] for c in y]), y

rng = np.random.default_rng(9)
XB_pool, yB_pool = make_balanced(rng, 50, "B")                  # labelled by the inspectors, 50 per class
XB_va, yB_va = make_balanced(rng, 20, "B")                      # validation: 20 per class
XB_te, yB_te, _, _ = make_set(rng, 800, line="B")               # test: 800 patches with the usual shares
BUDGETS = [5, 10, 20, 50]

def budget(n):
    """The first n labelled patches of each class: a larger budget contains the smaller ones."""
    return np.concatenate([np.flatnonzero(yB_pool == c)[:n] for c in range(4)])
from torchvision.models import resnet18, ResNet18_Weights
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline

net = resnet18(weights=ResNet18_Weights.IMAGENET1K_V1).eval()   # eval(): batch norm keeps ImageNet statistics
net.fc = nn.Identity()                                          # output: the 512-number pooled feature vector
MEAN = torch.tensor([0.485, 0.456, 0.406])[:, None, None]
STD = torch.tensor([0.229, 0.224, 0.225])[:, None, None]

def imagenet_input(X, size):
    """grey uint8 (n, 48, 48) -> the input ResNet-18 was trained on: 3 channels, ImageNet normalisation."""
    x = torch.tensor(X.astype(np.float32) / 255)[:, None]
    if size != 48:
        x = nn.functional.interpolate(x, size=(size, size), mode="bilinear", align_corners=False)
    return (x.repeat(1, 3, 1, 1) - MEAN) / STD

def features(X, size):
    with torch.no_grad():
        return torch.cat([net(b) for b in imagenet_input(X, size).split(200)]).numpy()

for size in [48, 96]:
    F_pool, F_va, F_te = features(XB_pool, size), features(XB_va, size), features(XB_te, size)
    row = []
    for n in BUDGETS:
        idx = budget(n)
        fits = [make_pipeline(StandardScaler(), LogisticRegression(C=C, max_iter=5000)).fit(F_pool[idx], yB_pool[idx])
                for C in [0.01, 0.1, 1]]
        best = max(fits, key=lambda m: m.score(F_va, yB_va))
        row.append(f"{n}: {best.score(F_te, yB_te):.3f}")
    print(f"frozen ResNet-18, input {size}x{size}, features {F_pool.shape[1]}: test accuracy by labels per class  "
          + "  ".join(row))
frozen ResNet-18, input 48x48, features 512: test accuracy by labels per class  5: 0.415  10: 0.496  20: 0.535  50: 0.576
frozen ResNet-18, input 96x96, features 512: test accuracy by labels per class  5: 0.484  10: 0.580  20: 0.604  50: 0.703

Better than the classical features from 10 labels per class on, and clearly better at 96 pixels than at 48 (0.703 against 0.576 with 50 labels per class): at 48 pixels the last stage works on a 2 x 2 map, and a 3-pixel spot is gone after the first few downsamplings. But even the best is far below the target. ImageNet's top-level features describe objects in photographs; whether a grain is a little darker than its neighbours is not something they were made to encode.

Step 4: fine-tuning ResNet-18's last stage

The next move is to let the last stage adapt (partial fine-tuning): layer4 (8.4 million parameters) and a new 4-class head are trained on line B, the rest stays frozen. Two engineering details make this cheap and correct on a CPU:

  • Everything up to layer3 is frozen and in eval() mode, so its output for a given patch never changes. It is computed once for all patches and cached; every epoch then runs only layer4 and the head. (This works because the training uses no augmentation; with random flips the cache would have to hold every flipped version.)
  • layer4 keeps ImageNet's batch-norm statistics (the module stays in eval()), and gets a learning rate 10 times smaller than the new head, as in the ResNet lesson.

Recorded, about 25 s for the four budgets.

python · try it yourself
import numpy as np, cv2

CLASSES = ["ok", "scratch", "spot", "crack"]

def make_defect(rng, c, size=48, line="A"):
    """One grey surface patch (uint8, size x size) of class c from production line "A" or "B".
    Also returns the defect's length in pixels and its contrast in grey levels (0, 0 for "ok")."""
    if line == "A":                                   # brushed steel: horizontal streaks
        streak = cv2.GaussianBlur(rng.normal(0, 1, (size, size)), (0, 0), sigmaX=8, sigmaY=0.7)
        img = 135 + 9 * streak / streak.std() + rng.normal(0, 5, (size, size))
    else:                                             # cast aluminium: darker and grainy
        grain = cv2.GaussianBlur(rng.normal(0, 1, (size, size)), (0, 0), sigmaX=1.5)
        img = 95 + 10 * grain / grain.std() + rng.normal(0, 4, (size, size))
    img += np.linspace(-1, 1, size)[None, :] * rng.uniform(-12, 12)    # uneven lighting
    m = np.zeros((size, size), np.float32)
    length, contrast = 0.0, 0.0
    if c == 1:                                        # scratch: long, straight, thin, bright
        length = rng.uniform(18, 40); a = rng.uniform(0, np.pi)
        cx, cy = rng.uniform(14, size - 14, 2)
        dx, dy = np.cos(a) * length / 2, np.sin(a) * length / 2
        cv2.line(m, (int(cx - dx), int(cy - dy)), (int(cx + dx), int(cy + dy)), 1.0, 1, cv2.LINE_AA)
        contrast = rng.uniform(12, 45)
    elif c == 2:                                      # spot: small, round, dark
        r = rng.uniform(1.5, 5); length = 2 * r
        cv2.circle(m, tuple(int(v) for v in rng.uniform(8, size - 8, 2)), int(round(r)), 1.0, -1, cv2.LINE_AA)
        m = cv2.GaussianBlur(m, (0, 0), 0.8)
        contrast = -rng.uniform(15, 55)
    elif c == 3:                                      # crack: jagged dark random walk
        p = rng.uniform(12, size - 12, 2); a = rng.uniform(0, 2 * np.pi)
        steps = int(rng.integers(5, 10))
        for _ in range(steps):
            a += rng.normal(0, 0.6)
            q = np.clip(p + 3 * np.array([np.cos(a), np.sin(a)]), 1, size - 2)
            cv2.line(m, (int(p[0]), int(p[1])), (int(q[0]), int(q[1])), 1.0, 1, cv2.LINE_AA)
            p = q
        length = 3.0 * steps
        contrast = -rng.uniform(15, 50)
    img = img + contrast * m
    return np.clip(img, 0, 255).astype(np.uint8), length, abs(contrast)

def make_set(rng, n, line="A", p=(0.4, 0.2, 0.2, 0.2)):
    """n patches with class shares p; returns images (n, 48, 48), labels, defect lengths, contrasts."""
    y = rng.choice(4, size=n, p=p)
    out = [make_defect(rng, int(c), line=line) for c in y]
    return np.stack([o[0] for o in out]), y, np.array([o[1] for o in out]), np.array([o[2] for o in out])
import copy
import torch
from torch import nn

def make_balanced(rng, per_class, line):
    """per_class patches of each class, shuffled: the labelled pool and validation set of the new line."""
    y = np.repeat(np.arange(4), per_class); rng.shuffle(y)
    return np.stack([make_defect(rng, int(c), line=line)[0] for c in y]), y

rng = np.random.default_rng(9)
XB_pool, yB_pool = make_balanced(rng, 50, "B")                  # labelled by the inspectors, 50 per class
XB_va, yB_va = make_balanced(rng, 20, "B")                      # validation: 20 per class
XB_te, yB_te, _, _ = make_set(rng, 800, line="B")               # test: 800 patches with the usual shares
BUDGETS = [5, 10, 20, 50]

def budget(n):
    """The first n labelled patches of each class: a larger budget contains the smaller ones."""
    return np.concatenate([np.flatnonzero(yB_pool == c)[:n] for c in range(4)])
from torchvision.models import resnet18, ResNet18_Weights

net = resnet18(weights=ResNet18_Weights.IMAGENET1K_V1).eval()
MEAN = torch.tensor([0.485, 0.456, 0.406])[:, None, None]
STD = torch.tensor([0.229, 0.224, 0.225])[:, None, None]
def imagenet_input(X, size=96):
    x = nn.functional.interpolate(torch.tensor(X.astype(np.float32) / 255)[:, None], size=(size, size),
                                  mode="bilinear", align_corners=False)
    return (x.repeat(1, 3, 1, 1) - MEAN) / STD

# Everything up to layer3 stays frozen and in eval() mode, so its output never changes: compute it once.
frozen = nn.Sequential(net.conv1, net.bn1, net.relu, net.maxpool, net.layer1, net.layer2, net.layer3)
with torch.no_grad():
    C_pool, C_va, C_te = (torch.cat([frozen(b) for b in imagenet_input(X).split(200)]) for X in (XB_pool, XB_va, XB_te))
print("cached layer3 output per patch:", tuple(C_pool.shape[1:]))

for n in BUDGETS:
    idx = torch.tensor(budget(n)); y = torch.tensor(yB_pool)[idx]
    torch.manual_seed(0)
    top = nn.Sequential(copy.deepcopy(net.layer4), nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(512, 4)).eval()
    opt = torch.optim.Adam([{"params": top[0].parameters(), "lr": 1e-4},          # pretrained: small steps
                            {"params": top[3].parameters(), "lr": 1e-3}])         # new head: larger steps
    best = (-1.0, None, 0)
    for epoch in range(1, 16):
        for b in torch.randperm(len(y)).split(16):          # top stays in eval(): BN statistics are ImageNet's
            loss = nn.functional.cross_entropy(top(C_pool[idx][b]), y[b])
            opt.zero_grad(); loss.backward(); opt.step()
        with torch.no_grad():
            acc = (top(C_va).argmax(1).numpy() == yB_va).mean()
        if acc > best[0]:
            best = (acc, copy.deepcopy(top.state_dict()), epoch)
    top.load_state_dict(best[1])
    with torch.no_grad():
        pred = top(C_te).argmax(1).numpy()
    print(f"layer4 + head fine-tuned, {n:2d} labels per class: best epoch {best[2]:2d}  test accuracy {(pred == yB_te).mean():.3f}"
          f"  escape {(pred[yB_te > 0] == 0).mean():.3f}")
cached layer3 output per patch: (256, 6, 6)
layer4 + head fine-tuned,  5 labels per class: best epoch  5  test accuracy 0.706  escape 0.257
layer4 + head fine-tuned, 10 labels per class: best epoch 10  test accuracy 0.734  escape 0.337
layer4 + head fine-tuned, 20 labels per class: best epoch  2  test accuracy 0.760  escape 0.251
layer4 + head fine-tuned, 50 labels per class: best epoch  7  test accuracy 0.765  escape 0.195

Fine-tuning layer4 lifts every budget, most at 5 labels per class (0.706 against 0.484 frozen), but the curve flattens at about 0.76, and a fifth to a third of the defects escape. With a few hundred patches, 8.4 million parameters adapt only so far, and the frozen layers below still deliver ImageNet's description of the patch.

Step 5: the neighbour as the source

The line-A CNN from Project 8 is tiny and was trained on 1,200 patches only, but on the same task: the same defects, a similar camera, a texture to ignore. Three ways to use it, against the same CNN trained from scratch on line B alone (training from scratch, the fine-tuning recipe):

  • (a) frozen line-A CNN, its 64 pooled features into logistic regression;
  • (b) fine-tuned: all layers of the line-A CNN trained on the line-B labels, learning rate 1e-3 (a third of Project 8's), flips, 30 epochs, the best validation epoch kept; batch norm in train() mode is right here, because the whole network should adapt to the new statistics;
  • (c) from scratch: Project 8's recipe on the line-B labels only, 30 epochs.

Recorded, about 25 s.

python · try it yourself
import numpy as np, cv2

CLASSES = ["ok", "scratch", "spot", "crack"]

def make_defect(rng, c, size=48, line="A"):
    """One grey surface patch (uint8, size x size) of class c from production line "A" or "B".
    Also returns the defect's length in pixels and its contrast in grey levels (0, 0 for "ok")."""
    if line == "A":                                   # brushed steel: horizontal streaks
        streak = cv2.GaussianBlur(rng.normal(0, 1, (size, size)), (0, 0), sigmaX=8, sigmaY=0.7)
        img = 135 + 9 * streak / streak.std() + rng.normal(0, 5, (size, size))
    else:                                             # cast aluminium: darker and grainy
        grain = cv2.GaussianBlur(rng.normal(0, 1, (size, size)), (0, 0), sigmaX=1.5)
        img = 95 + 10 * grain / grain.std() + rng.normal(0, 4, (size, size))
    img += np.linspace(-1, 1, size)[None, :] * rng.uniform(-12, 12)    # uneven lighting
    m = np.zeros((size, size), np.float32)
    length, contrast = 0.0, 0.0
    if c == 1:                                        # scratch: long, straight, thin, bright
        length = rng.uniform(18, 40); a = rng.uniform(0, np.pi)
        cx, cy = rng.uniform(14, size - 14, 2)
        dx, dy = np.cos(a) * length / 2, np.sin(a) * length / 2
        cv2.line(m, (int(cx - dx), int(cy - dy)), (int(cx + dx), int(cy + dy)), 1.0, 1, cv2.LINE_AA)
        contrast = rng.uniform(12, 45)
    elif c == 2:                                      # spot: small, round, dark
        r = rng.uniform(1.5, 5); length = 2 * r
        cv2.circle(m, tuple(int(v) for v in rng.uniform(8, size - 8, 2)), int(round(r)), 1.0, -1, cv2.LINE_AA)
        m = cv2.GaussianBlur(m, (0, 0), 0.8)
        contrast = -rng.uniform(15, 55)
    elif c == 3:                                      # crack: jagged dark random walk
        p = rng.uniform(12, size - 12, 2); a = rng.uniform(0, 2 * np.pi)
        steps = int(rng.integers(5, 10))
        for _ in range(steps):
            a += rng.normal(0, 0.6)
            q = np.clip(p + 3 * np.array([np.cos(a), np.sin(a)]), 1, size - 2)
            cv2.line(m, (int(p[0]), int(p[1])), (int(q[0]), int(q[1])), 1.0, 1, cv2.LINE_AA)
            p = q
        length = 3.0 * steps
        contrast = -rng.uniform(15, 50)
    img = img + contrast * m
    return np.clip(img, 0, 255).astype(np.uint8), length, abs(contrast)

def make_set(rng, n, line="A", p=(0.4, 0.2, 0.2, 0.2)):
    """n patches with class shares p; returns images (n, 48, 48), labels, defect lengths, contrasts."""
    y = rng.choice(4, size=n, p=p)
    out = [make_defect(rng, int(c), line=line) for c in y]
    return np.stack([o[0] for o in out]), y, np.array([o[1] for o in out]), np.array([o[2] for o in out])

import copy
import torch
from torch import nn

def to_tensor(X):                                 # uint8 (n, 48, 48) -> float (n, 1, 48, 48), about -1..1
    return torch.tensor((X.astype(np.float32) - 128) / 32)[:, None]

def make_cnn():
    block = lambda i, o: [nn.Conv2d(i, o, 3, padding=1), nn.BatchNorm2d(o), nn.ReLU()]
    return nn.Sequential(*block(1, 16), nn.MaxPool2d(2), *block(16, 32), nn.MaxPool2d(2), *block(32, 64),
                         nn.AdaptiveMaxPool2d(1), nn.Flatten(), nn.Linear(64, 4))   # max: "is it anywhere?"

def augment(xb, aug):
    if aug in ("flips", "flips + transpose"):
        if torch.rand(1).item() < 0.5: xb = xb.flip(3)        # left-right
        if torch.rand(1).item() < 0.5: xb = xb.flip(2)        # up-down
    if aug == "flips + transpose" and torch.rand(1).item() < 0.5:
        xb = xb.transpose(2, 3)                                # streaks become vertical
    return xb

def train_cnn(Xt, yt, Xv, yv, aug="flips", epochs=12, seed=0):
    """Adam 3e-3, batches of 32; returns the model at the epoch with the best validation accuracy."""
    torch.manual_seed(seed)
    model = make_cnn(); opt = torch.optim.Adam(model.parameters(), lr=3e-3)
    best = (-1.0, None, 0)
    for epoch in range(1, epochs + 1):
        model.train()
        for idx in torch.randperm(len(yt)).split(32):
            loss = nn.functional.cross_entropy(model(augment(Xt[idx], aug)), yt[idx])
            opt.zero_grad(); loss.backward(); opt.step()
        model.eval()
        with torch.no_grad():
            acc = (model(Xv).argmax(1) == yv).float().mean().item()
        if acc > best[0]:
            best = (acc, copy.deepcopy(model.state_dict()), epoch)
    model.load_state_dict(best[1]); model.eval()
    return model, best[2]

def make_balanced(rng, per_class, line):
    """per_class patches of each class, shuffled: the labelled pool and validation set of the new line."""
    y = np.repeat(np.arange(4), per_class); rng.shuffle(y)
    return np.stack([make_defect(rng, int(c), line=line)[0] for c in y]), y

rng = np.random.default_rng(9)
XB_pool, yB_pool = make_balanced(rng, 50, "B")                  # labelled by the inspectors, 50 per class
XB_va, yB_va = make_balanced(rng, 20, "B")                      # validation: 20 per class
XB_te, yB_te, _, _ = make_set(rng, 800, line="B")               # test: 800 patches with the usual shares
BUDGETS = [5, 10, 20, 50]

def budget(n):
    """The first n labelled patches of each class: a larger budget contains the smaller ones."""
    return np.concatenate([np.flatnonzero(yB_pool == c)[:n] for c in range(4)])
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline

rng = np.random.default_rng(8)                                  # Project 8: line A, 1200 + 400 patches
X_tr, y_tr, _, _ = make_set(rng, 1200)
X_va, y_va, _, _ = make_set(rng, 400)
model_a, _ = train_cnn(to_tensor(X_tr), torch.tensor(y_tr), to_tensor(X_va), torch.tensor(y_va), aug="flips")

def accuracy(model, X, y):
    with torch.no_grad():
        pred = model(to_tensor(X)).argmax(1).numpy()
    return (pred == y).mean(), (pred[y > 0] == 0).mean()

body = nn.Sequential(*list(model_a.children())[:-1]).eval()     # line-A CNN without its last layer: 64 features
with torch.no_grad():
    F_pool, F_va, F_te = (body(to_tensor(X)).numpy() for X in (XB_pool, XB_va, XB_te))

Xv, yv = to_tensor(XB_va), torch.tensor(yB_va)
print("labels/class   A frozen + LR   A fine-tuned    scratch CNN   (test accuracy / escape on line B)")
for n in BUDGETS:
    idx = budget(n); Xn, yn = to_tensor(XB_pool[idx]), torch.tensor(yB_pool[idx])
    # (a) frozen line-A features + logistic regression, C chosen on validation
    fits = [make_pipeline(StandardScaler(), LogisticRegression(C=C, max_iter=5000)).fit(F_pool[idx], yB_pool[idx])
            for C in [0.01, 0.1, 1]]
    lr = max(fits, key=lambda m: m.score(F_va, yB_va)); p = lr.predict(F_te)
    a = ((p == yB_te).mean(), (p[yB_te > 0] == 0).mean())
    # (b) every layer of the line-A CNN fine-tuned, smaller learning rate, best validation epoch
    torch.manual_seed(0)
    ft = copy.deepcopy(model_a); opt = torch.optim.Adam(ft.parameters(), lr=1e-3); best = (-1.0, None)
    for epoch in range(30):
        ft.train()
        for b in torch.randperm(len(yn)).split(16):
            loss = nn.functional.cross_entropy(ft(augment(Xn[b], "flips")), yn[b])
            opt.zero_grad(); loss.backward(); opt.step()
        ft.eval()
        acc = accuracy(ft, XB_va, yB_va)[0]
        if acc > best[0]:
            best = (acc, copy.deepcopy(ft.state_dict()))
    ft.load_state_dict(best[1]); b_ = accuracy(ft, XB_te, yB_te)
    # (c) the same CNN from random weights, Project 8's recipe, 30 epochs
    sc, _ = train_cnn(Xn, yn, Xv, yv, aug="flips", epochs=30)
    c_ = accuracy(sc, XB_te, yB_te)
    print(f"{n:6d}         " + "   ".join(f"{acc:.3f} / {esc:.3f}" for acc, esc in (a, b_, c_)))
labels/class   A frozen + LR   A fine-tuned    scratch CNN   (test accuracy / escape on line B)
     5         0.682 / 0.335   0.786 / 0.205   0.458 / 0.654
    10         0.694 / 0.288   0.816 / 0.205   0.718 / 0.118
    20         0.635 / 0.207   0.845 / 0.176   0.809 / 0.168
    50         0.670 / 0.251   0.863 / 0.118   0.864 / 0.174

The line-A CNN fine-tuned is the best strategy at 5, 10 and 20 labels per class (0.786, 0.816, 0.845), and with only 5 labels per class it beats every ImageNet variant at 50. Frozen, the same network is mediocre (0.63 to 0.69): its features were tuned to streaked steel and its batch-norm statistics to line A's brightness, and both have to move. From scratch, the CNN starts barely above "always ok" (0.458 with 5 labels per class) and catches up fast: at 50 labels per class it equals the fine-tuned one (0.864 against 0.863). That is the usual shape of transfer: a pretrained start buys the most when labels are scarcest, and its advantage shrinks as data grows (transfer learning).

Step 6: the learning curves and the decision

All the numbers on one plot, in your browser (the values are copied from the outputs above).

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

budgets = [5, 10, 20, 50]                                       # labels per class (x 4 classes = images)
results = {                                                     # line B test accuracy, copied from Steps 2 to 5
    "pooled features + LR (Step 2)":       [0.504, 0.552, 0.491, 0.516],
    "ImageNet frozen, 96 px + LR (Step 3)": [0.484, 0.580, 0.604, 0.703],
    "ImageNet layer4 fine-tuned (Step 4)": [0.706, 0.734, 0.760, 0.765],
    "line-A CNN frozen + LR (Step 5)":     [0.682, 0.694, 0.635, 0.670],
    "line-A CNN fine-tuned (Step 5)":      [0.786, 0.816, 0.845, 0.863],
    "CNN from scratch (Step 5)":           [0.458, 0.718, 0.809, 0.864],
}
print("labels per class:".ljust(38), "".join(f"{n:>7d}" for n in budgets))
for name, acc in results.items():
    print(name.ljust(38), "".join(f"{a:7.3f}" for a in acc))
best = [max(results, key=lambda k: results[k][i]) for i in range(len(budgets))]
print("best per budget:", [b.split(" (")[0] for b in best])
gain = {n: round(results["line-A CNN fine-tuned (Step 5)"][i] - results["CNN from scratch (Step 5)"][i], 3)
        for i, n in enumerate(budgets)}
print("fine-tuned line-A CNN minus scratch:", gain)
print("target accuracy 0.85 reached at:",
      {k.split(" (")[0]: next((n for n, a in zip(budgets, v) if a >= 0.85), "not within 50") for k, v in results.items()})

fig, ax = plt.subplots(figsize=(7, 4))
for name, acc in results.items():
    ax.plot(budgets, acc, marker="o", label=name.split(" (")[0])
ax.axhline(0.85, color="grey", ls="--", lw=1); ax.axhline(0.396, color="grey", ls=":", lw=1)
ax.text(5.2, 0.86, "target 0.85", fontsize=8); ax.text(5.2, 0.405, "always 'ok'", fontsize=8)
ax.set_xscale("log"); ax.set_xticks(budgets); ax.set_xticklabels(budgets)
ax.set_xlabel("labelled patches per class (line B)"); ax.set_ylabel("test accuracy (800 patches)")
ax.set_title("Learning curves on the new line"); ax.legend(fontsize=7, loc="lower right")
plt.tight_layout()
labels per class:                            5     10     20     50
pooled features + LR (Step 2)            0.504  0.552  0.491  0.516
ImageNet frozen, 96 px + LR (Step 3)     0.484  0.580  0.604  0.703
ImageNet layer4 fine-tuned (Step 4)      0.706  0.734  0.760  0.765
line-A CNN frozen + LR (Step 5)          0.682  0.694  0.635  0.670
line-A CNN fine-tuned (Step 5)           0.786  0.816  0.845  0.863
CNN from scratch (Step 5)                0.458  0.718  0.809  0.864
best per budget: ['line-A CNN fine-tuned', 'line-A CNN fine-tuned', 'line-A CNN fine-tuned', 'CNN from scratch']
fine-tuned line-A CNN minus scratch: {5: 0.328, 10: 0.098, 20: 0.036, 50: -0.001}
target accuracy 0.85 reached at: {'pooled features + LR': 'not within 50', 'ImageNet frozen, 96 px + LR': 'not within 50', 'ImageNet layer4 fine-tuned': 'not within 50', 'line-A CNN frozen + LR': 'not within 50', 'line-A CNN fine-tuned': 50, 'CNN from scratch': 50}

Against the criteria:

Criterion Target Best result
test accuracy on line B at least 0.85 0.863 (line-A CNN fine-tuned, 50 per class) met at 50 labels per class
escape rate at most 0.05 0.118 (same model) not met
label budget at most 50 per class 50 per class

Recommendation for the write-up. Start line B from the line-A CNN and fine-tune all of it; with 20 labels per class it is already within 0.005 of the accuracy target. Do not stop at 50 labels per class: neither the fine-tuned nor the scratch curve has flattened, and the escape rate (0.118) is far from the 0.05 target. The next steps are the escape-focused operating threshold of Project 8, chosen on a larger line-B validation set, and more labels chosen where the model is unsure (active learning). The ImageNet route is not wrong in general: on real, higher-resolution photographs of defects it is often the strongest start. Here it lost because the target images are tiny, grey and unlike photos, and a close relative of the task was available. The scores are about this generator; on real lines the size of every gap will differ, the method of finding it will not.

Extensions

  • Seeds and variance: repeat Step 5 with three different draws of the 5 labels per class; with 20 training images the spread between draws can be larger than the gaps between strategies (checkpoints and reproducibility).
  • Normalise per patch: subtract each patch's own mean before the network. Does the line-A model then work better on line B without any labels (Step 1)?
  • Train on both lines: one model on lines A and B together, with the line as an input or not; check that line A does not get worse (catastrophic forgetting).
  • Pseudo-labels: use the fine-tuned model's confident predictions on unlabelled line-B patches as extra training data (pseudo-labelling).
  • Monitor the shift: compare each day's patch brightness and P(ok) distribution with the training data, so the next new material is noticed before the reject bin fills up (data drift).

Write-up template

text
Project: line B defect classifier by transfer, <date>
Shift: line-A model on line B: accuracy <x> (line A <x>), what it predicts, why (input statistics, texture)
Data: labelled pool <n> per class, validation <n> per class, test <n> (shares), how labels were drawn
Strategies: <list>, choices made on validation (C, epochs, learning rates)
Learning curve (test accuracy / escape at 5, 10, 20, 50 per class): <table or plot>
Best per budget: <...>; cross-over with scratch at <n> per class
Criteria: accuracy <met/not>, escape <met/not>
Recommendation: source <...>, labels needed <estimate and how estimated>, next steps
Limits: synthetic generator, one seed per budget, balanced validation set, no threshold tuning yet

Practice

  1. In Step 1 the line-A model reached 0.282 on line B with an escape rate of 0.000. Why is a zero escape rate here not good news?
Answer

Because it rejects everything: 722 of 800 patches were called spots and no patch was called ok, so the false reject rate is 1.000. An escape rate alone can always be made zero by rejecting all patches; it has to be read together with the false reject rate (Project 8's two criteria).

  1. Step 4 caches the output of layer3 once. Name two changes to the training that would make the cache wrong.
Answer

Any data augmentation applied to the images (flips, crops, brightness), because the cached features belong to the unaugmented patches; and unfreezing a layer at or below layer3, or putting the frozen part in train() mode, because then its output changes during training (weights or batch-norm statistics).

  1. At 50 labels per class, fine-tuning and training from scratch reach the same test accuracy (0.863 and 0.864). Give two reasons why you would still start from the line-A model.
Answer

It is far better at the smaller budgets, so the line is usable earlier while labels are still being collected (0.845 at 20 per class against 0.809). And the 0.001 difference at 50 is one patch out of 800, within the noise of a single seed; its escape rate (0.118) is also lower than the scratch model's (0.174).

  1. A colleague proposes to pick the label budget by looking at where the test curve of Step 6 crosses 0.85. What is the problem, and what would you do instead?
Answer

The test set would then be used to make a decision, so its numbers are no longer an unbiased estimate for the chosen budget. Read the budget from validation curves (with a larger validation set than 20 per class), and keep a fresh line-B test set for the final model's acceptance test.

Test yourself

Why did Project 8's model call most line-B patches 'spot'?

  1. Line B has more spots
  2. The grainy texture looks like many dark blobs, and the darker input is outside the range the model was trained on
  3. The model was trained too long
  4. Spots are the most common class

Which source gave the best line-B classifier with 5 labels per class?

  1. ImageNet ResNet-18, frozen
  2. ImageNet ResNet-18, layer4 fine-tuned
  3. The small line-A CNN, all layers fine-tuned
  4. A CNN from scratch

Why can the layer3 output be computed once and cached in Step 4?

  1. Because layer3 is small
  2. Because everything up to layer3 is frozen and in eval() mode, and no augmentation is used, so its output for a patch never changes
  3. Because the learning rate is small
  4. Because ResNet-18 has no batch norm

What happened to the advantage of fine-tuning over training from scratch as the labels grew from 5 to 50 per class?

  1. It grew
  2. It shrank from 0.328 to about zero
  3. It stayed constant
  4. Scratch was always better