Winning Kaggle the Reproducible Way

Interactive chapter

This page shows the chapter notebook with its saved results. Constructed examples do not measure competition gains.

Chapter 43: Image Classification Tricks

Try the decision first

How much does a random split of crops overstate accuracy compared with splitting by source image, and how does that grow with crops per image?

Write your expectation before opening the worked results. Use the chapter activity to compare supported inputs. To change the calculation itself, run the notebook on GitHub.

Your answers stay on this page until you download them. They are not sent to a server.

Open the chapter activity

Worked notebook and saved results

How much does a random split of crops overstate accuracy compared with splitting by source image, and how does that grow with crops per image?

A validation score that cannot be reproduced on new images misleads every later decision, including which crop policy, resolution or backbone to keep. The chapter asks that the original image identity survive preprocessing so the split respects it.

Real digit images and a memorizing classifier: the overstatement is modest (0.03) here and would be larger for noisy labels or a model that memorizes more, and smaller for models that do not. Scores at one crop per image differ by noise only.

The experiment

Real data: scikit-learn's bundled digits, enlarged to 16 x 16. 300 source images are each cut into 1, 3 or 9 overlapping 14 x 14 crops (the control). A one-nearest-neighbor classifier on pixels is scored three ways: 5-fold cross-validation with crops split at random, 5-fold cross-validation with whole source images grouped, and accuracy on the crops of 400 source images never seen in training. Predictions are pooled before scoring; results are means over 8 draws.

Calculation code
import numpy as np
from scipy.ndimage import zoom
from sklearn.datasets import load_digits
from sklearn.model_selection import GroupKFold, KFold
from sklearn.neighbors import KNeighborsClassifier

from kaggle_companion.activities._common import clean

SEED = 43
REPLICATES = 8          # independent source-image draws per control value; results are means over them
SOURCES, TEST_SOURCES = 300, 400
CROP = 14               # crops are 14 x 14 windows of a 16 x 16 image
OFFSETS = [(i, j) for i in range(3) for j in range(3)]    # nine possible, heavily overlapping, window positions


def load_images():
    """Real digit scans: scikit-learn's bundled 8 x 8 digits, enlarged to 16 x 16 by bilinear interpolation."""
    digits = load_digits()
    return np.stack([zoom(image / 16.0, 2, order=1) for image in digits.images]), digits.target


def make_crops(images, labels, crops_per_image, rng):
    """Cut `crops_per_image` windows out of every source image; remember which source each crop came from."""
    X, y, source = [], [], []
    for n, (image, label) in enumerate(zip(images, labels)):
        for position in rng.choice(len(OFFSETS), crops_per_image, replace=False):
            i, j = OFFSETS[position]
            X.append(image[i:i + CROP, j:j + CROP].ravel())
            y.append(label)
            source.append(n)
    return np.array(X), np.array(y), np.array(source)


def cross_validated_accuracy(splitter, X, y, groups=None):
    """Pool the held-out predictions of every fold and score them once."""
    pred = np.zeros(len(y), dtype=int)
    for fit, out in splitter.split(X, y, groups):
        pred[out] = KNeighborsClassifier(1).fit(X[fit], y[fit]).predict(X[out])
    return float((pred == y).mean())


def run(crops_per_image):
    images, labels = load_images()
    scores = {"random": [], "grouped": [], "heldout": []}
    for r in range(REPLICATES):
        rng = np.random.default_rng(SEED * 100 + r)
        order = rng.permutation(len(labels))
        train, test = order[:SOURCES], order[1000:1000 + TEST_SOURCES]       # test sources never appear in training
        X, y, source = make_crops(images[train], labels[train], crops_per_image, rng)
        X_test, y_test, _ = make_crops(images[test], labels[test], crops_per_image, rng)
        scores["random"].append(cross_validated_accuracy(KFold(5, shuffle=True, random_state=0), X, y))   # crops split at random
        scores["grouped"].append(cross_validated_accuracy(GroupKFold(5), X, y, source))                   # whole source images split
        scores["heldout"].append(float((KNeighborsClassifier(1).fit(X, y).predict(X_test) == y_test).mean()))
    mean = {k: float(np.mean(v)) for k, v in scores.items()}
    return clean({"crops_per_image": crops_per_image, "accuracy": mean, "training_crops": SOURCES * crops_per_image,
                  "random_overstates_in_share_of_worlds": float(np.mean(np.array(scores["random"]) > np.array(scores["heldout"]))),
                  "replicates": REPLICATES, "source_images": SOURCES})

