TExcelTAD
Home › Deep Learning: Neural Networks, Architectures & PyTorch › Mini Project: Digits with an MLP, a CNN and a ViT

Mini Project: Digits with an MLP, a CNN and a ViT

The course has made a claim about architectures: each one builds an assumption about the data into its wiring, and that assumption is worth something only when it matches the data. An MLP assumes nothing about which inputs are neighbours. A CNN assumes that nearby pixels belong together and that a pattern means the same thing wherever it appears. A vision transformer assumes little and has to learn the layout from its training images. This project tests the claim on one small task: three networks of similar size on the Digits images, trained by the same loop, compared on accuracy and on a robustness probe that targets exactly the CNN's assumption. Then you write it up, including what the numbers cannot tell you.

The brief

  • Task: classify the 8 ×\times 8 handwritten digits of load_digits (1797 images, 10 classes) with the course's split: 1077 training, 360 validation, 360 test images, stratified, random_state=0.
  • Models, each between 13,000 and 19,000 parameters:
    1. MLP: the image flattened to 64 numbers, two hidden ReLU layers of 128 and 64 units (MLPs).
    2. CNN: two 3 ×\times 3 convolutions with 16 and 32 channels, each followed by ReLU and 2 ×\times 2 max pooling, then a 64-unit hidden layer (convolution layers, a CNN from scratch).
    3. ViT: 16 patches of 2 ×\times 2 pixels embedded in 32 dimensions, a class token, learned position embeddings, two pre-norm transformer blocks with 4 heads (vision transformers, the transformer block).
  • Baseline: multinomial logistic regression on the 64 pixels, its CC chosen on validation.
  • Training, identical for the three networks: AdamW (learning rate 3⋅10−33 \cdot 10^{-3}, weight decay 10−210^{-2}), cosine schedule over 40 epochs, batches of 64, the epoch with the best validation accuracy restored (a reusable training loop). Every number is the mean of three seeds (0, 1, 2), because one run of a small network on 360 images is noisy (checkpoints, seeds and reproducibility).
  • Evaluation: accuracy on validation (for every choice), on the test set, and on a shifted test set: the same 360 test images moved one pixel to the right, the column that falls off the edge dropped and a zero column added on the left. A person reads a shifted digit without noticing; the probe asks whether the model does too.
  • Fairness rules: the hyperparameters above were fixed before any model was run and are the same for all three networks, so no model gets more tuning than another. The test and shifted-test numbers are reported for every model because this is a comparison study; no choice is made on them.

The network steps are recorded examples (they need PyTorch) and take about 15 to 25 seconds each on a CPU; the baseline and the results table run in your browser.

Step 1: the data and a linear baseline

Before training any network, find out how hard the task is. A linear model on raw pixels is the baseline every network must beat, and the shifted test set is built here once in NumPy so you can see what it does.

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

X, y = load_digits(return_X_y=True)
X = X / 16.0
X_tmp, X_te, y_tmp, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_tr, X_va, y_tr, y_va = train_test_split(X_tmp, y_tmp, test_size=0.25, random_state=0, stratify=y_tmp)
print("train / validation / test:", len(y_tr), len(y_va), len(y_te))
print("class counts in test:", np.bincount(y_te).tolist())

img = X_te.reshape(-1, 8, 8)
X_sh = np.zeros_like(img)
X_sh[:, :, 1:] = img[:, :, :-1]                                 # every test image moved 1 pixel right
X_sh = X_sh.reshape(-1, 64)
print("pixels lost at the right edge:", round(float(img[:, :, -1].sum() / img.sum()), 4))

scores = {}
for C in (0.1, 1.0, 10.0, 100.0):                               # choose C on validation only
    scores[C] = LogisticRegression(C=C, max_iter=5000).fit(X_tr, y_tr).score(X_va, y_va)
    print(f"C = {C:<5}  val accuracy {scores[C]:.3f}")
