TExcelTAD

Project 1: Image Classification

The first of the course's seven projects puts the classification section together in one guided lab. The task is the shape classifier of the previous lessons, made harder in the ways real images are hard: shapes at any rotation, a wider range of sizes, strong sensor noise, and colours that are sometimes barely different from the background. You will build a baseline, improve it twice, evaluate honestly, find out where the best model fails, and write it up. Every step reuses code from image classification and training a CNN; each example runs on its own.

Goal and success criteria

Write the success criteria before looking at any result, so the result cannot shape them:

Criterion Target Measured on
test accuracy at least 0.90 600 held-out hard crops, used once
worst class recall at least 0.85 same
no hidden weak spot accuracy reported per size and per contrast group same, split by the generator's metadata
cost CPU only, training under 30 s the recorded run

The data

make_crop(..., hard=True) draws one square, circle or triangle on a 32×3232 \times 32 noisy background with any rotation, a circumradius from 5 to 13 pixels, a random colour, and extra Gaussian pixel noise (σ=20\sigma = 20 grey levels). The version here also returns two facts per image that the generator knows and a real dataset would have to annotate: the shape's size (circumradius rr) and its contrast, the largest difference between the shape's colour and the background's mean grey (110) over the three channels. The images are the same as without the metadata.

The splits are 1,200 training, 300 validation and 600 test images, drawn independently from the same generator (so there are no near-duplicates across splits to worry about; with real data, split by source). Hyperparameters are chosen on the validation set; the test set is used once per final model.

Step 1: baseline, pixels and logistic regression

python · try it yourself
import numpy as np, cv2
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.metrics import confusion_matrix

CLASSES = ["square", "circle", "triangle"]

def make_crop(rng, c, size=32, hard=False, meta=False):
    """make_crop of the classification lessons; meta=True also returns the size r and the colour contrast."""
    img = rng.normal(110, 12, (size, size, 3))
    r = rng.uniform(5, 13) if hard else rng.uniform(7, 10)          # circumradius in pixels
    a, d = rng.uniform(0, 2 * np.pi), rng.uniform(0, size / 2 - r - 1)
    cx, cy = size / 2 + d * np.cos(a), size / 2 + d * np.sin(a)     # inside a disc: rotations keep it in the frame
    turn = rng.uniform(0, 2 * np.pi) if hard else rng.uniform(-0.2, 0.2)
    m = np.zeros((size, size), np.uint8)
    if c == 1:
        cv2.circle(m, (int(round(cx)), int(round(cy))), int(round(r)), 1, -1)
    else:
        k = 4 if c == 0 else 3
        t = turn + (np.pi / 4 if c == 0 else -np.pi / 2) + np.arange(k) * 2 * np.pi / k
        cv2.fillPoly(m, [np.round(np.stack([cx + r * np.cos(t), cy + r * np.sin(t)], 1)).astype(np.int32)], 1)
    colour = rng.integers(0, 256, 3)
    img[m > 0] = colour
    if hard:
        img = img + rng.normal(0, 20, img.shape)
    img = img.clip(0, 255).astype(np.uint8)
    return (img, r, float(np.abs(colour - 110).max())) if meta else img

def make_set(rng, n, hard=True):
    y = rng.integers(0, 3, n)
    out = [make_crop(rng, int(c), hard=hard, meta=True) for c in y]
    return np.array([o[0] for o in out]), y, np.array([o[1] for o in out]), np.array([o[2] for o in out])

rng = np.random.default_rng(1)
X_tr, y_tr, r_tr, c_tr = make_set(rng, 1200)
X_va, y_va, r_va, c_va = make_set(rng, 300)
X_te, y_te, r_te, c_te = make_set(rng, 600)
print("train / val / test:", len(y_tr), len(y_va), len(y_te), "| test per class:", np.bincount(y_te).tolist())
print(f"test size r: {r_te.min():.1f} to {r_te.max():.1f} | contrast: {c_te.min():.0f} to {c_te.max():.0f} grey levels")

flat = lambda X: X.reshape(len(X), -1) / 255
best = None
for C in [1e-5, 1e-4, 1e-3]:
    model = make_pipeline(StandardScaler(), LogisticRegression(C=C, max_iter=300)).fit(flat(X_tr), y_tr)
    acc = model.score(flat(X_va), y_va)
    print(f"C = {C:g}: validation accuracy {acc:.3f}")
    if best is None or acc > best[0]:
        best = (acc, C, model)