Measure it across the control

The control is crops cut from each source image. Each value below runs the whole experiment from the generator up.

Calculation code
import pandas as pd
from kaggle_companion.activities.ch43 import explain

VALUES = [1, 3, 9]
results = {value: run(value) for value in VALUES}
table = pd.DataFrame({str(v): explain(results[v], v)['metrics'] for v in VALUES})
print(table.to_string())
                            1       3       9
Random split            0.877   0.964   0.995
Split by source image   0.885   0.935   0.957
New source images       0.893   0.942   0.962
Random overstatement   -0.016  +0.021  +0.033
Grouped difference     -0.008  -0.008  -0.005

Look at it

The figure shows the default setting, crops cut from each source image = 9.

Calculation code
import matplotlib.pyplot as plt
from kaggle_companion.activities.ch43 import draw, NCOLS, HEIGHT

DEFAULT = 9
fig, axes = plt.subplots(1, NCOLS, figsize=(6.6 if NCOLS == 1 else 10.4, HEIGHT), layout='constrained')
draw(axes, results[DEFAULT], DEFAULT)
plt.show()
Saved figure from this chapter calculation

What the result says

With 9 crops per source image (2,700 training crops), a random split reports 0.995 and a split by source image 0.957, while new source images score 0.962. The random split overstates accuracy by 0.995 - 0.962 = 0.033; the grouped split is 0.957 - 0.962 = -0.005 away. The random split claims an error rate 7.3 times smaller than the real one, and overstated accuracy in 100% of 8 draws.

Apply this to your competition

Book location: Chapter 43, Separate Development From Assessment.

Technical corrections

Apply a lesson from this chapter

Select a lesson whose conditions match your project. State how you would test it and what would make you reject it.

Check optimizer coverage after adding trainable modules

Conditions

  • a pretrained backbone gains a recurrent or attention adapter

Action

  • Proposed: assert every intended trainable parameter is present exactly once in optimizer groups.

Check

  • Proposed: compare trainable parameter identities with optimizer group identities and add deliberately trainable GRU/attention groups; check gradients and actual parameter changes.

Limits

  • Coverage checks and missing groups are proposed correction. Gradients can exist for omitted parameters without optimizer updates.

Find source links and value grades in the lesson atlas

Detect nonfinite training and load an explicitly validated checkpoint

Conditions

  • mixed-precision adapter training can diverge or omit a valid checkpoint

Action

  • Proposed adaptation of source observation: Check finite loss/parameters, diagnose failed batches, reduce LR and restore a validated checkpoint; test fallback separately.

Check

  • Proposed verification: Verify skipped-batch counts, finite predictions and checkpoint provenance in failure simulations.

Limits

  • Skipping batches or reinitializing adapters can alter training silently; fallback existence does not ensure quality.

Find source links and value grades in the lesson atlas

Select checkpoints using the target validation metric

Conditions

  • the evaluation objective is F1 rather than training loss

Action

  • Proposed recipe: select model weights using validation F1.

Check

  • Proposed check: Verify the F1 implementation and compare selected checkpoints on a separate assessment fold, fixing any threshold-tuning protocol.

Limits

  • Repeated checkpoint selection can overfit a small validation set; F1 must use the correct averaging and thresholds.

Find source links and value grades in the lesson atlas

Regularize only the layers that need it in a tiny image task

Conditions

  • small neural-response training data overfits

Action

  • Proposed conditional application: Compare dropout, L2 and batch normalization by layer, using dense-only dropout as a tested candidate.

Check

  • Proposed check: Compare regularization placements with repeated image splits and fixed budgets, reporting variance and train-versus-validation behavior.

Limits

  • Only20evaluation examples make selected settings uncertain; excessive regularization can underfit.

Find source links and value grades in the lesson atlas

Re-evaluate dropout after scaling training data and ensemble size

Conditions

  • training scales change the need and cost of regularization

Action

  • Proposed adaptation of source observation: Compare dropout/no-dropout under both single-model and final-ensemble budgets after scaling data.

