liveBook · Manning

Chapter 13: Training a classification model to detect suspected tumors

What you will learn in chapter 13 of Deep Learning with PyTorch, Second Edition

The chapter introduction connects the previously prepared CT-scan dataset to the upcoming work of loading data, training a classifier, and tracking its performance.

After this chapter you will be able to

What it builds on

Section by section

Introduction

The chapter introduction connects the previously prepared CT-scan dataset to the upcoming work of loading data, training a classifier, and tracking its performance.

13.1 A foundational model and training loop

This section defines the nodule-classification task and outlines a training-and-validation loop that will provide an evaluable foundation for the larger project.

Key terms: candidate, nodule, non-nodule, classification, epoch, batch, loss, backpropagation, training, validation

13.2 The main entry point for our application

The section structures training as a command-line application that can also be instantiated and run directly from Python or Jupyter.

Key terms: command-line application, application class, Jupyter Notebook, native CLI, if main stanza, argparse, __init__, main

13.3 Pretraining setup and initialization

The section identifies what must be initialized before a training epoch can process batches and explains the roles of LunaDataset and DataLoader.

Key terms: model, optimizer, LunaDataset, DataLoader, training epoch

13.3.1 Initializing the model and optimizer

Explains how the training application sets up GPU use and chooses an initial optimizer without tuning the model yet.

Key terms: nn.DataParallel, DistributedDataParallel, self.model.to(device), model parameters, optimizer, GPU, stochastic gradient descent, SGD, momentum, learning rate

13.3.2 Care and feeding of data loaders

This section explains how LunaDataset samples become batched, five-dimensional inputs for a 3D convolutional model, and how DataLoader workers can keep training supplied with data.

Key terms: LunaDataset, torch.nn.Conv3d, channel, batch, (N, C, D, H, W), ct_t.unsqueeze(0), DataLoader, sample tuples, batch tuple, collation

13.4 Our first-pass neural network design

The section motivates a pragmatic first-pass 3D classification network based on established image-recognition designs.

Key terms: 2D images, 3D, first network architecture

13.4.1 The core convolutions

This section explains the tail–backbone–head structure of the classifier and how its repeated convolutional blocks process 3D CT data.

Key terms: tail, backbone, head, LunaBlock, convolutions, activation, max-pooling, receptive field, 3 × 3 × 3 convolution, 5 × 5 × 5 convolution

13.4.2 The full model

This section completes the LunaModel by explaining its input normalization, four-block backbone, transition to a classification head, two output forms, and weight initialization.

Key terms: nn.BatchNorm3d, Hounsfield unit (HU), backbone, 2 × 2 × 2 max-pool, self.block4, fully connected layer, view, flatten, forward, logits

13.5 Training and validating the model

This section shows how the training loop assembles the model and data-loading pieces, while tracking sample-level metrics and organizing batch processing.

Key terms: trnMetrics_g, computeBatchLoss, logMetrics, per-class metrics, tqdm, train_dl

13.5.1 The computeBatchLoss function

Explains how computeBatchLoss returns a batch loss for training while retaining per-sample results for evaluating and debugging the classifier.

Key terms: computeBatchLoss, CrossEntropyLoss, per-sample losses, batch loss, metrics_g, label, prediction, loss, per-class statistics

13.5.2 The validation loop is similar

Explains how validation reuses the batch-loss calculation while leaving the model unchanged and collecting metrics.

Key terms: validation, torch.no_grad(), optimizer, weights, computeBatchLoss, valMetrics_g, per-batch loss

13.6 Outputting performance metrics

This section explains what the training script logs after each epoch, where the results come from, and why monitoring them matters.

Key terms: performance metrics, does not converge, epoch, trnMetrics_g, valMetrics_g, percent correct, average loss per class

13.6.1 The logMetrics function

The section explains how logMetrics uses per-sample tensors and binary masks to calculate and log overall and per-class training or validation results.

Key terms: logMetrics, metrics_t, mode_str, epoch_ndx, classificationThreshold, negLabel_mask, negPred_mask, positive masks, negative masks, metrics_dict

13.7 Running the training script

This section starts the training workflow and shows how to recognize cache preparation delays and check whether the GPU is being kept busy.

Key terms: main code directory, requirements.txt, LunaDataset, prepcache.py, dsets.py, cache, top, nvidia-smi, GPU-Util, CPU bottlenecks

13.7.1 Data needed for training

This subsection shows how to check that the expected training and validation data and underlying LUNA files are present before troubleshooting training.

Key terms: samples, training, validation, series UID, .mhd file, .raw file, data-unversioned/part2/luna

13.7.2 Interlude: The tqdm function

This section introduces tqdm as a way to track progress and estimate completion time during long-running deep learning loops.

Key terms: tqdm, progress bar, time remaining, iterations per second

13.8 Evaluating the model: Getting 99.7% correct means we’re done, right?

The section shows why 99.7% accuracy is misleading when the classifier misses every nodule, and why that error matters.

Key terms: validation set, non-nodules, nodules, not-a-nodule, val_pos loss, val_neg loss, positive samples, misclassification, tumor, innocuous structure

13.9 Graphing training metrics with TensorBoard

The section explains why graphing training metrics in TensorBoard is useful and why it can be used with PyTorch.

Key terms: TensorBoard, training metrics, trends, outlier, TensorFlow, PyTorch APIs

13.9.1 Running TensorBoard

This section shows how to launch TensorBoard, inspect training and validation metrics, and manage which runs appear in its graphs.

Key terms: TensorBoard, runs/, --logdir, localhost:6006, Scalars, training and validation metrics, Value column, tooltip, smoothing, runs

13.9.2 Adding TensorBoard support to the metrics logging function

The section adds TensorBoard logging to the metrics function, explains how scalar metrics become charts, and chooses training samples rather than epochs for the chart’s X-axis.

Key terms: SummaryWriter, log_dir, training run, validation run, metrics_dict, add_scalar, tag, scalar_value, global_step, totalTrainingSamples_count

13.10 Why isn’t the model learning to detect nodules?

The section explains why the classifier can show high accuracy and decreasing loss without learning to detect nodules.

Key terms: nodule, loss, training and validation sets

13.11 Conclusion

The conclusion summarizes the working classification training pipeline and notes that its results are not yet usable.

Key terms: model, training loop, metrics

13.12 Exercises

13.13 Summary

Where this is used later

Concepts explained in this chapter

← Chapter 12: Combining data sources into a unified dataset Chapter 14: Improving training with metrics and augmentation →

These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.