pred = best[2].predict(flat(X_te))
print(f"baseline (C = {best[1]:g}): TEST accuracy {(pred == y_te).mean():.3f}")
print(confusion_matrix(y_te, pred))

fig, axes = plt.subplots(1, 8, figsize=(8, 1.4))
for i, ax in enumerate(axes):
    ax.imshow(X_te[i]); ax.set_title(f"{CLASSES[y_te[i]]} r={r_te[i]:.0f}", fontsize=7); ax.axis("off")
plt.tight_layout()
train / val / test: 1200 300 600 | test per class: [193, 198, 209]
test size r: 5.0 to 13.0 | contrast: 11 to 145 grey levels
C = 1e-05: validation accuracy 0.367
C = 0.0001: validation accuracy 0.390
C = 0.001: validation accuracy 0.403
baseline (C = 0.001): TEST accuracy 0.362
[[65 81 47]
 [65 77 56]
 [63 71 75]]

Raw pixels are hopeless here: 0.403 on validation at best and 0.362 on the test set, barely above the 0.333 of guessing, with every row of the confusion matrix spread over all three columns. A logistic regression on pixels needs the same shape at the same place, size and angle to give the same pixels, and this generator varies all three. That is the floor every other model must clear.

Step 2: HOG and a linear SVM, then rotation augmentation

HOG handles colour and position, but the classification lesson showed it failing on rotations it had not seen. Here every training image is already rotated at random, so the SVM sees all edge directions for every class. A second variant adds augmented copies: each training image rotated by two further random angles (rotation about the image centre is label-preserving here, because the generator keeps shapes inside a central disc). C is chosen on the validation set for both.

python · try it yourself
import numpy as np, cv2
from skimage.feature import hog
from sklearn.svm import LinearSVC
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.metrics import confusion_matrix, recall_score

CLASSES = ["square", "circle", "triangle"]

def make_crop(rng, c, size=32, hard=False, meta=False):
    """make_crop of the classification lessons; meta=True also returns the size r and the colour contrast."""
    img = rng.normal(110, 12, (size, size, 3))
    r = rng.uniform(5, 13) if hard else rng.uniform(7, 10)          # circumradius in pixels
    a, d = rng.uniform(0, 2 * np.pi), rng.uniform(0, size / 2 - r - 1)
    cx, cy = size / 2 + d * np.cos(a), size / 2 + d * np.sin(a)     # inside a disc: rotations keep it in the frame
    turn = rng.uniform(0, 2 * np.pi) if hard else rng.uniform(-0.2, 0.2)
    m = np.zeros((size, size), np.uint8)
    if c == 1:
        cv2.circle(m, (int(round(cx)), int(round(cy))), int(round(r)), 1, -1)
    else:
        k = 4 if c == 0 else 3
        t = turn + (np.pi / 4 if c == 0 else -np.pi / 2) + np.arange(k) * 2 * np.pi / k
        cv2.fillPoly(m, [np.round(np.stack([cx + r * np.cos(t), cy + r * np.sin(t)], 1)).astype(np.int32)], 1)
    colour = rng.integers(0, 256, 3)
    img[m > 0] = colour
    if hard:
        img = img + rng.normal(0, 20, img.shape)
    img = img.clip(0, 255).astype(np.uint8)
    return (img, r, float(np.abs(colour - 110).max())) if meta else img

def make_set(rng, n, hard=True):
    y = rng.integers(0, 3, n)
    out = [make_crop(rng, int(c), hard=hard, meta=True) for c in y]
    return np.array([o[0] for o in out]), y, np.array([o[1] for o in out]), np.array([o[2] for o in out])

def hog_features(X):
    return np.array([hog(im, orientations=9, pixels_per_cell=(8, 8), cells_per_block=(2, 2),
                         channel_axis=-1) for im in X])

def rotate_each(X, angles):
    return np.array([cv2.warpAffine(im, cv2.getRotationMatrix2D((15.5, 15.5), float(a), 1.0), (32, 32),
                                    borderMode=cv2.BORDER_REFLECT_101) for im, a in zip(X, angles)])

rng = np.random.default_rng(1)
X_tr, y_tr, r_tr, c_tr = make_set(rng, 1200)
X_va, y_va, r_va, c_va = make_set(rng, 300)
X_te, y_te, r_te, c_te = make_set(rng, 600)
aug_rng = np.random.default_rng(2)
X_aug = np.concatenate([X_tr] + [rotate_each(X_tr, aug_rng.uniform(0, 360, len(X_tr))) for _ in range(2)])
y_aug = np.tile(y_tr, 3)
H_tr, H_aug, H_va, H_te = hog_features(X_tr), hog_features(X_aug), hog_features(X_va), hog_features(X_te)