Check

  • Proposed verification: Track convergence, ensemble quality and wall time, not just per-epoch accuracy.

Limits

  • This is source-specific; removing regularization is not generally safe for large datasets.

Find source links and value grades in the lesson atlas

Compare high-resolution DCL refinement with the preceding image backbone

Conditions

  • fine-grained product labels need detailed visual representations

Action

  • Run a separately budgeted high-resolution DCL refinement comparison against the preceding backbone.

Check

  • Hold data/split fixed and compare quality, resolution-only control and complete training/inference cost.

Limits

  • DCL details are absent from the local packet; resolution and objective changes are bundled.
  • Average/max concatenated pooling is a separate architecture choice.

Find source links and value grades in the lesson atlas

Separate resolution hypotheses from measured gains

Conditions

  • larger images increase compute without clear current validation gains

Action

  • Proposed adaptation of source observation: Compare image resolution jointly with runtime and retain higher resolution only as an explicitly tested hypothesis.

Check

  • Proposed verification: Measure held-out score, training time and inference memory across resolutions.

Limits

  • The author’s private-set rationale is speculative; higher resolution was not shown to cause an isolated gain.

Find source links and value grades in the lesson atlas

Use input dropout as a provisional response to unrefined high-dimensional features

Conditions

  • many correlated input columns remain and feature-engineering time is limited

Action

  • Proposed adaptation of source observation: Compare modest input dropout with the same network without dropout as a temporary regularization experiment.

Check

  • Proposed verification: Evaluate sensitivity to dropout rate and inspect whether informative sparse columns are damaged.

Limits

  • No isolated dropout improvement is given; the source’s expectation of stronger future feature engineering is untested.

Find source links and value grades in the lesson atlas

Retain general checkpoints when subgroup fine-tuning lacks support

Conditions

  • specialist fine-tuning has small or synthetic-only subgroup data

Action

  • Proposed adaptation of source observation: Compare specialist and general checkpoints separately for each subtype and keep the general one when evidence deteriorates or cannot be measured.

Check

  • Proposed verification: Evaluate real subgroup held-outs and track fine-tuning stages.

Limits

  • The explanation for horizontal-bar regression is the author’s hypothesis.
  • Aggregate all-chart versus selective specialist-pipeline scores do not isolate the effect of fine-tuning, checkpoint choice, training data or subgroup validation.

Find source links and value grades in the lesson atlas

Freeze early layers to fit larger batches then unfreeze

Conditions

  • fine-tuning a large vision model is memory constrained

Action

  • Proposed adaptation of source observation: Compare staged freezing/unfreezing with full-parameter training under the same memory budget.

Check

  • Proposed verification: Measure memory, convergence and final quality; separately evaluate resampling/cleaning.

Limits

  • No isolated memory saving or causal gain is supplied, and failed cleaning is specific to this dataset.
  • Freezing-row public/private scores are a sequential author comparison of a complete recipe; they do not quantify memory saving or prove isolated causal benefit.

Find source links and value grades in the lesson atlas

Initialize residual attention with a zero gate

Conditions

  • spatial feature maps can accommodate an attention extension

Action

  • Proposed: compute spatial query-key-value attention and add it to the original feature map through a zero-initialized learnable gate.

Check

  • Proposed: compare with the existing baseline on the same valid held-out split and task metric; record runtime and prediction alignment.

Limits

  • This class is instantiated by ResidualCNNWithSelfAttention; no measured attention ablation is shown. Attention forms an H*W by H*W matrix, so memory must be measured.

Find source links and value grades in the lesson atlas

Compare handcrafted region views with transfer learning

Conditions

  • microscopy cells have nucleus and cytoplasm masks

Action

  • Proposed conditional application: Create whole-cell, nucleus and cytoplasm views and compare handcrafted features with pretrained CNNs using MCC validation.

Check

  • Proposed check: Keep all views from each patient/cell source in one split; compare feature/CNN views on MCC and memory.

Limits

  • Segmentation masks must exist at prediction time; 25GB notebook memory and external acquisition shift limit reuse.

Find source links and value grades in the lesson atlas

Audit image sizes and grayscale statistics before batching

Conditions

  • image resolutions and class counts vary substantially

Action

  • Proposed recipe: use image-size, class-count and grayscale-statistics audits to guide preprocessing and sampling.

