models · Level 3

Train and test an image classifier with PyTorch

Build a CPU CNN, protect the data splits and inspect the evidence behind a result.

By Micky Irons

  • Level 3Building
  • 240 min
  • 6 chapters
  • Online course and PDF workbook
Fictional learning scenemodels / 03

Read, practise and review

Your next step

Start this course online

Register your start, then work through the lessons and exercises at your own pace. You can download the PDF separately. Where a scored exam is available, you will find it after the lessons.

Register or resume your course

Mickai privately records this registration and sends its team a course-start notification. It records your intention to start, not proof of attendance or completion. Our course-start privacy notice explains the details and the 30-day resume cookie.

Follow the Mickai company page on LinkedIn

You can start learning without subscribing or following. Newsletter email confirmation and provider enrolment are recorded separately.

Start with the essentials

The short answer

A defensible image experiment keeps source groups separate, fits preprocessing on training only, selects with validation and opens the final test after freezing the model. This original CPU lab executes that workflow on synthetic 8 by 8 patterns; its result does not establish real-image performance or NVIDIA certification.

What you will learn

  • Define a reproducible CPU image experiment with separate development and final-evaluation roles.
  • Keep related image views in one source split and validate the tensor and preprocessing contract.
  • Trace a small CNN, its logits, parameter count and classification metrics.
  • Run parameter updates and validation selection without using final-test examples.
  • Diagnose data, implementation and generalisation failures with concrete error evidence.
  • Freeze and reload a selected checkpoint, evaluate the final split and state result limits.

Who it is for

Python learners who completed tensor and training-loop foundations and want a concrete image-classification experiment.

Before you start

  • Complete Tensors, gradients and a first training loop (tensors-gradients-training-loop), including batches, gradients and validation.
  • Read Python functions, command-line output and unit tests.
  • Use a local Python environment with space for the official CPU PyTorch wheel and dependencies; no GPU, account or model key is required.

Run the synthetic exercise

Download the exercise source, tests and instructions (ZIP)

No real records, external service or model is used by this exercise. Extract the ZIP into a fresh folder, read README.md and follow its local test instructions. Complete WORKSHEET.md before consulting ANSWER-KEY.md.

Commissioned for MICKAI Training Academy and drafted with AI assistance. Actual CPU execution is recorded; independent content, assessment, learner-package and rendering review remain required.

Learn in your browser · Chapter 01 of 06

01

Define an image experiment before training

Choose the prediction, independence unit and evidence you will preserve. A tiny image task can teach a complete experiment without representing a real camera system.

The original MICKAI Pixel Workshop classifies an 8 by 8 greyscale array as vertical, horizontal or cross. Labels are integers 0, 1 and 2 in that order. A prediction concerns one array, not a person or an entire source group. Every pixel is generated by the supplied Python program; there are no photographs, personal records, external datasets or pretrained weights. The purpose is to train and challenge a small convolutional classifier while keeping every data and evaluation decision visible.

Begin with Tensors, gradients and a first training loop, available as tensors-gradients-training-loop. That course explains tensor arithmetic, differentiation and the generic update cycle. Here those ideas become a spatial input contract, grouped image split and an end-to-end classifier experiment. Transformers: attention explained and implemented concerns forward attention, while Build a tiny language model from scratch trains a character model. Those are useful related paths, not missing chapters to repeat here. This course concentrates on convolution and image evaluation.

Write the experiment contract before looking for an impressive score. The output is one of three known pattern classes. The data source is this fixed synthetic generator, the model runs on CPU, and the primary validation criterion is mean cross-entropy loss. Use 16 epochs, batch size 18, learning rate 0.03 and the documented model seed. Select the lowest clean validation loss, keeping the earliest epoch on an exact tie. These are exercise choices to inspect, not recommended settings for every image problem. The four-hour study estimate is unpiloted; record actual learner time separately.

Give the three splits different jobs. Training examples supply parameter updates and fitted preprocessing statistics. Validation examples support the predeclared model-selection rule and diagnostic analysis. The final test is opened only after the selected checkpoint, class order and preprocessing are frozen. Calling a dataset test does not protect it if its results guide repeated changes. The separate fit and test commands make the intended sequence reviewable; they are educational guards, not an access-control system preventing a learner from reading files.