for name, H, y in [("HOG + SVM", H_tr, y_tr), ("HOG + SVM + 2 rotated copies", H_aug, y_aug)]:
    scores = {}
    for C in [1e-4, 1e-3, 1e-2]:
        scores[C] = make_pipeline(StandardScaler(), LinearSVC(C=C)).fit(H, y).score(H_va, y_va)
    C = max(scores, key=scores.get)
    model = make_pipeline(StandardScaler(), LinearSVC(C=C)).fit(H, y)
    pred = model.predict(H_te)
    rec = recall_score(y_te, pred, average=None)
    print(f"{name}: {len(y)} training images, C = {C:g} (val {scores[C]:.3f}), "
          f"TEST accuracy {(pred == y_te).mean():.3f}")
    print("  recall per class:", dict(zip(CLASSES, rec.round(3).tolist())))
print(confusion_matrix(y_te, pred))
HOG + SVM: 1200 training images, C = 0.01 (val 0.593), TEST accuracy 0.555
  recall per class: {'square': 0.394, 'circle': 0.631, 'triangle': 0.632}
HOG + SVM + 2 rotated copies: 3600 training images, C = 0.01 (val 0.583), TEST accuracy 0.553
  recall per class: {'square': 0.29, 'circle': 0.707, 'triangle': 0.651}
[[ 56  87  50]
 [ 36 140  22]
 [ 36  37 136]]

HOG lifts the test accuracy to 0.555: edge histograms ignore the colour and tolerate small shifts. But squares are the weak class (recall 0.394), mostly called circles, because a square seen at a random angle has edges in every direction, like a circle. The rotated copies do not help (validation 0.583 against 0.593, test 0.553): the training set was already rotated at random, so the copies add no variation the model had not seen, only correlated duplicates. Augmentation fixes a missing variation; it is not a free gain. The confusion matrix shown is that of the augmented model, the last one fitted.

Step 3: a small CNN with augmentation (recorded)

The CNN of the previous lesson, trained on the 1,200 hard training images with random rotation, flips and noise, the epoch chosen on the validation set. The recorded run also breaks the test accuracy down by the generator's metadata.

python · try it yourself
import copy, math
import numpy as np, cv2
import torch
from torch import nn
import torch.nn.functional as F

CLASSES = ["square", "circle", "triangle"]

def make_crop(rng, c, size=32, hard=False, meta=False):
    """make_crop of the classification lessons; meta=True also returns the size r and the colour contrast."""
    img = rng.normal(110, 12, (size, size, 3))
    r = rng.uniform(5, 13) if hard else rng.uniform(7, 10)          # circumradius in pixels
    a, d = rng.uniform(0, 2 * np.pi), rng.uniform(0, size / 2 - r - 1)
    cx, cy = size / 2 + d * np.cos(a), size / 2 + d * np.sin(a)     # inside a disc: rotations keep it in the frame
    turn = rng.uniform(0, 2 * np.pi) if hard else rng.uniform(-0.2, 0.2)
    m = np.zeros((size, size), np.uint8)
    if c == 1:
        cv2.circle(m, (int(round(cx)), int(round(cy))), int(round(r)), 1, -1)
    else:
        k = 4 if c == 0 else 3
        t = turn + (np.pi / 4 if c == 0 else -np.pi / 2) + np.arange(k) * 2 * np.pi / k
        cv2.fillPoly(m, [np.round(np.stack([cx + r * np.cos(t), cy + r * np.sin(t)], 1)).astype(np.int32)], 1)
    colour = rng.integers(0, 256, 3)
    img[m > 0] = colour
    if hard:
        img = img + rng.normal(0, 20, img.shape)
    img = img.clip(0, 255).astype(np.uint8)
    return (img, r, float(np.abs(colour - 110).max())) if meta else img

def make_set(rng, n, hard=True):
    y = rng.integers(0, 3, n)
    out = [make_crop(rng, int(c), hard=hard, meta=True) for c in y]
    return np.array([o[0] for o in out]), y, np.array([o[1] for o in out]), np.array([o[2] for o in out])