Check

  • Proposed check: Compute training-only statistics and inspect size/class extremes, then test resizing on the smallest and largest images and verify channel handling.

Limits

  • Resizing can discard tiny-image detail; normalization statistics must exclude held-out data.

Find source links and value grades in the lesson atlas

Distinguish best checkpoints from the last training state

Conditions

  • training saves multiple checkpoint types and inference runs automatically

Action

  • Proposed adaptation of source observation: Explicitly select the validated best checkpoint for inference and retain separate last-state metadata.

Check

  • Proposed verification: Check loaded checkpoint identity, row alignment and held-out quality.

Limits

  • The packet does not say which checkpoint automatic inference loads; best-selection parity must be verified.

Find source links and value grades in the lesson atlas

Compare ensembles of fine-tuned image backbones

Conditions

  • a labeled X-ray classification task has limited domain-specific training resources

Action

  • Proposed recipe: test fine-tuned pretrained CNN alternatives and an ensemble.

Check

  • Proposed check: Compare single and ensemble models on patient- and acquisition-grouped held-out X-rays, including calibration, subgroup errors and inference cost.

Limits

  • Sparse README lacks split design; classroom scores do not establish clinical utility.

Find source links and value grades in the lesson atlas

Finish augmented image training with low-rate clean fine-tuning

Conditions

  • a CNN was trained with affine augmentation

Action

  • Proposed conditional application: Finish with a small number of low-learning-rate epochs without data augmentation.

Check

  • Proposed check: Resume identical checkpoints with low-rate clean versus augmented epochs; compare held-out accuracy and overfitting.

Limits

  • Removing augmentation may reduce robustness; no isolated numerical gain reported.

Find source links and value grades in the lesson atlas

Control which pretrained stages adapt

Conditions

  • pretrained image backbones with a task-specific head

Action

  • Proposed: freeze the backbone and optionally unfreeze its final residual stage.

Check

  • Proposed: inspect trainable parameter names and BatchNorm behavior; compare head-only and final-stage tuning on held-out images.

Limits

  • This is configurable implementation support, not evidence that freezing was selected for a particular run. requires_grad does not itself freeze BatchNorm running statistics.

Find source links and value grades in the lesson atlas

Build balanced fine-tuning data from cross-predicted correct examples

Conditions

  • training class prevalence differs from balanced target evaluation

Action

  • Proposed adaptation of source observation: Generate out-of-sample correctness/confidence estimates and sample a balanced refinement subset.

Check

  • Proposed verification: Evaluate class-wise accuracy and probability calibration on an independent natural/balanced set.

Limits

  • Selecting only easy correctly predicted examples can discard hard cases; top-k details are unspecified.

Find source links and value grades in the lesson atlas

Test label smoothing rather than assuming improvement

Conditions

  • label smoothing is being added to an image classifier

Action

  • Proposed recipe: keep an unsmoothed comparison and retain smoothing only if the target validation metric improves.

Check

  • Proposed check: Compare unsmoothed and tuned-smoothed targets on the actual metric, including calibration and minority errors.

Limits

  • Smoothing benefit depends on target noise and strength; no magnitude is given.

Find source links and value grades in the lesson atlas

Condition a shared representation with entity-specific linear readouts

Conditions

  • one image representation predicts responses for multiple named entities

Action

  • Proposed: look up an entity-specific weight vector and bias and apply them to shared image features.

Check

  • Proposed: verify entity IDs use a persistent vocabulary and compare against separate models and a joint output head on held-out images.

Limits

  • This supports known entity IDs; unseen-entity behavior is unspecified, and no comparative advantage or hardware cost is reported.

Find source links and value grades in the lesson atlas

Recheck optimizer choice for each backbone family

Conditions

  • an image ensemble contains different architecture families

Action

  • Proposed recipe: benchmark optimizer choice separately instead of copying one choice to every backbone.

Check

  • Proposed check: Tune learning rates comparably for each optimizer/backbone pair and compare quality and stability under fixed folds and budgets.

Limits

  • Optimizer and learning-rate schedules are coupled; source does not give matched controls.

Find source links and value grades in the lesson atlas

Track repeated pair contributions and weighting changes

Conditions

  • candidate triples duplicate entity pairs across network contexts