Establish a baseline that requires no learned image features. Count labels in the training split and always predict its most frequent class, resolving a balanced tie with the smallest class index. All three training classes have 36 images, so the baseline predicts vertical. It gets 12 of the 36 balanced validation images correct. That is a 33.3 percent reference for this task, not a universal chance level or a useful classifier. Preserve it so that a trained model must demonstrate more than an attractive training curve.

The author tested Python 3.12.10 and the official Windows CPU wheel torch 2.14.1+cpu. The PyTorch release page identified v2.14.1 and its 2.14 API documentation was checked on 26 October 2026. The exact wheel hash and dependency versions are recorded separately. No CUDA build, GPU, torchvision, account or model API is used. Installation downloads packages, but generating data and running the exercise afterward needs no network. Other platforms or versions require their own installation and execution check. [S2] [S3]

NVIDIA publishes its separate Fundamentals of Deep Learning course, including convolution and other topics. Its repository was consulted to understand the requested learning area, not to obtain this manuscript, code, dataset, notebook or assessment. This is an original, narrower MICKAI CPU exercise. It does not reproduce the full NVIDIA programme, teach all its modules or award its credential. Keep the provenance statement with the experiment record so an educational result cannot be mistaken for NVIDIA affiliation, accreditation or professional deployment approval. [S1]

Try it yourself · Activity 01

20 min

Write the experiment contract

Before running training, write the prediction contract, baseline rule, selection rule and final-test opening condition.

  1. Name the array, labels and source-group unit.
  2. Record the fixed settings and the jobs of all three splits.
  3. State which result supports the synthetic task and which larger claim it cannot support.

Which observation would change the conclusion, and which missing evidence leaves it unresolved?

Worked answer

Predict vertical, horizontal or cross for a generated array. Train on training groups, fit statistics there, select minimum clean validation loss over 16 fixed epochs and freeze the selected state before the test command. A training-label majority tie chooses class 0, giving a 12/36 validation baseline. Neither a high score nor completing the exercise establishes real-image performance or NVIDIA certification.

Next chapter

Learn in your browser · Chapter 02 of 06

02

Split source groups and validate pixel inputs

Protect the evaluation boundary before turning lists into tensors. Correlated views and fitted preprocessing can leak information even when filenames differ.

The generator creates 30 independent synthetic base drawings for each of three classes. Each base has its own seeded pixel values and a stroke position, then produces two related noisy views. A source group identifies that base; two view IDs identify its children. Both views of a group must stay together. Different view filenames do not make them independent observations. The drawings still share a deliberately simple generator and pattern family, so disjoint groups do not turn this exercise into evidence about arbitrary real-world images.

Group numbers 0 through 17 belong to training, 18 through 23 to validation and 24 through 29 to final test, separately within each class. That gives 54 training groups and 108 images, 18 validation groups and 36 images, and 18 test groups and 36 images. The split is assigned before view noise is generated. Changing a view seed cannot repair a group appearing in two splits. The manifest-level disjointness check can run without constructing or inspecting final-test pixel arrays.

The tensor contract is N, C, H, W: batch size, channel count, height and width. A full training tensor has shape 108, 1, 8, 8 and float32 values. Integer targets have shape 108 and dtype torch.long, with values 0 through 2. The channel dimension is present even for greyscale. A tensor with dimensions 108, 8, 8 has lost that declared axis; simply having 64 numbers per image does not establish the shape consumed by the network.

Validate source data before creating a promising curve. Each image must have a unique ID, an integer label in the known class range and exactly 64 finite numeric pixels between zero and one. Reject a missing pixel, NaN or a fractional class label. Do not silently replace malformed values and retain the old experiment identity. A repair changes the input and requires a new recorded comparison. These checks protect the declared synthetic contract; they do not verify that a real image was correctly labelled or ethically obtained.

