smartyfy.mrindigi.com

Python Master Course V2 — 143. Datasets, Batching and Reliable Training Loops

Purpose and learning outcomes

A reliable training loop is a small accounting system: it must pair each input with the correct target, update only during training, and aggregate losses using the right number of examples. We will train a compact multilayer perceptron on bundled wine measurements and use a separate one-batch diagnostic to verify that the optimization loop can learn at all.

  • Create TensorDataset and DataLoader inputs
  • Implement explicit training and validation phases
  • Aggregate batch losses correctly and check tensor contracts

Prerequisites: 113: classes primer; 142: PyTorch autograd; 131: data splits.

Environment and run order

Use the isolated Python 3.11 or 3.12 environment from lesson 142. All tensors and models below run on the CPU. No pretrained weights or external datasets are downloaded. For first-time setup install the numerical packages, then use the official PyTorch installer selector for your operating system. The CPU wheel command below is for Linux or Windows; macOS uses python -m pip install torch. Run Python blocks sequentially in a single file.

Shell

python -m pip install numpy pandas scikit-learn matplotlib
# Linux/Windows CPU installation:
python -m pip install torch --index-url https://download.pytorch.org/whl/cpu
python -m pip freeze > requirements-observed.txt

Understand the model and the evidence

Datasets describe examples, loaders describe batches

TensorDataset holds matching tensors and returns aligned input-target pairs by index. DataLoader groups these examples into minibatches and can shuffle their order. Shuffling training examples changes stochastic updates without changing partition membership. Validation should retain a stable ordering for easier diagnostics. num_workers=0 keeps this small script simple across operating systems and avoids subprocess setup complications.

Logits and targets have distinct contracts

For three classes, a network returns logits with shape (batch,3). CrossEntropyLoss expects raw logits and integer class indices with shape (batch,), using torch.long. It performs the required log-softmax internally. Applying softmax first is unnecessary and changes the intended loss calculation. The hidden layer uses ReLU to introduce nonlinearity; Linear maps the final hidden representation to one logit per class.

Separate modes and gradient contexts

model.train enables training behavior for modules that need it; model.eval enables evaluation behavior. torch.no_grad additionally avoids recording evaluation graphs. Only the training phase clears gradients, calls backward, and steps the optimizer. A validation loss accidentally followed by backward and step would make validation data part of training, destroying its role in model selection.

Aggregate by examples, not by batches

A batch loss computed with mean reduction averages over that batch. If the final batch is smaller, averaging batch means gives its examples excessive weight. Multiply each mean by the batch size, sum, and divide by the total example count. Training loss is measured while parameters change between batches, whereas validation loss is measured with one fixed epoch-end model; this can explain small apparent inconsistencies.

Incremental worked example

1. Prepare training-fitted scaling and paired tensors

The test partition is reserved for a later final decision and remains unused here. The scaler learns only training statistics. We convert floating inputs to float32 and integer labels to long, then create loaders with a separately seeded shuffle generator.

Python

import copy
import numpy as np
import torch
from torch import nn
from torch.utils.data import TensorDataset, DataLoader
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

torch.set_num_threads(1)
torch.manual_seed(43)
X, y = load_wine(return_X_y=True)
Xd, Xt, yd, yt = train_test_split(X, y, test_size=0.2, stratify=y, random_state=43)
Xr, Xv, yr, yv = train_test_split(Xd, yd, test_size=0.25, stratify=yd, random_state=44)
scale = StandardScaler().fit(Xr)
def dataset(A, target):
    return TensorDataset(torch.tensor(scale.transform(A), dtype=torch.float32),
                         torch.tensor(target, dtype=torch.long))
train_data, valid_data = dataset(Xr, yr), dataset(Xv, yv)
shuffle_rng = torch.Generator().manual_seed(43)
train_loader = DataLoader(train_data, batch_size=24, shuffle=True,
                          generator=shuffle_rng, num_workers=0)
valid_loader = DataLoader(valid_data, batch_size=24, shuffle=False, num_workers=0)
model = nn.Sequential(nn.Linear(13, 20), nn.ReLU(), nn.Linear(20, 3))
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)

2. Train and evaluate with correct loss accounting

The run_epoch function changes behavior based on whether an optimizer is provided. set_grad_enabled records training graphs only. Accuracy counts correct predictions, and the loss total weights every row equally. The fixed 40-epoch budget is declared before inspecting validation.

Python

def run_epoch(net, loader, opt=None):
    training = opt is not None
    net.train(training)
    total_loss, correct, count = 0.0, 0, 0
    with torch.set_grad_enabled(training):
        for inputs, targets in loader:
            assert inputs.ndim == 2 and targets.ndim == 1
            logits = net(inputs)
            assert logits.shape == (len(inputs), 3)
            loss = loss_fn(logits, targets)
            if training:
                opt.zero_grad(set_to_none=True)
                loss.backward()
                opt.step()
            total_loss += loss.item() * len(inputs)
            correct += (logits.argmax(dim=1) == targets).sum().item()
            count += len(inputs)
    return total_loss / count, correct / count