best_C = max(scores, key=scores.get)
clf = LogisticRegression(C=best_C, max_iter=5000).fit(X_tr, y_tr)
print(f"chosen C = {best_C}: test {clf.score(X_te, y_te):.3f}   shifted test {clf.score(X_sh, y_te):.3f}")
train / validation / test: 1077 360 360
class counts in test: [36, 36, 35, 37, 36, 37, 36, 36, 35, 36]
pixels lost at the right edge: 0.0023
C = 0.1    val accuracy 0.936
C = 1.0    val accuracy 0.967
C = 10.0   val accuracy 0.972
C = 100.0  val accuracy 0.964
chosen C = 10.0: test 0.975   shifted test 0.406

The test set has 35 to 37 images per class, so accuracy is a fair summary. Shifting by one pixel loses almost nothing: only 0.23 % of the ink sits in the last column (the Digits images have a blank border). Logistic regression is strong here: C=10C = 10 wins on validation with 0.972, and the model gets 0.975 on the test set. On the shifted images it falls to 0.406. Each weight belongs to one pixel position, so moving the digit moves it onto the wrong weights.

Step 2: the MLP and the CNN

The setup (the first 55 lines, up to and including report) is the same in every network step, so each step runs on its own. fit is the loop of the training-loop lesson in compact form; shift is the augmentation used in step 4; report trains a model with three seeds and prints the means.

python · try it yourself
import copy
import numpy as np
import torch
from torch import nn
from torch.utils.data import TensorDataset, DataLoader
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split

X, y = load_digits(return_X_y=True)
X = (X / 16.0).reshape(-1, 1, 8, 8).astype(np.float32)          # images: (n, channels, 8, 8)
X_tmp, X_te, y_tmp, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_tr, X_va, y_tr, y_va = train_test_split(X_tmp, y_tmp, test_size=0.25, random_state=0, stratify=y_tmp)
X_tr, X_va, X_te = map(torch.from_numpy, (X_tr, X_va, X_te))
y_tr, y_va, y_te = (torch.tensor(a) for a in (y_tr, y_va, y_te))
X_sh = torch.roll(X_te, shifts=1, dims=3); X_sh[..., 0] = 0     # the test images moved 1 pixel right

def shift(xb, g):                                               # random shift of -1, 0 or +1 pixel per image
    pad = nn.functional.pad(xb, (1, 1, 1, 1))
    dy, dx = torch.randint(0, 3, (2, len(xb)), generator=g)
    return torch.stack([pad[i, :, dy[i]:dy[i] + 8, dx[i]:dx[i] + 8] for i in range(len(xb))])

def accuracy(model, X, y):
    model.eval()
    with torch.no_grad():
        return (model(X).argmax(1) == y).float().mean().item()

def fit(model, seed, epochs=40, augment=False):
    g = torch.Generator().manual_seed(seed)
    loader = DataLoader(TensorDataset(X_tr, y_tr), batch_size=64, shuffle=True, generator=g)
    opt = torch.optim.AdamW(model.parameters(), lr=3e-3, weight_decay=1e-2)
    sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=epochs)
    best_va, best_state = -1.0, None
    for epoch in range(epochs):
        model.train()
        for xb, yb in loader:
            if augment:
                xb = shift(xb, g)
            loss = nn.functional.cross_entropy(model(xb), yb)
            opt.zero_grad(); loss.backward(); opt.step()
        sched.step()
        va = accuracy(model, X_va, y_va)
        if va > best_va:                                        # keep the best epoch on validation
            best_va, best_state = va, copy.deepcopy(model.state_dict())
    model.load_state_dict(best_state)
    return best_va

def report(name, make, augment=False):
    rows = []
    for seed in (0, 1, 2):
        torch.manual_seed(seed)
        model = make()
        rows.append((fit(model, seed, augment=augment), accuracy(model, X_te, y_te), accuracy(model, X_sh, y_te)))
    va, te, sh = np.array(rows).mean(axis=0)
    params = sum(p.numel() for p in model.parameters())
    print(f"{name:4s} {params:6d} params   val {va:.3f}   test {te:.3f}   shifted test {sh:.3f}")

mlp = lambda: nn.Sequential(nn.Flatten(), nn.Linear(64, 128), nn.ReLU(), nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 10))
cnn = lambda: nn.Sequential(nn.Conv2d(1, 16, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),     # 16 x 4 x 4
                            nn.Conv2d(16, 32, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),    # 32 x 2 x 2
                            nn.Flatten(), nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 10))