Compute one scalar mean and population standard deviation from training pixels only. The code uses unbiased=False for that standard deviation and clamps it away from zero. Apply the same stored statistics to validation and final test. Pixels already lie between zero and one; they are not byte values needing another division by 255. Fitting statistics on all splits lets evaluation inputs influence preprocessing. Refitting on a future batch also changes the model interface even when learned weights are unchanged.

Treat augmentation as a data-generation decision with a label meaning. In this lab the two small-noise views are generated after group assignment and preserve the underlying label. A ninety-degree rotation would exchange a vertical bar and a horizontal bar, so retaining their old labels would corrupt supervision. The supplied exercise does not use rotation or borrow an image augmentation library. When extending it, state which transformation preserves each label and keep derived views within the source group rather than re-splitting them as new examples.

Use group IDs, image IDs and payload digests for different questions. Group IDs expose a correlated-source overlap. Image IDs detect accidental repeated rows. A SHA-256 payload digest binds the generated records and labels that were checked. Two differently named files can still contain related or identical input, while a changed digest does not identify a changed label by itself. Preserve the generator, split rule and seed as well as the digest so another reviewer can reconstruct the precise dataset rather than merely trust its filename.

Try it yourself · Activity 02

25 min

Audit a split and preprocessing proposal

A colleague puts view 0 of every base in training and view 1 in validation, then fits one mean over both sets. Write a corrected plan before running the supplied split and normalisation tests.

  1. Count groups and images in the three declared splits.
  2. Explain both the source overlap and fitted-statistics problem.
  3. Check the training input and target shapes without evaluating test pixels.

Which observation would change the conclusion, and which missing evidence leaves it unresolved?

Worked answer

Keep both views in one source group and split groups first. Use 54/18/18 groups, giving 108/36/36 images. Fit scalar mean and population standard deviation on training only and reuse them unchanged. Inputs are float32 [108,1,8,8] and targets long [108]. Moving a training group into validation must fail the disjointness check.

Next chapter

Learn in your browser · Chapter 03 of 06

03

Build a small convolutional model and a readable metric

Trace dimensions and the loss interface. A model with only 235 learned values is large enough for the toy task and small enough to inspect.

TinyCNN begins with Conv2d from one input channel to four output channels, using a 3 by 3 kernel and padding one. With default stride one, an 8 by 8 image keeps its spatial size. The batch therefore becomes N, 4, 8, 8. A convolution applies each learned local pattern across spatial positions using shared weights. It does not automatically recognise every translation or make the data split independent. Its useful bias is local feature extraction, which must still be tested on the chosen images. [S4]

ReLU replaces negative activations with zero. Average pooling over non-overlapping 2 by 2 regions halves each spatial dimension, producing N, 4, 4, 4. Flatten preserves the batch dimension and combines those 64 feature values per image. Dropout with probability 0.1 precedes a linear layer from 64 features to three outputs. Pooling and flatten do not invent additional labels; they reshape and summarise features. A wrong flatten boundary can mix examples even if a later matrix multiplication happens to run. [S5]

Count parameters independently of the printed model. Four convolution filters each have one times three times three weights plus a bias: 4 times 10 gives 40. The final linear layer has 64 times 3 weights and 3 biases, giving 195. Total learned parameters are 235. ReLU, average pooling, flatten and dropout add no learned parameters here. A larger count or a different output shape indicates that the executable architecture differs from the workbook; resolve that mismatch before comparing results.

The three outputs are logits, one score per class, not an image and not necessarily probabilities. Feed raw logits of shape N, 3 and integer targets of shape N to CrossEntropyLoss. Do not insert a softmax before this loss in the supplied model. For zero logits and a valid one-class target the loss is log(3), approximately 1.099, because the classes have equal probability under the loss calculation. Class-index targets use torch.long; probability-target alternatives are a different interface not used here. [S6]

For a prediction, argmax over the class dimension selects the highest logit. It returns a class index interpreted using the saved order vertical, horizontal, cross. Normalising logits with softmax would not change this argmax for ordinary finite scores, but it would not make the resulting number a calibrated confidence guarantee. A prediction can be wrong with a large score gap. Preserve raw counts and record IDs for error analysis instead of describing a confident score as an independently verified label.