for epoch in range(40):
    train_metrics = run_epoch(model, train_loader, optimizer)
    valid_metrics = run_epoch(model, valid_loader)
    if epoch % 10 == 0:
        print(epoch, "train loss/accuracy", train_metrics,
              "validation loss/accuracy", valid_metrics)

3. Run a diagnostic on a separate model

A copied model and new optimizer isolate the one-batch check from the main experiment. The diagnostic deliberately overfits training examples to test basic learning mechanics; its score is not a generalization claim.

Python

diagnostic = copy.deepcopy(model)
diag_opt = torch.optim.Adam(diagnostic.parameters(), lr=0.02)
xb, yb = train_data.tensors[0][:12], train_data.tensors[1][:12]
diagnostic.train()
for _ in range(100):
    diag_opt.zero_grad(set_to_none=True)
    diag_loss = loss_fn(diagnostic(xb), yb)
    diag_loss.backward()
    diag_opt.step()
print("one-batch diagnostic loss", diag_loss.item())

Expected output / interpretation

Four epoch summaries and one diagnostic loss are printed.
Expected tensor contracts: inputs (batch,13), logits (batch,3), targets (batch,).
Loss reduction and accuracy are empirical; no exact convergence score is promised.

Guided lab and acceptance criteria

  1. Trace one batch through the loader, hidden layer, output layer, and loss. Record shapes and dtypes. Deliberately cast labels to float in a separate diagnostic and read the resulting error before restoring long labels.
  2. Use a batch size that does not divide the training count. Compare a naive average of batch means with the sample-weighted formula on a fixed evaluation pass to demonstrate why final-batch size matters.
  3. Run the separate one-batch diagnostic from a freshly initialized small model as an extension. If it fails to reduce loss, inspect label alignment, parameter updates, and learning rate before adding more layers.
  4. Deliver the loop, a learning-curve plot, tensor contracts, and a short explanation of why the test set remains unopened. Acceptance requires that validation never calls optimizer.step and that each epoch’s loss accounts for the number of examples actually processed.

Common mistakes and repairs

  • Applying softmax before CrossEntropyLoss: pass raw logits because the loss includes the required normalization.
  • Calling model.eval but forgetting to disable gradient recording: evaluation mode changes selected module behavior, while no_grad or set_grad_enabled controls autograd.
  • Averaging batch means equally when batch sizes differ: weight each mean by its example count.

Questions that test understanding

Why are class labels long tensors?

CrossEntropyLoss with class-index targets uses integer indices to select the correct class logit. Floating targets follow a different possible contract and must not be substituted casually. Explicit long labels and a one-dimensional target shape make the intended classification objective unambiguous.

Does shuffling the training loader leak data?

No, provided the dataset already contains only training rows. It changes order within a partition. Shuffling before a temporal split or mixing validation examples into the training dataset is a different issue and can invalidate the evaluation.

Why can validation loss be below training loss?

Training loss is accumulated while parameters change, so early batches use a less-trained model. Dropout or augmentation can also make training harder than evaluation. This pattern is not automatically a bug; inspect the mode, transformations, and timing before interpreting it.

What does a successful one-batch overfit prove?

It supports that the model, labels, loss, gradients, and optimizer can cooperate on a tiny training subset. It does not establish good generalization or an honest split. Treat it as an implementation diagnostic, not a replacement for held-out evaluation.

Why use a separate diagnostic model?

Deliberately optimizing on a tiny subset changes parameters toward memorization. Reusing those parameters in the main experiment would alter its training procedure and confuse the evidence. A copied or freshly initialized diagnostic object keeps that intervention isolated and auditable.

Why not evaluate test every epoch?

Repeated test scores tempt epoch selection and architecture changes based on supposedly final evidence. Validation exists for those decisions. Keep test closed until the training budget, checkpoint rule, and model choices are fixed, then report one final result.

Exercises with worked solutions

Exercise 1: Check row alignment

Reveal the worked solution and reasoning

TensorDataset requires matching first dimensions, but semantic pairing still depends on constructing tensors from the same row selection. A direct check against the source labels verifies this small pipeline’s conversion rather than assuming matching lengths imply correct pairing.

Python

assert len(train_data) == len(yr)
assert np.array_equal(train_data.tensors[1].numpy(), yr)
assert len(valid_data) == len(yv)
print("dataset lengths and labels checked")

Exercise 2: Explain the final-batch weighting error

Reveal the worked solution and reasoning

If batch means are 1.0 for 24 rows and 3.0 for 6 rows, their naive mean is 2.0. The sample mean is (24*1+6*3)/30=1.4. The smaller batch must not receive the same aggregate influence as four times as many observations.

Python

correct_mean = (24 * 1.0 + 6 * 3.0) / 30
assert abs(correct_mean - 1.4) < 1e-12
print(correct_mean)

Recap and next step

A trustworthy loop preserves row pairing, explicit tensor contracts, phase separation, and correct metric accounting. These mechanics matter more than adding layers. Next we use the same controlled loop to compare optimization and regularization choices while separating genuine experimental changes from accidental differences in initialization or data order.

Official references

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.