print("mean of 3 seeds, no augmentation")
report("MLP", mlp)
report("CNN", cnn)
mean of 3 seeds, no augmentation
MLP   17226 params   val 0.975   test 0.969   shifted test 0.421
CNN   13706 params   val 0.980   test 0.969   shifted test 0.572

Both networks reach the baseline's level and no more: 0.975 and 0.980 on validation, 0.969 on the test for both. The difference that the architecture makes shows only on the shifted images: the MLP keeps 0.421, about as little as logistic regression, while the CNN keeps 0.572. Convolution is translation equivariant (a shifted input gives a shifted feature map) and max pooling absorbs part of a small shift, but not all of it: after two poolings the map is only 2 ×\times 2 and the final linear layer again ties each position to its own weights, so the CNN is far from shift-invariant.

Step 3: the vision transformer

The ViT has no convolution after its patch embedding and no notion of distance between patches except the position embeddings it learns. On 1077 training images that is a handicap.

python · try it yourself
import copy
import numpy as np
import torch
from torch import nn
from torch.utils.data import TensorDataset, DataLoader
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split

X, y = load_digits(return_X_y=True)
X = (X / 16.0).reshape(-1, 1, 8, 8).astype(np.float32)          # images: (n, channels, 8, 8)
X_tmp, X_te, y_tmp, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_tr, X_va, y_tr, y_va = train_test_split(X_tmp, y_tmp, test_size=0.25, random_state=0, stratify=y_tmp)
X_tr, X_va, X_te = map(torch.from_numpy, (X_tr, X_va, X_te))
y_tr, y_va, y_te = (torch.tensor(a) for a in (y_tr, y_va, y_te))
X_sh = torch.roll(X_te, shifts=1, dims=3); X_sh[..., 0] = 0     # the test images moved 1 pixel right

def shift(xb, g):                                               # random shift of -1, 0 or +1 pixel per image
    pad = nn.functional.pad(xb, (1, 1, 1, 1))
    dy, dx = torch.randint(0, 3, (2, len(xb)), generator=g)
    return torch.stack([pad[i, :, dy[i]:dy[i] + 8, dx[i]:dx[i] + 8] for i in range(len(xb))])

def accuracy(model, X, y):
    model.eval()
    with torch.no_grad():
        return (model(X).argmax(1) == y).float().mean().item()

def fit(model, seed, epochs=40, augment=False):
    g = torch.Generator().manual_seed(seed)
    loader = DataLoader(TensorDataset(X_tr, y_tr), batch_size=64, shuffle=True, generator=g)
    opt = torch.optim.AdamW(model.parameters(), lr=3e-3, weight_decay=1e-2)
    sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=epochs)
    best_va, best_state = -1.0, None
    for epoch in range(epochs):
        model.train()
        for xb, yb in loader:
            if augment:
                xb = shift(xb, g)
            loss = nn.functional.cross_entropy(model(xb), yb)
            opt.zero_grad(); loss.backward(); opt.step()
        sched.step()
        va = accuracy(model, X_va, y_va)
        if va > best_va:                                        # keep the best epoch on validation
            best_va, best_state = va, copy.deepcopy(model.state_dict())
    model.load_state_dict(best_state)
    return best_va

def report(name, make, augment=False):
    rows = []
    for seed in (0, 1, 2):
        torch.manual_seed(seed)
        model = make()
        rows.append((fit(model, seed, augment=augment), accuracy(model, X_te, y_te), accuracy(model, X_sh, y_te)))
    va, te, sh = np.array(rows).mean(axis=0)
    params = sum(p.numel() for p in model.parameters())
    print(f"{name:4s} {params:6d} params   val {va:.3f}   test {te:.3f}   shifted test {sh:.3f}")