Mean loss and accuracy answer different questions. Accuracy counts correct predicted classes divided by evaluated images. Cross-entropy also responds to how strongly the scores favour the correct target. Two checkpoints can have equal accuracy but different mean loss. The predeclared selection rule uses clean validation loss, so do not switch to whichever metric favours a preferred epoch after seeing the curve. Report the majority baseline alongside the learned result using the same image population, label order and evaluation definition.

When aggregating batch losses, weight each mean by its batch image count, add those totals and divide by total images. If a last batch has six images while earlier batches have eighteen, averaging batch means equally gives the smaller batch disproportionate influence. The supplied loop records an image-weighted training mean across updates. Its training-time dropout and changing weights mean this number is not identical to evaluating the selected fixed checkpoint on all training images afterward. Label these two quantities separately.

Try it yourself · Activity 03

25 min

Trace the network and check one loss

For a batch of five images, write every shape from input to logits, count parameters and calculate the loss of equal zero logits.

  1. Keep the batch axis visible through pooling and flatten.
  2. Count weights and biases separately.
  3. Run shape and loss-contract tests before interpreting accuracy.

Which observation would change the conclusion, and which missing evidence leaves it unresolved?

Worked answer

Shapes are [5,1,8,8], [5,4,8,8], [5,4,4,4], [5,64] and [5,3]. The convolution has 40 parameters and the linear layer 195, total 235. Zero logits give log(3) loss for valid class-index targets. Floating class indices of shape [5] do not meet this target contract.

python · 3 lines
logits = model(images)  # [N, 3], raw scores
loss = torch.nn.functional.cross_entropy(logits, labels)
predicted_class = logits.argmax(dim=1)

Next chapter

Learn in your browser · Chapter 04 of 06

04

Train, validate and freeze a selected checkpoint

Keep parameter updates and model selection separate. Record the executable sequence instead of relying on an attractive screenshot.

The training loader uses batch size 18, shuffles training examples with a seeded generator and uses zero worker processes. One epoch visits 108 training images in six batches. Sixteen fixed epochs therefore perform 96 optimiser steps. Shuffling changes update order without moving a record into a different split. A DataLoader provides batches, not a guarantee of correct labels or independent evaluation. The explicit CPU path avoids multiprocessing setup and GPU transfer issues while you inspect the experiment. [S7]

At each training batch, use train mode, clear previous gradients with optimiser.zero_grad(set_to_none=True), run the forward pass, compute scalar loss, call backward and then optimiser.step(). The supplied code sets train mode once at the epoch start and keeps it active for its batches. Clearing gradients matters because backward otherwise accumulates them. Backward alone computes gradients without applying an update. An optimiser step before those gradients exist cannot substitute for the intended learning sequence. Check the complete order when a loss refuses to change.

After an epoch, validation calls model.eval() and enters torch.inference_mode(). These solve different problems. Evaluation mode changes layers such as dropout; inference mode disables autograd work for that evaluation. Inference mode does not itself switch dropout off. The evaluator performs no backward pass or optimiser step, so validation examples do not train weights. Returning to training requires train mode again. Keeping these transitions explicit prevents a validation function from silently changing the next epoch into the wrong phase. [S8] [S9]

Select the checkpoint with the lowest clean validation loss, not the final loop iteration by habit. Copy its state dictionary with copy.deepcopy when it improves. A live reference to model.state_dict() may continue reflecting later updates instead of preserving earlier best parameters. On an exact loss tie, the strict less-than comparison keeps the earliest checkpoint. The selected epoch is an observation of this run. Record it with the full history rather than treating it as a universal number of epochs for this architecture.

The seed controls model initialisation and loader order, while each synthetic drawing has its own deterministic generation seed. The author also used one CPU thread and deterministic algorithms. PyTorch warns that complete reproducibility is not guaranteed across releases, devices and platforms. Record Python and torch versions, CPU execution, data hashes and settings. If environments disagree, investigate changed inputs or environment before discarding a record. A seed is a useful control; it is not proof that every future machine will produce identical floating-point bytes. [S10]