rng = np.random.default_rng(1)
X_tr, y_tr, r_tr, c_tr = make_set(rng, 1200)
X_va, y_va, r_va, c_va = make_set(rng, 300)
X_te, y_te, r_te, c_te = make_set(rng, 600)
mean = (X_tr / 255).mean(axis=(0, 1, 2)); std = (X_tr / 255).std(axis=(0, 1, 2))
to_tensor = lambda X: torch.tensor(((X / 255 - mean) / std).transpose(0, 3, 1, 2), dtype=torch.float32)

class SmallCNN(nn.Module):
    def __init__(self):
        super().__init__()
        block = lambda cin, cout: [nn.Conv2d(cin, cout, 3, padding=1), nn.BatchNorm2d(cout), nn.ReLU()]
        self.features = nn.Sequential(*block(3, 16), nn.MaxPool2d(2), *block(16, 32), nn.MaxPool2d(2),
                                      *block(32, 64), nn.AdaptiveAvgPool2d(1), nn.Flatten())
        self.head = nn.Linear(64, 3)
    def forward(self, x):
        return self.head(self.features(x))

def augment(x):
    n = len(x)
    a = torch.rand(n) * 2 * math.pi
    theta = torch.zeros(n, 2, 3)
    theta[:, 0, 0], theta[:, 0, 1], theta[:, 1, 0], theta[:, 1, 1] = a.cos(), -a.sin(), a.sin(), a.cos()
    x = F.grid_sample(x, F.affine_grid(theta, list(x.shape), align_corners=False),
                      padding_mode="reflection", align_corners=False)
    flip = torch.rand(n) < 0.5
    x[flip] = x[flip].flip(3)
    return x + torch.randn_like(x) * torch.rand(n, 1, 1, 1) * 0.3

def predict(model, X):
    model.eval()
    with torch.no_grad():
        return model(X).argmax(1).numpy()

Xtr, ytr, Xva, Xte = to_tensor(X_tr), torch.tensor(y_tr), to_tensor(X_va), to_tensor(X_te)
torch.manual_seed(0)
model = SmallCNN()
epochs, steps = 45, math.ceil(len(ytr) / 32)
opt = torch.optim.Adam(model.parameters(), lr=3e-3)
sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=3e-3, total_steps=epochs * steps)
best = (0.0, None, 0)
for epoch in range(1, epochs + 1):
    model.train()
    for idx in torch.randperm(len(ytr)).split(32):
        loss = F.cross_entropy(model(augment(Xtr[idx])), ytr[idx])
        opt.zero_grad(); loss.backward(); opt.step(); sched.step()
    val = (predict(model, Xva) == y_va).mean()
    if val > best[0]:
        best = (val, copy.deepcopy(model.state_dict()), epoch)
model.load_state_dict(best[1])
pred = predict(model, Xte)
print(f"kept epoch {best[2]} (validation accuracy {best[0]:.3f})")
print(f"TEST accuracy {(pred == y_te).mean():.3f}")
print("recall per class:", {c: round(float((pred[y_te == k] == k).mean()), 3) for k, c in enumerate(CLASSES)})
print(np.array([[int(((y_te == t) & (pred == p)).sum()) for p in range(3)] for t in range(3)]))
print("accuracy by size r:")
for lo, hi in [(5, 7), (7, 9), (9, 11), (11, 13)]:
    s = (r_te >= lo) & (r_te < hi)
    print(f"  {lo:2d} <= r < {hi:2d}: {(pred[s] == y_te[s]).mean():.3f}  (n = {int(s.sum())})")
print("accuracy by contrast (largest channel difference from the background):")
for lo, hi in [(0, 40), (40, 80), (80, 146)]:
    s = (c_te >= lo) & (c_te < hi)
    print(f"  {lo:3d} to {hi:3d}: {(pred[s] == y_te[s]).mean():.3f}  (n = {int(s.sum())})")
kept epoch 42 (validation accuracy 0.923)
TEST accuracy 0.925
recall per class: {'square': 0.813, 'circle': 0.965, 'triangle': 0.99}
[[157   5  31]
 [  7 191   0]
 [  1   1 207]]
accuracy by size r:
   5 <= r <  7: 0.779  (n = 136)
   7 <= r <  9: 0.948  (n = 155)
   9 <= r < 11: 0.968  (n = 156)
  11 <= r < 13: 0.987  (n = 153)
accuracy by contrast (largest channel difference from the background):
    0 to  40: 0.600  (n = 15)
   40 to  80: 0.888  (n = 134)
   80 to 146: 0.947  (n = 451)