Action

  • Proposed adaptation of source observation: Record pair multiplicity and compare inverse-multiplicity weighting with equal triple weighting.

Check

  • Proposed verification: Evaluate devices with many versus few IPs and check training loss concentration.

Limits

  • The final weighting change lacked a demonstrated improvement and cellular generalization was unresolved.

Find source links and value grades in the lesson atlas

Delay downsampling for weak image signals

Conditions

  • early image compression may destroy weak steganographic evidence

Action

  • Proposed conditional application: Remove the first convolution stride and max-pooling so a pretrained SEResNet18 models the original resolution.

Check

  • Proposed check: Train matched downsampling and delayed-downsampling backbones on fixed local splits; compare steganalysis metric, convergence, GPU memory and latency.

Limits

  • High-resolution features increase memory and compute.
  • The source supplies no isolated numeric ablation of these downsampling changes; relevance depends on tiny image signals.

Find source links and value grades in the lesson atlas

Compare GeM pooling with an otherwise fixed image regressor

Conditions

  • image regression uses a globally pooled convolutional representation

Action

  • Proposed adaptation of source observation: Replace average pooling with generalized mean pooling and compare under the same regression loss and augmentation.

Check

  • Proposed verification: Check held-out metric and numerical stability for learned pooling exponent.

Limits

  • No numeric isolated pooling result is given; listed augmentations may not preserve labels in other tasks.

Find source links and value grades in the lesson atlas

Align pretrained hybrid components before joint fine-tuning

Conditions

  • CNN and transformer weights were pretrained independently

Action

  • Proposed conditional application: Replace patch embedding with CNN blocks, freeze transformer/head for one adaptation epoch, then unfreeze for joint training.

Check

  • Proposed check: Compare direct/staged composition with activation/gradient finite checks and held-out landmark retrieval scores.

Limits

  • One adaptation epoch is setup-specific; architecture mismatches may need more than freezing.

Find source links and value grades in the lesson atlas

Exclude incompatible heads when restoring a pretrained classifier

Conditions

  • pretraining and target classification have different class heads

Action

  • Proposed: restore the backbone while leaving target logits and auxiliary logits heads initialized for the new task.

Check

  • Proposed: verify head shapes, restored variable names and target class order; assess target validation separately.

Limits

  • The script trains at a fixed learning rate and does not report isolated transfer gain.

Find source links and value grades in the lesson atlas

Redo tuning after a backbone change and test patch overlap

Conditions

  • a new pretrained image backbone changes model size and representation

Action

  • Proposed adaptation of source observation: Revalidate the staged fine-tuning recipe and compare resolution increases with overlapping patch extraction.

Check

  • Proposed verification: Measure retrieval quality, memory and latency for matched checkpoints.

Limits

  • Several stages change together; final score cannot isolate the patch-overlap effect.

Find source links and value grades in the lesson atlas

Separate stopping policy from best-checkpoint saving

Conditions

  • fixed-epoch training where early stopping is disabled

Action

  • Proposed: save a checkpoint on lower validation loss even when training continues to its full epoch budget.

Check

  • Proposed: reload the selected checkpoint explicitly before inference and compare its validation loss to the returned in-memory model.

Limits

  • The source configuration disables early stopping; its returned model is not reloaded in that branch, so the proposed reload is an addition rather than an observed action.

Find source links and value grades in the lesson atlas

Use explicit evaluation mode for dropout-bearing predictors

Conditions

  • trained neural regressors contain dropout and are run under no_grad

Action

  • Proposed: switch the model to evaluation mode before held-out and submission inference.

Check

  • Proposed: call eval and verify repeated predictions are stable; inspect whether the external solver leaves the model in train or eval mode.

Limits

  • Evaluation mode is a proposed safeguard. The external solver state is not shown, so the source does not prove dropout was active at inference.

Find source links and value grades in the lesson atlas

Freeze then selectively unfreeze a transferred image backbone

Conditions

  • limited labelled images are available for a pretrained image classifier

Action

  • Proposed adaptation of source observation: Train the classification head with the backbone frozen, then compare unfreezing its last blocks.

Check

  • Proposed verification: Monitor held-out loss and compare with full unfreezing under matched training budget.

Limits

  • Epoch counts and learning-rate schedules are absent; the last-five-block choice is model-specific.

Find source links and value grades in the lesson atlas