The author run on 26 October 2026 selected epoch 15 from the fixed 16-epoch schedule. Initial training loss was approximately 1.151; evaluating the selected state on training gave approximately 0.0000182. Clean validation classified 36 of 36 correctly. These are measured results for the supplied seeds and simple patterns, not promised learner outputs or real-image quality evidence. Logs preserve the full curve. In particular, the selected epoch does not imply that epochs after 15 should be removed from every future experiment.

The fit command writes selection.json and selected-state.pt into a fresh run directory. Metadata records preprocessing, label order, architecture input shape, selection rule, data hashes and checkpoint hash, and explicitly records zero test evaluations. Repeating fit into that directory is refused to preserve earlier evidence. A unit test replaces the test-record constructor with a failure during fitting, demonstrating that this implementation finishes training and selection without generating test pixels. That strengthens the protocol claim without evaluating final-test performance or relying on an author statement alone.

Try it yourself · Activity 04

30 min

Reconstruct and challenge the training record

Run unit tests and fit in a fresh directory. Identify the selected checkpoint and explain why training and validation observations have different roles.

  1. Predict the optimiser-step count before running.
  2. Find the minimum validation-loss epoch and compare it with saved selection.
  3. Explain eval mode, inference mode and a copied checkpoint separately.

Which observation would change the conclusion, and which missing evidence leaves it unresolved?

Worked answer

There are six batches per epoch and 96 updates. Select minimum clean validation loss with earliest exact ties; the author selected 15, but read your own history. Training updates weights; validation evaluates and chooses among candidates. eval changes dropout behaviour, inference_mode disables gradient recording, and deep-copying preserves selected parameters without later aliasing.

python · 6 lines
model.train()
optimiser.zero_grad(set_to_none=True)
loss = criterion(model(images), labels)
loss.backward()
optimiser.step()
# Validation uses eval and inference_mode, without an update.

Next chapter

Learn in your browser · Chapter 05 of 06

05

Use errors and corruption to challenge the result

An easy clean split can conceal a brittle task. Diagnose inputs and model separately before changing the experiment.

A confusion matrix has true labels in rows and predicted labels in columns here. Its entries count images, so all nine cells sum to the evaluated population. A row sum is the number of examples of that true class. The diagonal counts correct predictions. If a horizontal row contains eight horizontal predictions and four cross predictions, horizontal recall is eight divided by twelve, not eight divided by all 36 images. Write the axis convention next to the matrix; a transposed table can otherwise support a wrong narrative.

Overall accuracy can conceal which class fails, especially after introducing class imbalance. Compare each true-class row, its errors and actual image IDs instead of declaring the task solved from one average. The validation set is balanced and very small. Even 36/36 leaves uncertainty about other generator settings, unseen failure types and real inputs. Two views within a group are correlated, so treating 36 images as 36 unrelated real-world acquisitions would exaggerate the diversity of this evidence. A larger numeral is not a substitute for an independent data source.

The stress condition was declared before final testing: replace every validation pixel with zero while retaining labels. It deliberately removes the class signal. The author model then classified 12/36 correctly, while clean validation remained 36/36. This contrast demonstrates dependence on visible pattern information and a severe out-of-distribution input. It does not measure camera-noise robustness or establish that an all-black real image should have one of these labels. A real interface might need an invalid-input or abstention policy that this three-class lab does not implement.

Inspect mistakes with source IDs, true label, prediction and input condition. Errors under blank stress are not evidence that original labels should change to the predicted class. A model output is a hypothesis, not label authority. For a malformed example, fix the data contract and create a new version. For systematic confusion on valid examples, formulate a training or architecture hypothesis and test it using training and validation. Do not quietly repair evaluation labels until the metric improves; preserve the original finding and the reason for any authorised correction.

Tests challenge meaningful failure modes. Moving one source group into validation must fail disjointness. A NaN, missing pixel or out-of-range class must fail input validation. Evaluation must leave weights unchanged and give stable predictions with dropout disabled. Reloading selected state must reproduce its clean validation predictions. Training must change a parameter and lower the recorded training loss in this fixed toy experiment. These checks exercise intended contracts rather than merely checking that a script exits successfully, and their expected rejections should be kept in the evidence record.

