Noisy Image Dataset Cleanup and a NumPy Two-Layer Net with Gradient Checks
Machine LearningModel answerLast updated
Plan a data-quality pipeline for a noisy, imbalanced small-image dataset, then derive and numerically verify backprop for a two-layer softmax network in NumPy.
You have a collection of 32×32 color images spanning 10 to 20 classes. The data is known to be imperfect: roughly 8-15% of labels are wrong, some files are corrupted or of very low quality, and the class frequencies are skewed.
Part 1: Baseline and data-quality plan
Describe how you would build a reliable classifier on this data. Your answer should cover:
- A baseline model and the metrics you log for every run.
- How you would build train, validation and test splits that can be trusted, including how you prevent leakage.
- How you would detect and quantify label noise, and how you would find corrupted or low-quality images.
- How you would handle class imbalance.
- A comparison of mitigation strategies, such as pruning samples by model confidence, co-teaching, and strong augmentation like MixUp or CutMix. For each, explain how you would measure its effect on top-1 accuracy, calibration, and the confusion matrix.
Part 2: Backprop from first principles
Using only NumPy-style linear algebra, define a network of the form linear → ReLU → linear → softmax cross-entropy.
- Write the forward and backward passes and give the analytical gradients for all parameters.
- Explain how you would validate them with a numerical gradient check.
- Discuss numerical stability (log-sum-exp), weight initialization, and regularization.
- Explain how you would extend the approach to a convolutional network for this dataset.
Hints
Hint 1
Fix the evaluation set first: if the test labels are also noisy, you cannot tell whether a mitigation really helped. Think about grouping near-duplicates before splitting and about a small hand-verified subset.
Hint 2
To flag noisy labels you need predictions that were not trained on the sample itself. Out-of-fold probabilities with per-class thresholds expose likely mislabels and which class pairs get confused.
Hint 3
For the gradient at the logits, the softmax plus cross-entropy combination simplifies to (probabilities minus one-hot) divided by the batch size. The ReLU simply masks the upstream gradient where the pre-activation was not positive.
Hint 4
For the gradient check, use centered differences with a small step in float64, compare with a relative error, and turn off anything stochastic. Check a random subset of entries per parameter.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Data-quality plan
Baseline and discipline
Start with a small ResNet adapted to 32×32 inputs: stride-1 stem with no max-pool, SGD with momentum 0.9, cosine learning-rate decay, weight decay around 5e-4, random-crop (4 px padding) and horizontal flip, about 100 epochs. Log for every run: top-1 accuracy (overall and per class), macro-F1, expected calibration error (15 bins), NLL, and a normalized confusion matrix. Change exactly one thing per experiment and run 3 seeds, reporting mean ± std. Differences smaller than the seed spread are not findings.
Trustworthy splits
With 8-15% label noise, a noisy test set caps measured accuracy near 85-92% and blurs real improvements. So:
- Deduplicate and group. Compute perceptual hashes or embedding similarity; images above a high similarity threshold (for example cosine > 0.95) form a group. Split by group so near-copies never straddle train and test.
- Stratify by class, roughly 80/10/10.
- Build a clean test subset. Have 2-3 annotators relabel 1-2k images and keep majority-agreement ones. This is the headline metric; the noisy test set is secondary.
- Fit everything on train only: normalization statistics, noise detectors, thresholds. Tune on validation, touch test once.
Corrupted and low-quality images
Cheap checks first: decode failures, wrong shape or channel count, near-constant images (tiny pixel std), extreme brightness or saturation, blur via variance of the Laplacian. Then embedding checks: kNN-distance outliers or an isolation forest in a pretrained or self-supervised feature space. Always eyeball a sample from each flagged bucket before deleting, and report "x% flagged, y% confirmed on a manual review of 200."
Detecting and quantifying label noise
Use confident learning:
- Get out-of-fold probabilities via k-fold cross-validation. In-sample probabilities memorize the noise.
- For each class j, set a threshold t_j equal to the mean predicted probability of j over samples labeled j.
- A sample labeled i is confidently of class j if p_j ≥ t_j for some j ≠ i.
- Count into a joint matrix C[i][j]. Normalized off-diagonal mass estimates the noise rate and shows which pairs (cat/dog) are confused.
Audit about 300 flagged and 300 unflagged samples by hand to get precision, recall and a calibrated noise-rate estimate. Complementary signals are late-training loss trajectories (or area-under-margin) and kNN label disagreement.
Class imbalance
In rough order of effort: class-balanced sampling or effective-number loss weights; logit adjustment (subtract τ·log prior at inference), which is cheap and strong; focal loss only with care, since under noise many "hard" examples are simply mislabeled. Judge by macro-F1 and per-class recall, because overall accuracy can barely move while minority recall changes a lot.
Comparing mitigations
| Strategy | Mechanism | Typical effect | Risk |
|---|---|---|---|
| Confidence-based pruning | Drop or relabel out-of-fold-flagged samples | Gains of a few points on clean test; sharper confusion diagonal | Removes hard-but-correct minority samples; cap pruning per class |
| Co-teaching | Two networks pick small-loss samples for each other, keep rate ramps down | Robust at 10-20% noise | Needs a noise-rate estimate; double compute |
| MixUp / CutMix | Convex or patch-wise mixing of images and labels | Accuracy gain and a clear ECE drop; delays memorizing noise | Hurts an underfit model; tune α in 0.2-1.0 |
| Label smoothing | Soft targets | Better calibration | Can interfere with later temperature scaling |
| Robust losses (GCE, symmetric CE) | Bounded loss | Moderate gain | Slower convergence |
Report an ablation ladder, one row per step: baseline → dedup and corruption filter → pruning → MixUp/CutMix → logit adjustment → temperature scaling (fit on validation). Each row shows clean-test accuracy, macro-F1, ECE and a confusion-matrix difference. Expect pruning to help mostly on confused pairs, augmentation and temperature scaling to fix calibration, and imbalance handling to lift minority rows.
Part 2: Two-layer network
Forward
- z1 = X W1 + b1
- h = ReLU(z1)
- s = h W2 + b2
- p = softmax(s)
- L = −(1/N) Σ log p[n, y_n] + (λ/2)(‖W1‖² + ‖W2‖²)
Backward
- ds = (p − onehot(y)) / N
- dW2 = hᵀ ds + λ W2, db2 = Σ ds
- dh = ds W2ᵀ
- dz1 = dh ⊙ 1[z1 > 0]
- dW1 = Xᵀ dz1 + λ W1, db1 = Σ dz1
Code
import numpy as np
def init_params(D, H, C, seed=0):
rng = np.random.default_rng(seed)
return {
"W1": rng.standard_normal((D, H)) * np.sqrt(2.0 / D), # He init for ReLU
"b1": np.zeros(H),
"W2": rng.standard_normal((H, C)) * np.sqrt(1.0 / H),
"b2": np.zeros(C),
}
def loss_and_grads(P, X, y, reg=0.0):
W1, b1, W2, b2 = P["W1"], P["b1"], P["W2"], P["b2"]
N = X.shape[0]
z1 = X @ W1 + b1
h = np.maximum(0.0, z1)
s = h @ W2 + b2
sh = s - s.max(axis=1, keepdims=True)
logp = sh - np.log(np.exp(sh).sum(axis=1, keepdims=True))
loss = -logp[np.arange(N), y].mean() + 0.5 * reg * (np.sum(W1**2) + np.sum(W2**2))
ds = np.exp(logp)
ds[np.arange(N), y] -= 1.0
ds /= N
dh = ds @ W2.T
dz1 = dh * (z1 > 0)
grads = {
"W2": h.T @ ds + reg * W2, "b2": ds.sum(0),
"W1": X.T @ dz1 + reg * W1, "b1": dz1.sum(0),
}
return loss, grads
def grad_check(P, X, y, reg=1e-3, eps=1e-5, n=10, seed=1):
rng = np.random.default_rng(seed)
_, g = loss_and_grads(P, X, y, reg)
worst = 0.0
for k, v in P.items():
for _ in range(n):
i = tuple(rng.integers(0, d) for d in v.shape)
old = v[i]
v[i] = old + eps; lp, _ = loss_and_grads(P, X, y, reg)
v[i] = old - eps; lm, _ = loss_and_grads(P, X, y, reg)
v[i] = old
num = (lp - lm) / (2 * eps)
rel = abs(num - g[k][i]) / max(1e-8, abs(num) + abs(g[k][i]))
worst = max(worst, rel)
return worst # expect < 1e-6 in float64
Gradient check practice
Use float64, centered differences with eps around 1e-5, and relative error. Expect roughly 1e-7 or better; 1e-2 or worse signals a bug. Check a random subset of entries per parameter on a tiny batch. ReLU kinks can cause rare false mismatches when a pre-activation is within eps of zero, so rerun with another seed before concluding there is a bug.
Stability, init, regularization
- Log-sum-exp: subtract the row max before exponentiating and compute log-softmax directly, so there is no overflow and no log of a tiny probability.
- Initialization: He init (variance 2/fan_in) for the ReLU layer keeps activation variance stable; a smaller scale on the output layer gives near-uniform initial predictions, so the initial loss should be about log(C). That is a useful sanity check.
- Regularization: L2 on weights (not biases), plus dropout or augmentation; also overfit a tiny batch to confirm the pipeline can reach near-zero loss.
Extending to CNNs
Replace the first linear layer with convolutions (im2col turns them into matrix multiplies, with the backward pass being the transposed operation), add batch normalization and pooling, and finish with global average pooling and a linear classifier. The softmax-cross-entropy gradient at the logits is unchanged; only the layers underneath change. Weight sharing makes the conv gradient a sum over spatial positions.
Common mistakes
- Using in-sample predictions to detect noise.
- Splitting before deduplicating, which leaks near-copies.
- Tuning thresholds on the test set.
- Judging imbalance fixes by accuracy alone.
- Forgetting the 1/N factor or the regularization term in the gradient, or gradient-checking in float32.