The CNN reaches 0.925 on the test set, kept at epoch 42 by validation accuracy (0.923). Against the success criteria: test accuracy 0.925 meets "at least 0.90", but the worst class recall is 0.813 (squares), below the 0.85 target, with 31 squares called triangles. The breakdown shows where: the smallest shapes (5≤r<75 \le r < 7: 0.779, n = 136) and the few lowest-contrast ones (0.600, but n = 15, so this number is very uncertain: one image is 6.7 points). A square of circumradius 5 is about 7 pixels wide, drawn on noise with σ=20\sigma = 20; at that size its corners are a pixel or two. So the honest verdict is "meets the accuracy target, fails the per-class target, because of small squares", and the obvious next experiments are higher-resolution crops or more small squares in training.

Error analysis: where the classical model fails

A single accuracy hides where the errors are. The same breakdown for the best classical model by validation accuracy, plain HOG + SVM with C = 0.01, in your browser, plus a failure gallery: test images it got wrong, with what it predicted. Looking at the failures is the step that tells you what to do next: more data of a kind, a different feature, a relabelling, or a change of the success criteria.

python · try it yourself
import numpy as np, cv2
import matplotlib.pyplot as plt
from skimage.feature import hog
from sklearn.svm import LinearSVC
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline

CLASSES = ["square", "circle", "triangle"]

def make_crop(rng, c, size=32, hard=False, meta=False):
    """make_crop of the classification lessons; meta=True also returns the size r and the colour contrast."""
    img = rng.normal(110, 12, (size, size, 3))
    r = rng.uniform(5, 13) if hard else rng.uniform(7, 10)          # circumradius in pixels
    a, d = rng.uniform(0, 2 * np.pi), rng.uniform(0, size / 2 - r - 1)
    cx, cy = size / 2 + d * np.cos(a), size / 2 + d * np.sin(a)     # inside a disc: rotations keep it in the frame
    turn = rng.uniform(0, 2 * np.pi) if hard else rng.uniform(-0.2, 0.2)
    m = np.zeros((size, size), np.uint8)
    if c == 1:
        cv2.circle(m, (int(round(cx)), int(round(cy))), int(round(r)), 1, -1)
    else:
        k = 4 if c == 0 else 3
        t = turn + (np.pi / 4 if c == 0 else -np.pi / 2) + np.arange(k) * 2 * np.pi / k
        cv2.fillPoly(m, [np.round(np.stack([cx + r * np.cos(t), cy + r * np.sin(t)], 1)).astype(np.int32)], 1)
    colour = rng.integers(0, 256, 3)
    img[m > 0] = colour
    if hard:
        img = img + rng.normal(0, 20, img.shape)
    img = img.clip(0, 255).astype(np.uint8)
    return (img, r, float(np.abs(colour - 110).max())) if meta else img

def make_set(rng, n, hard=True):
    y = rng.integers(0, 3, n)
    out = [make_crop(rng, int(c), hard=hard, meta=True) for c in y]
    return np.array([o[0] for o in out]), y, np.array([o[1] for o in out]), np.array([o[2] for o in out])

def hog_features(X):
    return np.array([hog(im, orientations=9, pixels_per_cell=(8, 8), cells_per_block=(2, 2),
                         channel_axis=-1) for im in X])

rng = np.random.default_rng(1)
X_tr, y_tr, r_tr, c_tr = make_set(rng, 1200)
X_va, y_va, r_va, c_va = make_set(rng, 300)
X_te, y_te, r_te, c_te = make_set(rng, 600)
model = make_pipeline(StandardScaler(), LinearSVC(C=0.01)).fit(hog_features(X_tr), y_tr)   # C chosen in Step 2
pred = model.predict(hog_features(X_te))
print(f"HOG + SVM: TEST accuracy {(pred == y_te).mean():.3f}")
print("accuracy by size r:")
for lo, hi in [(5, 7), (7, 9), (9, 11), (11, 13)]:
    s = (r_te >= lo) & (r_te < hi)
    print(f"  {lo:2d} <= r < {hi:2d}: {(pred[s] == y_te[s]).mean():.3f}  (n = {int(s.sum())})")
print("accuracy by contrast:")
for lo, hi in [(0, 40), (40, 80), (80, 146)]:
    s = (c_te >= lo) & (c_te < hi)
    print(f"  {lo:3d} to {hi:3d}: {(pred[s] == y_te[s]).mean():.3f}  (n = {int(s.sum())})")