Keep dataset corruption, implementation defects and limited generalisation separate in the failure log. A fractional target is a data-contract defect. Crediting a validation update to training is a phase defect. Poor performance on a valid shifted pattern is a model limitation or distribution question. These categories imply different next actions and evidence. Reinstalling a package cannot establish a correct label, and increasing epochs cannot repair a source group leaked across splits. Start with the earliest violated contract before tuning a parameter simply because it is easy to change.

Validation has now informed diagnosis, so it is a development resource rather than a final independent verdict. Record the hypotheses considered, including changes you decide against. If a final-test result selects another architecture, that set becomes development evidence for the revised experiment. A later final claim needs new appropriately separated data or a clearly disclosed reuse protocol. A new output directory preserves files; it does not make previously inspected examples scientifically untouched again. Preserve that distinction even when every command is technically reproducible.

Try it yourself · Activity 05

30 min

Read a confusion matrix and investigate a failure

Use clean and blank validation reports. Explain the axes, list two error IDs and propose an evidence-led next action without opening the final test.

  1. Check each matrix sums to 36.
  2. Distinguish removed-signal stress from a corrupted target contract.
  3. Run leakage and malformed-input tests and record expected rejection.

Which observation would change the conclusion, and which missing evidence leaves it unresolved?

Worked answer

Clean validation has 36 correct and blank validation 12 in the saved author run. Rows are true classes and columns predictions. Two blank-validation error IDs in the saved run are c1-g18-v0 and c1-g18-v1: both have true class horizontal (1) and predicted class vertical (0). They are correlated views from one source group, not two independent real-world cases. Retain blank-input errors rather than relabelling them. A next experiment may change a validation stress or training-only transformation with an explicit label rule, but remains development evidence. Keep final testing closed until the revised decision rule is frozen.

Next chapter

Learn in your browser · Chapter 06 of 06

06

Open the final test and hand over a bounded result

Bind the tested state, preserve the result and state what this small CPU experiment leaves out.

Before the test command, freeze selected checkpoint, preprocessing statistics, class order, input shape and selection metadata. The final command checks the checkpoint digest against selection.json, loads selected state and only then generates the 36 test images from separate source groups. It writes FINAL-RESULTS.json and refuses to evaluate into that run directory again. This makes accidental repeated testing visible. It does not stop deliberate copying or changing the program; honest experiment records still matter. A frozen decision is a research protocol, not merely a file extension.

Reconstruct the same TinyCNN class before loading its state dictionary. Use CPU map_location and weights_only=True for this locally produced file, then enter eval and inference mode. A state dictionary contains learned tensors, not every detail needed to interpret inputs. Keep architecture source, preprocessing and label mapping beside it. PyTorch documents restrictions and residual risks of weights-only loading; the lab loads its own checkpoint, not an arbitrary unknown file. A matching hash checks a version, not general safety or the truth of a result. [S11]

The author final test, performed after selection, classified 36 of 36 correctly; the training-derived majority baseline classified 12 of 36. Clean validation was also 36 of 36, while the predeclared blank validation condition had 12 correct. Report these populations and conditions separately. Do not average clean and blank scores into a new headline or say a perfect test proves broad visual understanding. This result belongs to the selected checkpoint and exact generator, split and package versions recorded in the evidence, not every future revision of the code.

A handover names the task and class order, source-group split, generated-data hashes, training settings, selected epoch and rule, checkpoint digest, clean validation diagnostics, final-test counts and known exclusions. Preserve failed checks and expected mutation rejections alongside successes. Another reviewer should identify which model produced which result without relying on the author remembering a filename. Keep the private final knowledge-assessment bank outside the learner ZIP. Learner practice answers are separate educational material and must not become a route for publishing scored exam items.