class ViT(nn.Module):
    def __init__(self, patch=2, d=32, depth=2, heads=4):
        super().__init__()
        self.embed = nn.Conv2d(1, d, patch, stride=patch)                 # 16 patches of 2 x 2 -> 16 tokens
        self.cls = nn.Parameter(torch.zeros(1, 1, d))                     # class token
        self.pos = nn.Parameter(torch.randn(1, (8 // patch) ** 2 + 1, d) * 0.02)   # learned positions
        block = nn.TransformerEncoderLayer(d, heads, 2 * d, dropout=0.0, activation="gelu",
                                           batch_first=True, norm_first=True)
        self.encoder = nn.TransformerEncoder(block, depth, enable_nested_tensor=False)
        self.norm, self.head = nn.LayerNorm(d), nn.Linear(d, 10)

    def forward(self, x):
        tokens = self.embed(x).flatten(2).transpose(1, 2)                 # (n, 16, d)
        tokens = torch.cat([self.cls.expand(len(x), -1, -1), tokens], dim=1) + self.pos
        return self.head(self.norm(self.encoder(tokens)[:, 0]))          # read out the class token

print("mean of 3 seeds, no augmentation")
report("ViT", ViT)
mean of 3 seeds, no augmentation
ViT   18218 params   val 0.956   test 0.962   shifted test 0.399

With the most parameters (18,218) it is the weakest of the three on validation (0.956) and test (0.962), and on shifted images it is no better than the MLP (0.399). A one-pixel shift changes the content of every 2 ×\times 2 patch, and the learned position embeddings carry no built-in notion that neighbouring positions are similar. ViTs beat CNNs when they are pretrained on millions of images; on a thousand they lack the CNN's built-in assumptions and have to learn them from too little data (vision transformers).

Step 4: teaching invariance with data

If the architecture does not know that shifted digits are the same digit, the data can say so: train on images shifted by a random −1-1, 00 or +1+1 pixel in each direction (the shift function, a padded random crop applied to every training batch). The validation and test images are not augmented.

python · try it yourself
import copy
import numpy as np
import torch
from torch import nn
from torch.utils.data import TensorDataset, DataLoader
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split

X, y = load_digits(return_X_y=True)
X = (X / 16.0).reshape(-1, 1, 8, 8).astype(np.float32)          # images: (n, channels, 8, 8)
X_tmp, X_te, y_tmp, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_tr, X_va, y_tr, y_va = train_test_split(X_tmp, y_tmp, test_size=0.25, random_state=0, stratify=y_tmp)
X_tr, X_va, X_te = map(torch.from_numpy, (X_tr, X_va, X_te))
y_tr, y_va, y_te = (torch.tensor(a) for a in (y_tr, y_va, y_te))
X_sh = torch.roll(X_te, shifts=1, dims=3); X_sh[..., 0] = 0     # the test images moved 1 pixel right

def shift(xb, g):                                               # random shift of -1, 0 or +1 pixel per image
    pad = nn.functional.pad(xb, (1, 1, 1, 1))
    dy, dx = torch.randint(0, 3, (2, len(xb)), generator=g)
    return torch.stack([pad[i, :, dy[i]:dy[i] + 8, dx[i]:dx[i] + 8] for i in range(len(xb))])

def accuracy(model, X, y):
    model.eval()
    with torch.no_grad():
        return (model(X).argmax(1) == y).float().mean().item()

def fit(model, seed, epochs=40, augment=False):
    g = torch.Generator().manual_seed(seed)
    loader = DataLoader(TensorDataset(X_tr, y_tr), batch_size=64, shuffle=True, generator=g)
    opt = torch.optim.AdamW(model.parameters(), lr=3e-3, weight_decay=1e-2)
    sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=epochs)
    best_va, best_state = -1.0, None
    for epoch in range(epochs):
        model.train()
        for xb, yb in loader:
            if augment:
                xb = shift(xb, g)
            loss = nn.functional.cross_entropy(model(xb), yb)
            opt.zero_grad(); loss.backward(); opt.step()
        sched.step()
        va = accuracy(model, X_va, y_va)
        if va > best_va:                                        # keep the best epoch on validation
            best_va, best_state = va, copy.deepcopy(model.state_dict())
    model.load_state_dict(best_state)
    return best_va

def report(name, make, augment=False):
    rows = []
    for seed in (0, 1, 2):
        torch.manual_seed(seed)
        model = make()
        rows.append((fit(model, seed, augment=augment), accuracy(model, X_te, y_te), accuracy(model, X_sh, y_te)))
    va, te, sh = np.array(rows).mean(axis=0)
    params = sum(p.numel() for p in model.parameters())
    print(f"{name:4s} {params:6d} params   val {va:.3f}   test {te:.3f}   shifted test {sh:.3f}")

mlp = lambda: nn.Sequential(nn.Flatten(), nn.Linear(64, 128), nn.ReLU(), nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 10))
cnn = lambda: nn.Sequential(nn.Conv2d(1, 16, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
                            nn.Conv2d(16, 32, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
                            nn.Flatten(), nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 10))
print("mean of 3 seeds, trained with random 1-pixel shifts")
report("MLP", mlp, augment=True)
report("CNN", cnn, augment=True)
mean of 3 seeds, trained with random 1-pixel shifts
MLP   17226 params   val 0.945   test 0.927   shifted test 0.925
CNN   13706 params   val 0.971   test 0.960   shifted test 0.953

Augmentation closes the robustness gap: the MLP now keeps 0.925 on shifted images and the CNN 0.953, almost their unshifted test accuracy. It is not free. The MLP must now learn every digit at nine positions with the same 17,226 parameters, and its clean test accuracy drops from 0.969 to 0.927. The CNN's weight sharing makes the same lesson cheap: its test accuracy moves only from 0.969 to 0.960.

Step 5: the ViT with augmentation

python · try it yourself
import copy
import numpy as np
import torch
from torch import nn
from torch.utils.data import TensorDataset, DataLoader
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split

X, y = load_digits(return_X_y=True)
X = (X / 16.0).reshape(-1, 1, 8, 8).astype(np.float32)          # images: (n, channels, 8, 8)
X_tmp, X_te, y_tmp, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_tr, X_va, y_tr, y_va = train_test_split(X_tmp, y_tmp, test_size=0.25, random_state=0, stratify=y_tmp)
X_tr, X_va, X_te = map(torch.from_numpy, (X_tr, X_va, X_te))
y_tr, y_va, y_te = (torch.tensor(a) for a in (y_tr, y_va, y_te))
X_sh = torch.roll(X_te, shifts=1, dims=3); X_sh[..., 0] = 0     # the test images moved 1 pixel right

def shift(xb, g):                                               # random shift of -1, 0 or +1 pixel per image
    pad = nn.functional.pad(xb, (1, 1, 1, 1))
    dy, dx = torch.randint(0, 3, (2, len(xb)), generator=g)
    return torch.stack([pad[i, :, dy[i]:dy[i] + 8, dx[i]:dx[i] + 8] for i in range(len(xb))])

def accuracy(model, X, y):
    model.eval()
    with torch.no_grad():
        return (model(X).argmax(1) == y).float().mean().item()

def fit(model, seed, epochs=40, augment=False):
    g = torch.Generator().manual_seed(seed)
    loader = DataLoader(TensorDataset(X_tr, y_tr), batch_size=64, shuffle=True, generator=g)
    opt = torch.optim.AdamW(model.parameters(), lr=3e-3, weight_decay=1e-2)
    sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=epochs)
    best_va, best_state = -1.0, None
    for epoch in range(epochs):
        model.train()
        for xb, yb in loader:
            if augment:
                xb = shift(xb, g)
            loss = nn.functional.cross_entropy(model(xb), yb)
            opt.zero_grad(); loss.backward(); opt.step()
        sched.step()
        va = accuracy(model, X_va, y_va)
        if va > best_va:                                        # keep the best epoch on validation
            best_va, best_state = va, copy.deepcopy(model.state_dict())
    model.load_state_dict(best_state)
    return best_va

def report(name, make, augment=False):
    rows = []
    for seed in (0, 1, 2):
        torch.manual_seed(seed)
        model = make()
        rows.append((fit(model, seed, augment=augment), accuracy(model, X_te, y_te), accuracy(model, X_sh, y_te)))
    va, te, sh = np.array(rows).mean(axis=0)
    params = sum(p.numel() for p in model.parameters())
    print(f"{name:4s} {params:6d} params   val {va:.3f}   test {te:.3f}   shifted test {sh:.3f}")

class ViT(nn.Module):
    def __init__(self, patch=2, d=32, depth=2, heads=4):
        super().__init__()
        self.embed = nn.Conv2d(1, d, patch, stride=patch)                 # 16 patches of 2 x 2 -> 16 tokens
        self.cls = nn.Parameter(torch.zeros(1, 1, d))                     # class token
        self.pos = nn.Parameter(torch.randn(1, (8 // patch) ** 2 + 1, d) * 0.02)   # learned positions
        block = nn.TransformerEncoderLayer(d, heads, 2 * d, dropout=0.0, activation="gelu",
                                           batch_first=True, norm_first=True)
        self.encoder = nn.TransformerEncoder(block, depth, enable_nested_tensor=False)
        self.norm, self.head = nn.LayerNorm(d), nn.Linear(d, 10)

    def forward(self, x):
        tokens = self.embed(x).flatten(2).transpose(1, 2)                 # (n, 16, d)
        tokens = torch.cat([self.cls.expand(len(x), -1, -1), tokens], dim=1) + self.pos
        return self.head(self.norm(self.encoder(tokens)[:, 0]))          # read out the class token

print("mean of 3 seeds, trained with random 1-pixel shifts")
report("ViT", ViT, augment=True)
mean of 3 seeds, trained with random 1-pixel shifts
ViT   18218 params   val 0.884   test 0.868   shifted test 0.867

The ViT becomes robust too (0.867 shifted, 0.868 test), but at a much lower level: in 40 epochs it does not fit the harder, augmented task (validation 0.884). That is the "data hunger" of transformers in one number. More epochs, a warm-up, a smaller patch embedding or pretraining would help; with the same budget as the others it loses.

Step 6: the results table

python · try it yourself
import pandas as pd

# validation, test and shifted-test accuracies copied from the outputs of steps 1 to 5
rows = [
    ("logistic regression", "none",   650, 0.972, 0.975, 0.406),
    ("MLP",                 "none", 17226, 0.975, 0.969, 0.421),
    ("CNN",                 "none", 13706, 0.980, 0.969, 0.572),
    ("ViT",                 "none", 18218, 0.956, 0.962, 0.399),
    ("MLP",                 "shift", 17226, 0.945, 0.927, 0.925),
    ("CNN",                 "shift", 13706, 0.971, 0.960, 0.953),
    ("ViT",                 "shift", 18218, 0.884, 0.868, 0.867),
]
df = pd.DataFrame(rows, columns=["model", "augment", "params", "val", "test", "shifted"])
df["drop"] = (df["test"] - df["shifted"]).round(3)
print(df.to_string(index=False))
print()
print("best on validation:", df.loc[df["val"].idxmax(), ["model", "augment"]].tolist())
print("best on shifted test:", df.loc[df["shifted"].idxmax(), ["model", "augment"]].tolist())
print("one test image is worth", round(1 / 360, 4), "of accuracy")
              model augment  params   val  test  shifted  drop
logistic regression    none     650 0.972 0.975    0.406 0.569
                MLP    none   17226 0.975 0.969    0.421 0.548
                CNN    none   13706 0.980 0.969    0.572 0.397
                ViT    none   18218 0.956 0.962    0.399 0.563
                MLP   shift   17226 0.945 0.927    0.925 0.002
                CNN   shift   13706 0.971 0.960    0.953 0.007
                ViT   shift   18218 0.884 0.868    0.867 0.001

best on validation: ['CNN', 'none']
best on shifted test: ['CNN', 'shift']
one test image is worth 0.0028 of accuracy

What the numbers say

  1. Without augmentation, the architecture hardly matters on clean images. Logistic regression, the MLP, the CNN and the ViT all score between 0.962 and 0.975 on the test set. One test image is worth 0.0028 of accuracy, and three seeds of a 360-image evaluation cannot separate 0.969 from 0.975 with confidence: the difference is about two images.
  2. The architecture's assumption shows under the matching shift. The CNN keeps 0.572 of the shifted images against 0.40 to 0.42 for the models that tie weights to positions. It is the only model whose wiring says anything about translation, and even it is far from invariant.
  3. Data can teach what the wiring does not, at a price. With shifted training images every model becomes robust, but the price in clean accuracy is small only for the CNN (0.009) and large for the MLP (0.042) and the ViT (0.094).
  4. The best model depends on the question. On clean validation accuracy the CNN without augmentation wins (0.980), on the shifted test the augmented CNN (0.953). If the deployment will see digits that are not centred, the augmented CNN is the choice; if it will only see centred digits, logistic regression with 650 parameters is as good as any network here.

What the numbers cannot tell you: everything is measured on one tiny, clean data set of 8 ×\times 8 images, with one fixed training budget that suits the small models better than the ViT, and three seeds. The shift probe tests one kind of robustness; rotations, thicker strokes or other handwriting styles are not tested.

Extensions

  • Per-seed spread. Print the three seeds of each model as well as the mean, and compute the standard deviation. Which differences in the table are larger than two standard deviations?
  • A shift-invariant CNN. Replace the last pooling and the flatten with global average pooling (nn.AdaptiveAvgPool2d(1), pooling and receptive fields). How much of the shift gap closes without augmentation?
  • Give the ViT a fair chance. Train it for 120 epochs with a 5-epoch warm-up (the tiny transformer lesson has a warm-up and cosine schedule). Does it catch up with the augmented CNN?
  • Your own NumPy network. Train the MLP with your autograd engine instead of PyTorch, with the same augmentation, and compare.
  • Larger shifts. Evaluate on shifts of 2 pixels, or vertical shifts, without retraining. Which model degrades most slowly?

Write-up template

Copy this outline and fill it in with your numbers.

md
# Architecture comparison: <task>

## Question
Which architecture should we use for <task>, and does it matter how inputs are positioned?

## Setup
- Data: <source, size, split, how the split was made>
- Models: <architectures, parameter counts>
- Training: <optimizer, learning rate, schedule, epochs, batch size, augmentation; same for all?>
- Evaluation: <metrics, validation for choices, test once, robustness probe, number of seeds>

## Results
| model | augmentation | params | val | test | shifted test |
|---|---|---|---|---|---|

## Findings
1. <the main result, with the size of the difference and whether it is larger than seed noise>
2. <what the robustness probe shows>
3. <cost of augmentation per model>

## Limits
<one data set, image size, training budget, seeds, untested kinds of shift>

## Recommendation
<which model, under which assumption about the deployment data, and what to try next>

Checklist

  • The split, the seeds and the hyperparameters were fixed before the first model ran, and are the same for every model.
  • Every choice (epoch, CC) was made on validation; the test and shifted-test sets were never used to choose anything.
  • Each reported number states its data set, its metric and the number of seeds behind it.
  • Differences smaller than the noise (one test image is 0.0028) are called ties, not wins.
  • The write-up names the assumption each architecture makes and whether the experiment tested it.

Test yourself

In step 2, the MLP and the CNN both score 0.969 on the clean test set but 0.421 and 0.572 on the shifted one. What explains the difference?

  1. The CNN has more parameters
  2. Convolution shares its weights across positions, so a shifted digit produces a shifted feature map instead of hitting different weights
  3. The CNN was trained longer
  4. The MLP overfits the validation set

Why is every network number the mean of three seeds?

  1. To make training faster
  2. Because one run of a small network evaluated on 360 images varies by about as much as the differences being compared
  3. Because PyTorch requires three seeds
  4. To use the test set three times for choosing

After training with random shifts, the MLP's clean test accuracy falls from 0.969 to 0.927 while the CNN's falls only from 0.969 to 0.960. Why?

  1. Augmentation leaks the test set
  2. The MLP must learn each digit separately at every position with the same parameters, while the CNN's shared filters already handle positions
  3. The CNN uses a different optimizer
  4. Augmentation was applied to the CNN's test set

Logistic regression reaches 0.975 test accuracy with 650 parameters. What is the right conclusion?

  1. Neural networks are useless for images
  2. On small, centred 8 x 8 digits a linear model is a strong baseline; the networks' advantages show in robustness and on harder data, so always run the baseline
  3. The test set is broken
  4. The networks were trained wrongly