wrong = np.flatnonzero(pred != y_te)[:10]
fig, axes = plt.subplots(1, 10, figsize=(9, 1.5))
for ax, i in zip(axes, wrong):
    ax.imshow(X_te[i]); ax.axis("off")
    ax.set_title(f"{CLASSES[y_te[i]][:3]}->{CLASSES[pred[i]][:3]}\nr={r_te[i]:.0f} c={c_te[i]:.0f}", fontsize=6)
plt.tight_layout()
HOG + SVM: TEST accuracy 0.555
accuracy by size r:
   5 <= r <  7: 0.397  (n = 136)
   7 <= r <  9: 0.516  (n = 155)
   9 <= r < 11: 0.590  (n = 156)
  11 <= r < 13: 0.699  (n = 153)
accuracy by contrast:
    0 to  40: 0.533  (n = 15)
   40 to  80: 0.493  (n = 134)
   80 to 146: 0.574  (n = 451)

The classical model is weak everywhere, but its breakdown has the same shape as the CNN's: accuracy climbs with size, from 0.397 for the smallest shapes to 0.699 for the largest. HOG uses 8×88 \times 8 cells, so a shape 7 pixels wide lives inside one or two cells and its histogram is mostly noise. The contrast groups differ less here (0.493 to 0.574), so for this model size, not contrast, is the first problem. In the gallery, look at what the mistaken images have in common before deciding what to change.

Your turn

  1. Contrast. The generator lets you measure accuracy per contrast group. Change the experiment so that the training set has more low-contrast examples (draw 1,200 images and keep only those with contrast under 60, or oversample them) and measure whether the low-contrast group improves. What does that correspond to in a real project?
  2. Grey vs colour. Train HOG + SVM on grey images (cv2.cvtColor(X, cv2.COLOR_RGB2GRAY) per image) instead of channel_axis=-1. Which contrast group suffers, and why?
  3. Less data. Train the best classical model on 300 instead of 1,200 images. How much accuracy do you lose, and does augmentation help more or less with less data?
  4. Write-up. Fill in the template below with your numbers.
Hints and answers
  1. Filter with keep = c_tr < 60 (and the matching y_tr) or repeat those rows; recompute HOG features and refit. Low-contrast accuracy usually rises, sometimes at a small cost elsewhere. In a real project this is targeted data collection: after error analysis shows a weak slice (night images, small objects, one camera), you collect or label more of exactly that slice, and you keep reporting that slice separately (error analysis).
  2. A shape whose colour differs from the background only in hue (say a green of the same brightness as the grey) vanishes in a grey image, so the low-contrast and the "same brightness" shapes suffer. channel_axis=-1 lets HOG take the strongest gradient over the three channels, so hue edges survive.
  3. Expect a drop of several points. Augmentation usually helps more when data is scarce, because it is the only source of the missing variation; with plenty of real data covering every angle, rotated copies add little.

Write-up template

Section Your content
Task and data 3-class shapes, 32×3232 \times 32, generator settings, 1,200 / 300 / 600 split, how splits were made
Success criteria the table above, written before any result
Baseline pixels + logistic regression: test accuracy, confusion matrix
Improvements HOG + SVM; + rotated copies; CNN + augmentation: test accuracy and worst-class recall for each
Error analysis accuracy per size and contrast group (with n), failure gallery, the main failure mode in one sentence
Robustness and limits what the test set does not cover (real photos, occlusion, other shapes), number of seeds
Decision which model meets the criteria, at what cost; what you would do next

Test yourself

Why are the success criteria written before any model is trained?

  1. To save time
  2. So that the results cannot shape the criteria; choosing the target after seeing the scores turns any result into a success
  3. Because the test set is not ready
  4. It is a legal requirement

A model reaches 0.93 test accuracy, but accuracy on low-contrast images is 0.70. What should the write-up do?

  1. Report only 0.93
  2. Report both, with the number of images in the low-contrast group, and name it as the main weakness
  3. Remove the low-contrast images from the test set
  4. Retrain on the test set

Step 2 added rotated copies of the training images for HOG + SVM. Under which condition is rotation a valid augmentation?

  1. Always
  2. When a rotated image keeps its label and stays inside the frame: true for these shapes kept within a central disc, false for digits like 6 and 9
  3. Only for grey images
  4. Only for CNNs