CPU execution makes the full experiment small enough for an ordinary development machine. It does not estimate GPU throughput, large-image memory, deployment latency or energy requirements. This task has three generated patterns and 235 parameters; there is no camera acquisition, real image licensing, distribution monitoring, production service or user study. An extension to real images needs new data provenance, labels, group definitions, evaluation and operational work. Replacing a filename without reconsidering those assumptions does not transfer the evidence from a synthetic pattern task to a real visual application.

Convolutional training and testing are the outcome here. Transfer learning, pretrained image backbones, object detection, segmentation and transformer training are possible later studies, not completed competencies implied by this exercise. Reuse the tensor course for foundations and attention or tiny-language-model courses for their distinct architectures. NVIDIA offers its own broader material independently. This MICKAI course and any educational completion certificate do not provide NVIDIA credentials, professional qualification, learner identity verification or permission to deploy. Describe the specific demonstrated learning activity rather than borrowing authority from a neighbouring programme.

The knowledge assessment has 40 private multiple-choice items and draws a 20-question sitting. Strictly above 80 percent requires 17 correct; 16 does not pass. The six written exercises and executable practical work are ungraded. A knowledge score does not verify that a learner ran this loop or can operate a real vision system. A different reviewer must inspect teaching, every key and explanation, the learner package and rendering before publication. Actual author execution is evidence, not self-approval, and local files do not establish current course, exam or certificate availability.

Try it yourself · Activity 06

30 min

Freeze, test and write the handover

After your validation decisions, run the final test once for the frozen experiment and write a handover another reviewer can reproduce.

  1. Check selected checkpoint and metadata hashes before testing.
  2. Record baseline, clean validation, blank stress and final-test counts.
  3. State which changes require a new evaluation claim and what the certificate cannot establish.

Which observation would change the conclusion, and which missing evidence leaves it unresolved?

Worked answer

For the saved author experiment, epoch 15 was selected from 16 fixed epochs. Clean validation and final test were each 36/36; the majority baseline and blank validation stress were each 12/36 on their stated populations. Record actual checkpoint and payload hashes, not shortened examples. Preserve CPU and synthetic-data limits. Different-author review, real-image evaluation and publication checks are separate responsibilities.

python · 6 lines
model = TinyCNN().cpu()
state = torch.load(path, map_location="cpu", weights_only=True)
model.load_state_dict(state)
model.eval()
with torch.inference_mode():
    logits = model(normalised_images)

Assessment options

Keep learning

The complete workbook

Build and test a 235-parameter PyTorch convolutional classifier using original generated pixel arrays. Trace shapes, protect related views from split leakage, preserve a majority baseline and challenge clean accuracy with error analysis and a declared corruption. Six worked exercises are ungraded; the final exam assesses knowledge only.

  1. 01
    Define an image experiment before training

    Choose the prediction, independence unit and evidence you will preserve. A tiny image task can teach a complete experiment without representing a real camera system.

    Read here · 1 exercise
  2. 02
    Split source groups and validate pixel inputs

    Protect the evaluation boundary before turning lists into tensors. Correlated views and fitted preprocessing can leak information even when filenames differ.

    Read here · 1 exercise
  3. 03
    Build a small convolutional model and a readable metric

    Trace dimensions and the loss interface. A model with only 235 learned values is large enough for the toy task and small enough to inspect.

    Read here · 1 exercise
  4. 04
    Train, validate and freeze a selected checkpoint

    Keep parameter updates and model selection separate. Record the executable sequence instead of relying on an attractive screenshot.

    Read here · 1 exercise
  5. 05
    Use errors and corruption to challenge the result

    An easy clean split can conceal a brittle task. Diagnose inputs and model separately before changing the experiment.

    Read here · 1 exercise
  6. 06
    Open the final test and hand over a bounded result

    Bind the tested state, preserve the result and state what this small CPU experiment leaves out.

    Read here · 1 exercise

Also inside: a 8-point checklist, a glossary of 12 terms and 10 questions and answers to test yourself. 6 hands-on exercises, each with a worked answer at the back where the workbook gives one.

The PDF is free. We ask for your name and email before downloading. Read the privacy notice at the download form. Free to download and use for personal learning, study groups and inside your own team. Please do not resell the workbooks or republish them as your own. Link people to trust-agent.ai instead.

Get your free PDF workbook

Enter your name and email, then download the complete workbook. This form also works without JavaScript.

We privately record your name, email and request IP for this download. Read our privacy notice and retention policy.

Visit Mickai on LinkedIn

Newsletter confirmation does not affect your download. Following Mickai on LinkedIn is optional; this site does not verify followers.

Test yourself

Questions and answers

Why not randomly split the two views?

They share a generated source drawing. Keep both children in one group and split groups before making views.

Why keep a final test if validation exists?

Validation helps select and diagnose the model. The final split assesses the frozen decision without becoming another tuning signal.

Do greyscale images need a channel axis?

Yes. This model expects N,1,8,8 inputs, with an explicit channel dimension.

Should I softmax before CrossEntropyLoss?

No. Supply raw logits and long class-index targets to that loss in this exercise.

Does inference_mode turn off dropout?

No. Call model.eval() as well; the two operations control different behaviour.

Why did blank images still get 12 correct?

Balanced labels remain, and predicting one class can match 12 of 36 without recovering the erased pattern signal.

Can I change epochs after seeing final-test results?

You can run a new development experiment, but the inspected set no longer supports an untouched final-evaluation claim for that revised choice.

Are author counts guaranteed on my machine?

No. Preserve actual versions, settings and results; cross-platform or cross-release bitwise reproducibility is not guaranteed.

Is a checkpoint enough to reproduce predictions?

No. Retain architecture, training-fitted preprocessing, input shape and class order with selected state.

Does passing provide an NVIDIA certificate?

No. MICKAI educational completion is distinct from NVIDIA credentials, professional competence and verified practical execution.

Write as you go

My notes

Use this scratchpad for your own notes, working or answers as you read. Notes are saved in this browser on this device. Downloading makes a local copy; it does not send your notes to Mickai.

Learn → Practise → Demonstrate

Ready to put it into practice?

Take the scored exam when you feel ready. You do not need to download the workbook first. A score strictly above 80% earns a named, dated Mickai certificate with a verification page.

Take the official exam

Your name and email are collected at exam start. Certificates record an assessment result, not an accredited qualification or verified identity.

Learn the language

Key terms

Source group
One generated base drawing and its two related views.
Logit
An unnormalised class score supplied to the classification loss.
Convolution
A learned local operation whose weights are shared across spatial positions.
Validation
Development evaluation used by the declared selection and diagnostic process.
Final test
Separate source groups evaluated after the experiment decision is frozen.
Data leakage
Information crossing a declared development/evaluation boundary.

6 of the workbook's 12 terms. The complete glossary is in the workbook.

Follow the evidence

Sources and checks

Facts last checked: .

Examples in this workbook were run on: Windows, Python 3.12.10, torch 2.14.1+cpu; original synthetic data, 12 unit tests and separate fit/final-test commands executed. (2026-10-26).

These workbooks use AI assistance. See how the workbooks are made.

  1. NVIDIA DLI Fundamentals repository, curriculum context only, checked 26 October 2026NVIDIA DLI
  2. PyTorch v2.14.1 release, checked 26 October 2026PyTorch
  3. Official CPU wheel index, checked 26 October 2026PyTorch
  4. Conv2d, PyTorch 2.14, checked 26 October 2026PyTorch
  5. AvgPool2d, PyTorch 2.14, checked 26 October 2026PyTorch
  6. CrossEntropyLoss, PyTorch 2.14, checked 26 October 2026PyTorch
  7. Data utilities, PyTorch 2.14, checked 26 October 2026PyTorch
  8. Module evaluation mode, PyTorch 2.14, checked 26 October 2026PyTorch
  9. Inference mode, PyTorch 2.14, checked 26 October 2026PyTorch
  10. Reproducibility, PyTorch 2.14, checked 26 October 2026PyTorch
  11. Save and load a model, PyTorch tutorial, checked 26 October 2026PyTorch

Created by Micky Irons with the Mickai team. Published by Mickai LTD. Last updated 26 October 2026.

NextKeep going

Where to go next