Author: Ángel Fernández Caravaca
Date: March 16, 2026
Building models with nn.Module
nn.Module is the cornerstone of any neural network in PyTorch. Every model, from a single linear layer to a transformer, must inherit from it.
The minimum contract requires two things: defining the trainable components in __init__ and describing the forward computation in forward().
| class MyModel(nn.Module):
def __init__(self):
super().__init__()
self.layer = nn.Linear(in_features, out_features)
def forward(self, x):
return self.layer(x)
|
When you call model(x), PyTorch routes the call to forward() automatically and, behind the scenes, also takes care of gradient hooks, device placement and parameter registration.
Linear regression is the simplest possible model: a single nn.Linear(1, 1) layer that learns two parameters, a weight w and a bias b, to fit ŷ = wx + b. The training loop follows a four-step cycle:
- Forward: compute the predictions
- Loss computation: measure the error (e.g. MSE)
- Backward: compute the gradients with
loss.backward()
- Parameter update: apply
optimizer.zero_grad() and then optimizer.step().
Activation functions
Activation functions introduce non-linearity into the network, which lets it learn complex relationships beyond simple linear transformations. Without them, stacking several layers would be mathematically equivalent to a single linear layer. Some examples:
| Activation |
Formula |
Key properties |
| ReLU |
max(0, x) |
Simple and fast; suffers from the dying ReLU problem with negative inputs |
| Tanh |
(eˣ − e⁻ˣ) / (eˣ + e⁻ˣ) |
Zero-centred output (−1, 1); the gradient can vanish with large inputs |
| GELU |
x · Φ(x) |
Smooth, with a probabilistic gate; the preferred one in Transformers |
| LeakyReLU |
max(αx, x) |
Fixes dying ReLUs by allowing small negative gradients |
Decision boundaries
In classification problems, decision boundaries are the areas of the feature space where the class predicted by the model changes. They represent the limits the model has set to distinguish between classes.
Visualising them through a meshgrid of predictions shows how well the MLP has split the input space into class regions.
Inspecting the model's parameters
PyTorch automatically registers every nn.Parameter object (and the parameters of submodules). Two key APIs:
model.named_parameters(): iterates over (name, tensor) pairs of all the trainable parameters
model.parameters(): the same, but without names; useful for passing them to an optimiser
The total number of parameters is:
| total = sum(p.numel() for p in model.parameters() if p.requires_grad)
|
Visualising the weight matrices as heatmaps (e.g. with matplotlib.imshow) can reveal patterns such as structured sparsity or poor initialisation: information the raw numbers don't give you on their own.
Saving and loading models
PyTorch separates the model architecture (Python code) from the learnt weights (a state_dict, that is, an ordered dictionary of parameter tensors).
| # Save
torch.save(model.state_dict(), 'model.pth')
# Load into a new instance of the same architecture
model2 = MyModel()
model2.load_state_dict(torch.load('model.pth'))
model2.eval()
|
This design is intentional: weights are light and portable, and the architecture is defined in code and can be versioned separately. Using torch.allclose() to check that two models produce identical outputs after loading confirms there has been no numerical drift.
- Note: always use
.pth to save the model.
Custom layers and trainable parameters
Besides the built-in layers, PyTorch lets you define completely new operations that take part in gradient computation. Any tensor wrapped in nn.Parameter:
- Is registered as a model parameter (visible with
.parameters())
- Is included in the optimiser's updates
- Is tracked by autograd
Residual connections (ResNets)
A residual block introduces a skip connection that adds the block's input directly to its output:
where F(x) is a sequence of linear layers and activations. This seemingly small change solves two critical problems of deep networks:
Vanishing gradients: during backpropagation, gradients have to pass through every layer. In deep networks, repeated multiplication by small numbers makes the gradient shrink exponentially. Skip connections provide a clear highway for the gradient straight to the first layers.
Degradation problem: empirically, adding more layers to a plain network can worsen performance, even on the training data. With residual connections, deeper networks can always fall back on the identity function (F(x) ≈ 0), which guarantees that adding depth never makes things worse.
The key idea is that learning a residual F(x) = H(x) − x is easier than learning the full transformation H(x) from scratch, especially when the optimal function is close to the identity.
Weight initialisation
How the parameters are initialised before training has a profound influence on whether a network learns and how fast it does so. Poor initialisation causes two classic failure modes:
- Symmetry-breaking problem (all zeros): if all the weights are initialised to zero, every neuron in a layer computes the same function, receives the same gradient and is updated the same way, which in practice reduces the layer to a single neuron. The network can't break this symmetry with gradient descent alone.
There are different ways to initialise the weights. For example:
- Xavier (Glorot) initialisation: designed for saturating activations such as Tanh and Sigmoid. It scales the weights so that the variance of the activations and of the gradients is preserved from one layer to the next:
\[
W \approx \text{Uniform}(−\sqrt{\frac{6}{(n_{in} + n_{out})}}, \sqrt{\frac{6}{(n_{in} + n_{out})}})
\]
The goal is to prevent activations from vanishing (too small) or exploding (too large) as the signal moves forwards and the gradient backwards.
- Kaiming (He) initialisation: designed specifically for ReLU-family activations, which discard roughly half of the activations (the negative half). Xavier's variance calculation assumes a symmetric, linear activation, so it underestimates the effective fan-in with ReLU. Kaiming corrects this:
\[
W \approx \text{Normal}(0, \sqrt{\frac{2}{n_{in}}})
\]
The factor of 2 compensates for ReLU's halving effect.
Tip
A rule of thumb for deciding which one to use is:
- Use Xavier with Tanh/Sigmoid
- Use Kaiming with ReLU, LeakyReLU and GELU.
Exercises
Use the official documentation while solving the exercises.
Exercise 1
Build a simple linear regression model from scratch with nn.Module. Define a LinearRegression class with an nn.Linear(1, 1) layer. Generate synthetic data following y = 4x + 3 + noise with 100 points. Train for 400 epochs with MSELoss and SGD. After training, check that the learnt weight is close to 4 and the bias to 3.
- Hint:
- Architecture: 1 → Linear(1,1) → 1
- Loss:
nn.MSELoss
- Optimiser:
torch.optim.SGD
Show solution
I won't use torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=max_norm) here because the gradients are not going to explode. The general rule is to use it when the loss explodes. It would be an extra hyperparameter in our model.
| import torch
import torch.nn as nn
# Model:
class LinearRegression(nn.Module):
# Model constructor:
def __init__(self):
super().__init__()
self.LinearLayer = nn.Linear(1,1)
def forward(self, x):
return self.LinearLayer(x)
# Create the model:
model = LinearRegression()
# Data:
torch.manual_seed(42)
x = torch.rand(100,1)
noise = torch.randn(100,1) * 0.1
y = 4*x + 3 + noise
# Loss and optimiser:
learning_rate = 0.1
loss_fn = nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
# Training:
epochs = 400
losses = []
print('Starting training...')
for epoch in range(epochs):
# Zero the optimiser's gradients:
optimizer.zero_grad()
loss = loss_fn(model(x), y)
# Backpropagation:
loss.backward()
# torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0) # Optional
optimizer.step()
losses.append(loss.item())
if epoch % 25 == 0 or epoch == epochs - 1 :
print(f'Epoch {epoch} -----> Loss: {loss.item():.4f}')
print('-----' * 10)
# Parameters:
weight = model.LinearLayer.weight.item()
bias = model.LinearLayer.bias.item()
print(f'Weight learned: {weight:.4f} (expected ≈ 4)')
print(f'Bias learned: {bias:.4f} (expected ≈ 3)')
|
| Output |
|---|
| Starting training...
Epoch 0 -----> Loss: 29.0533
Epoch 25 -----> Loss: 0.0822
Epoch 50 -----> Loss: 0.0452
Epoch 75 -----> Loss: 0.0263
Epoch 100 -----> Loss: 0.0167
Epoch 125 -----> Loss: 0.0118
Epoch 150 -----> Loss: 0.0092
Epoch 175 -----> Loss: 0.0080
Epoch 200 -----> Loss: 0.0073
Epoch 225 -----> Loss: 0.0070
Epoch 250 -----> Loss: 0.0068
Epoch 275 -----> Loss: 0.0067
Epoch 300 -----> Loss: 0.0067
Epoch 325 -----> Loss: 0.0067
Epoch 350 -----> Loss: 0.0066
Epoch 375 -----> Loss: 0.0066
Epoch 399 -----> Loss: 0.0066
--------------------------------------------------
Weight learned: 3.9478 (expected ≈ 4)
Bias learned: 3.0264 (expected ≈ 3)
|
Exercise 2
Train the same MLP architecture four times on y = sin(x) (300 evenly spaced points, x ∈ [-π, π]), changing only the activation function each time: ReLU, Tanh, GELU and LeakyReLU. The activation is applied after each hidden layer; the output layer has none**
Draw the four loss curves on the same plot and the four learnt functions against the real sine curve. Which activation best fits the shape of the sine and why?
- Architecture:
Linear(1→32) → Act → Linear(32→16) → Act → Linear(16→1)
- Loss:
nn.MSELoss
- Optimiser:
Adam (lr=1e-3)
- Epochs:
500
- Batch: full batch (all 300 points at each step)
Show solution
| # Model:
torch.manual_seed(42)
class Model(nn.Module):
def __init__(self, activation=nn.ReLU):
super().__init__()
blocks = []
neurons = [(1,32), (32,16)]
for _ in range(2):
n_in, n_out = neurons[_]
blocks.extend([nn.Linear(n_in, n_out), activation()])
self.blocks = nn.Sequential(*blocks)
self.output = nn.Linear(16,1)
def forward(self, x):
x = self.blocks(x)
return self.output(x)
# Data:
x = torch.linspace(-torch.pi, torch.pi, 300).unsqueeze(1) # (300, 1)
y = torch.sin(x) # (300,1)
# Configurations:
configs = {'ReLU': nn.ReLU, 'Tanh': nn.Tanh,
'GELU': nn.GELU, 'LeakyReLU': nn.LeakyReLU}
epochs = 500
results = {}
for key, activation_function in configs.items():
model = Model(activation= activation_function)
optimizer = torch.optim.Adam(model.parameters(), lr = 1e-3)
loss_fn = nn.MSELoss()
losses = []
print(f'Starting {key} training...')
model.train()
for epoch in range(epochs):
optimizer.zero_grad()
loss = loss_fn(model(x), y)
loss.backward()
optimizer.step()
if epoch % 100 == 0 or epoch == epochs-1:
print(f'Epoch {epoch} ---> Loss: {loss.item()}')
losses.append(loss.item())
results[key] = {'losses': losses, 'model': model}
print('-----'*10)
|
| Output |
|---|
| Starting ReLU training...
Epoch 0 ---> Loss: 0.5030925869941711
Epoch 100 ---> Loss: 0.10790500789880753
Epoch 200 ---> Loss: 0.04407544806599617
Epoch 300 ---> Loss: 0.013190364465117455
Epoch 400 ---> Loss: 0.004388445056974888
Epoch 499 ---> Loss: 0.001769070397131145
--------------------------------------------------
Starting Tanh training...
Epoch 0 ---> Loss: 0.48216161131858826
Epoch 100 ---> Loss: 0.08473459631204605
Epoch 200 ---> Loss: 0.03545720502734184
Epoch 300 ---> Loss: 0.020817823708057404
Epoch 400 ---> Loss: 0.011727229692041874
Epoch 499 ---> Loss: 0.005883519072085619
--------------------------------------------------
Starting GELU training...
Epoch 0 ---> Loss: 0.8635809421539307
Epoch 100 ---> Loss: 0.0876428484916687
Epoch 200 ---> Loss: 0.017983855679631233
Epoch 300 ---> Loss: 0.007721055299043655
Epoch 400 ---> Loss: 0.0031852973625063896
Epoch 499 ---> Loss: 0.0012849830090999603
--------------------------------------------------
Starting LeakyReLU training...
Epoch 0 ---> Loss: 0.47952061891555786
Epoch 100 ---> Loss: 0.10101024806499481
Epoch 200 ---> Loss: 0.01301219779998064
Epoch 300 ---> Loss: 0.002192762680351734
Epoch 400 ---> Loss: 0.0006725467392243445
Epoch 499 ---> Loss: 0.00029215021640993655
--------------------------------------------------
|
| import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 2, figsize=(14, 5))
# Plot 1: loss curves
for key, data in results.items():
axes[0].plot(data['losses'], label=key)
axes[0].set_title('Loss Curves')
axes[0].set_xlabel('Epoch')
axes[0].set_ylabel('MSE Loss')
axes[0].legend()
axes[0].grid(True)
# Plot 2: learnt functions against sin(x)
axes[1].plot(x.numpy(), y.numpy(), color='black', linewidth=3, label='sin(x)', alpha=1)
for key, data in results.items():
model = data['model']
model.eval()
with torch.no_grad():
y_pred = model(x).numpy()
axes[1].plot(x.numpy(), y_pred, label=key, linestyle='--', linewidth=3)
axes[1].set_title('Learned Functions vs sin(x)')
axes[1].set_xlabel('x')
axes[1].set_ylabel('y')
axes[1].legend()
axes[1].grid(True)
plt.tight_layout()
plt.show()
|

Exercise 3
Generate a 3-class 2D synthetic dataset with sklearn.datasets.make_blobs(300 samples, centers=3, cluster_std=1.2, random_state=42). Split it 80/20 into train/test (random_state=42). Build and train an MLP and then:
- Show the final accuracy on the test set
-
Draw the decision boundaries as a coloured background with plt.contourf
(mesh step 0.1, margin of 0.5 beyond the data range) with the test points
overlaid as a scatter plot
-
Architecture: Linear(2→16) → ReLU → Linear(16→8) → ReLU → Linear(8→3)
- Loss:
nn.CrossEntropyLoss (expects raw logits: no activation on the output layer)
- Optimiser:
Adam (lr=1e-3)
- Epochs:
300
- Batch: full batch (all the training points at each step)
- Tensors:
X → FloatTensor, y → LongTensor
Show solution
| from sklearn.datasets import make_blobs
from sklearn.model_selection import train_test_split
# Generate the dataset:
x, y = make_blobs(n_samples=300, n_features=2, centers=3, cluster_std=1.2, random_state=42)
x_train, x_test, y_train, y_test = train_test_split(x,y, test_size=0.2, random_state=42, shuffle=True, stratify=y)
print('--- Complete dataset ---')
print(f'x.shape: {x.shape}')
print(f'y.shape: {y.shape}')
print(f'Classes: {set(y)}')
print('--- Train dataset ---')
print(f'x_train.shape: {x_train.shape}')
print(f'y_train.shape: {y_train.shape}')
print('--- Test dataset ---')
print(f'x_test.shape: {x_test.shape}')
print(f'y_test.shape: {y_test.shape}')
plt.figure(figsize=(6,5))
plt.grid(True, alpha=0.5)
plt.scatter(x[:,0], x[:, 1], c=y, cmap='viridis', edgecolors='k', s=50)
plt.title('Synthetic Dataset - make_blobs')
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.tight_layout()
plt.show()
|
| Output |
|---|
| --- Complete dataset ---
x.shape: (300, 2)
y.shape: (300,)
Classes: {np.int64(0), np.int64(1), np.int64(2)}
--- Train dataset ---
x_train.shape: (240, 2)
y_train.shape: (240,)
--- Test dataset ---
x_test.shape: (60, 2)
y_test.shape: (60,)
|

| from sklearn.metrics import accuracy_score
# Create the model:
model = nn.Sequential(nn.Linear(2,16), nn.ReLU(),
nn.Linear(16,8), nn.ReLU(),
nn.Linear(8,3))
# Transform the data:
x_train = torch.FloatTensor(x_train)
y_train = torch.LongTensor(y_train)
x_test = torch.FloatTensor(x_test)
y_test = torch.LongTensor(y_test)
# Loss and optimiser:
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
# Training loop:
epochs = 300
losses, accuracies = [], []
model.train()
print('--- Train ---')
for epoch in range(epochs):
# Reset the optimiser:
optimizer.zero_grad()
logits = model(x_train)
# Compute the loss:
loss = loss_fn(logits, y_train)
# Compute metrics:
with torch.no_grad():
preds = logits.argmax(dim=1).numpy()
accuracy = accuracy_score(y_train.numpy(), preds)
# Backpropagation:
loss.backward()
optimizer.step()
if (epoch % 50 == 0) or (epoch == epochs -1):
print(f'Epoch {epoch} ---> Loss: {loss.item():.4f} ; accuracy: {accuracy:.4f}')
losses.append(loss.item())
accuracies.append(accuracy)
model.eval()
# Test:
with torch.no_grad():
y_pred = model(x_test)
loss_test = loss_fn(y_pred, y_test)
accuracy_test = accuracy_score(y_test, y_pred.argmax(dim=1).numpy())
print('--- Test ---')
print(f'Loss: {loss_test.item():.4f}')
print(f'Accuracy: {accuracy_test:.4f}')
print('-----'*10)
|
| Output |
|---|
| --- Train ---
Epoch 0 ---> Loss: 1.0101 ; accuracy: 0.3333
Epoch 50 ---> Loss: 0.6699 ; accuracy: 0.6667
Epoch 100 ---> Loss: 0.4351 ; accuracy: 0.9375
Epoch 150 ---> Loss: 0.2124 ; accuracy: 0.9917
Epoch 200 ---> Loss: 0.0975 ; accuracy: 1.0000
Epoch 250 ---> Loss: 0.0486 ; accuracy: 1.0000
Epoch 299 ---> Loss: 0.0276 ; accuracy: 1.0000
--- Test ---
Loss: 0.0270
Accuracy: 1.0000
--------------------------------------------------
|
| import numpy as np
# plt.contourf:
# Range --> X axis
min_feature1 = x_test[:,0].min().item() - 0.5
max_feature1 = x_test[:,0].max().item() + 0.5
x_min, x_max = min_feature1, max_feature1
# Range --> Y axis
min_feature2 = x_test[:,1].min().item() - 0.5
max_feature2 = x_test[:,1].max().item() + 0.5
y_min, y_max = min_feature2, max_feature2
# Create a mesh with every possible combination:
feature1_pnt = np.arange(x_min, x_max, 0.1)
feature2_pnt = np.arange(y_min, y_max, 0.1)
xx, yy = np.meshgrid(feature1_pnt, feature2_pnt)
# Transform the mesh as if it were the model's input
grid_stack = np.column_stack([xx.ravel(), yy.ravel()])
grid = torch.FloatTensor(grid_stack) # shape (H*W, 2)
# Evaluate the model:
model.eval()
with torch.no_grad():
Z = model(grid).argmax(dim=1).numpy() # shape (H*W,)
Z = Z.reshape(xx.shape) # shape (H, W)
plt.title('Decision Boundaries')
plt.contourf(xx, yy, Z, alpha=0.3, cmap='viridis')
plt.scatter(x_test[:, 0], x_test[:, 1], c=y_test.numpy(),
cmap='viridis', edgecolors='k', s=50)
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.show()
|

Exercise 4
Define an MLP with nn.Sequential and inspect its parameters without
using any external library:
- Show the name and shape of each parameter with
model.named_parameters()
- Count the total number of trainable parameters with
sum(p.numel() for p in model.parameters())
-
Visualise the first layer's weight matrix as a heatmap with
plt.imshow, cmap='viridis' and a colour bar
-
Architecture: Linear(4→16) → ReLU → Linear(16→8) → ReLU → Linear(8→3)
- No training needed: just instantiate the model with the default (random) weights
Show solution
| # Create the model:
model = nn.Sequential(nn.Linear(4,16), nn.ReLU(),
nn.Linear(16,8), nn.ReLU(),
nn.Linear(8,3))
# Names:
for name, parameter in model.named_parameters():
print(f'Name: {name} --> Parameter: {parameter.shape}')
# Number of weights:
total = sum(p.numel() for p in model.parameters())
print(f'Total number of trainable parameters: {total}')
# Heatmap of the first layer:
weights1 = model[0].weight.detach().numpy() # Shape (16,4) --> 4 inputs, 16 neurons
plt.figure(figsize=(4,6))
plt.imshow(weights1, cmap='viridis', aspect='auto')
plt.colorbar()
plt.title('Weights Layer 1')
plt.xlabel('Input Features')
plt.ylabel('Neurons')
plt.tight_layout()
plt.show()
|
| Output |
|---|
| Name: 0.weight --> Parameter: torch.Size([16, 4])
Name: 0.bias --> Parameter: torch.Size([16])
Name: 2.weight --> Parameter: torch.Size([8, 16])
Name: 2.bias --> Parameter: torch.Size([8])
Name: 4.weight --> Parameter: torch.Size([3, 8])
Name: 4.bias --> Parameter: torch.Size([3])
Total number of trainable parameters: 243
|

Exercise 5
Train an MLP classifier on the Iris dataset (sklearn.datasets.load_iris,
150 samples, 4 features, 3 classes). Once it is trained:
- Save the model's weights with
torch.save(model.state_dict(), 'iris_model.pth')
- Create a new instance of the same architecture and load the saved weights
with
model.load_state_dict(torch.load('iris_model.pth'))
- Run both models in
model.eval() + torch.no_grad() on the test set
-
Check that the outputs are identical with torch.allclose(out1, out2)
-
Architecture: Linear(4→16) → ReLU → Linear(16→8) → ReLU → Linear(8→3)
- Loss:
nn.CrossEntropyLoss (expects raw logits: no activation on the output layer)
- Optimiser:
Adam (lr=1e-3)
- Epochs:
200
- Batch: full batch (all the training points at each step)
- Split: 80/20 train/test (
random_state=42)
- Tensors:
X → FloatTensor, y → LongTensor
Show solution
| from sklearn.datasets import load_iris
import pandas as pd
# Load the dataset:
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['class'] = iris.target
print(f'Number of instances: {iris.data.shape[0]}')
print(f'Number of Features: {iris.data.shape[1]}')
print(f'Feature names: {iris.feature_names}')
print(f'Number of labels: {len(iris.target_names)}')
print(f'Target names: {iris.target_names}')
display(df.head(5))
# Extract the data:
X, y = iris.data, iris.target # (150, 4), (150,)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
X_train = torch.FloatTensor(X_train)
X_test = torch.FloatTensor(X_test)
y_train = torch.LongTensor(y_train)
y_test = torch.LongTensor(y_test)
|
| Output |
|---|
| Number of instances: 150
Number of Features: 4
Feature names: ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']
Number of labels: 3
Target names: ['setosa' 'versicolor' 'virginica']
|
|
sepal length (cm) |
sepal width (cm) |
petal length (cm) |
petal width (cm) |
class |
| 0 |
5.1 |
3.5 |
1.4 |
0.2 |
0 |
| 1 |
4.9 |
3.0 |
1.4 |
0.2 |
0 |
| 2 |
4.7 |
3.2 |
1.3 |
0.2 |
0 |
| 3 |
4.6 |
3.1 |
1.5 |
0.2 |
0 |
| 4 |
5.0 |
3.6 |
1.4 |
0.2 |
0 |
| # Create the model:
model = nn.Sequential(nn.Linear(4,16), nn.ReLU(),
nn.Linear(16,8), nn.ReLU(),
nn.Linear(8,3))
# Loss and optimiser:
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
# Training loop:
epochs = 200
model.train()
for epoch in range(epochs):
optimizer.zero_grad()
loss = loss_fn(model(X_train), y_train)
loss.backward()
optimizer.step()
if (epoch % 50 == 0) or (epoch == epochs -1):
print(f'Epoch {epoch} --> loss: {loss.item():.4f}')
torch.save(model.state_dict(), 'iris_model.pth')
|
| Output |
|---|
| Epoch 0 --> loss: 1.1329
Epoch 50 --> loss: 1.0736
Epoch 100 --> loss: 0.9834
Epoch 150 --> loss: 0.8214
Epoch 199 --> loss: 0.6397
|
| # A new instance is needed: load_state_dict() loads the weights into an existing model, it doesn't return one.
saved_model = nn.Sequential(nn.Linear(4,16), nn.ReLU(),
nn.Linear(16,8), nn.ReLU(),
nn.Linear(8,3))
saved_model.load_state_dict(torch.load('iris_model.pth'))
# Test:
model.eval()
saved_model.eval()
with torch.no_grad():
pred1 = model(X_test)
pred2 = saved_model(X_test)
print(f'Both models are identical? --> {torch.allclose(pred1, pred2)}')
|
| Output |
|---|
| Both models are identical? --> True
|
Exercise 6
Implement a custom ScaledLinear(nn.Module) layer that computes
y = alpha * (W · x + b), where alpha is a trainable scalar
initialised to 1.0 through nn.Parameter. Use it to build an MLP that
predicts y₁ = sin(x) and y₂ = cos(x) at the same time
(300 evenly spaced points, x ∈ [-π, π], full batch). Stack them as
Y = torch.stack([y1, y2], dim=1), of shape (300, 2). Then:
- Check that
alpha appears in every layer when calling model.named_parameters()
- Show the value of
alpha in each ScaledLinear before and after training
- Has
alpha changed? Show True/False per layer by comparing the initial value with the final one
-
Draw both predicted curves against the real ones in a single figure with a legend
-
Architecture: ScaledLinear(1→32) → ReLU → ScaledLinear(32→16) → ReLU → ScaledLinear(16→2)
- Loss:
nn.MSELoss, applied directly to the full output of shape (300, 2)
- Optimiser:
Adam (lr=1e-3), with all the parameters, alpha included
- Epochs:
1000
- Batch: full batch (all 300 points at each step)
- Tensors:
X → FloatTensor of shape (300, 1), Y → FloatTensor of shape (300, 2)
Show solution
| # Create the class:
class ScaledLinear(nn.Module):
def __init__(self, input_neurons, output_neurons):
super().__init__()
self.W = nn.Parameter(torch.randn(output_neurons, input_neurons))
self.b = nn.Parameter(torch.zeros(output_neurons))
self.alpha = nn.Parameter(torch.tensor(1.0))
def forward(self, x):
return self.alpha * (torch.matmul(x, self.W.T) + self.b)
# Create the model:
model = nn.Sequential(ScaledLinear(1,32), nn.ReLU(),
ScaledLinear(32,16), nn.ReLU(),
ScaledLinear(16,2))
# Check that alpha appears:
print('--- Before training ---')
alphas = []
for name, parameter in model.named_parameters():
if name.__contains__('alpha'):
print(f'{name} --> {parameter.item()}')
alphas.append(parameter.item())
# Loss and optimiser:
loss_fn = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
# Data:
print('--- Dataset ---')
x = torch.linspace(-torch.pi, torch.pi, 200)
y1 = torch.sin(x)
y2 = torch.cos(x)
x = torch.FloatTensor(x.unsqueeze(1))
y = torch.FloatTensor(torch.stack([y1, y2], dim=1))
print(f'x.shape: {x.shape}')
print(f'y.shape: {y.shape}')
# Training loop:
epochs = 1000
model.train()
print('--- Train ---')
for epoch in range(epochs):
# Reset the optimiser:
optimizer.zero_grad()
# Prediction:
pred = model(x)
# Loss:
loss = loss_fn(pred, y)
# Backpropagation:
loss.backward()
optimizer.step()
if (epoch % 250 == 0) or (epoch == epochs -1):
print(f'Epoch {epoch} --> loss:{loss.item():.4f}')
print('--- After training ---')
i = 0
for name, parameter in model.named_parameters():
if name.__contains__('alpha'):
print(f'{name} --> {parameter.item():.4f}')
print(f'Did alpha change? --> {not (alphas[i] == parameter.item())}')
i +=1
# Test:
model.eval()
with torch.no_grad():
pred = model(x).numpy()
# Plot:
x_np = x.squeeze().numpy()
plt.figure(figsize=(8, 4))
plt.plot(x_np, y1.numpy(), color='blue', label='sin(x) real')
plt.plot(x_np, y2.numpy(), color='red', label='cos(x) real')
plt.plot(x_np, pred[:, 0], color='blue', label='sin(x) pred', linestyle='--')
plt.plot(x_np, pred[:, 1], color='red', label='cos(x) pred', linestyle='--')
plt.legend()
plt.title('sin(x) and cos(x) — real vs predicted')
plt.xlabel('x')
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
|
| Output |
|---|
| --- Before training ---
0.alpha --> 1.0
2.alpha --> 1.0
4.alpha --> 1.0
--- Dataset ---
x.shape: torch.Size([200, 1])
y.shape: torch.Size([200, 2])
--- Train ---
Epoch 0 --> loss:244.7681
Epoch 250 --> loss:0.5739
Epoch 500 --> loss:0.0633
Epoch 750 --> loss:0.0188
Epoch 999 --> loss:0.0077
--- After training ---
0.alpha --> 0.9404
Did alpha change? --> True
2.alpha --> 0.9417
Did alpha change? --> True
4.alpha --> 0.9417
Did alpha change? --> True
|

Summary
| Topic |
Key concept |
PyTorch API |
| Model definition |
Inherit from nn.Module and implement forward |
nn.Module, nn.Linear |
| Regression |
MSE loss, SGD/Adam |
nn.MSELoss, torch.optim |
| Activation functions |
Non-linearity, inductive bias |
nn.ReLU, nn.Tanh, nn.GELU, nn.LeakyReLU |
| Multiclass |
Logits + cross-entropy |
nn.CrossEntropyLoss |
| Parameter inspection |
Counting and visualising weights |
.named_parameters(), .numel() |
| Save / load |
Persisting and restoring the state_dict |
torch.save, torch.load |
| Custom layers |
Trainable scalars/tensors |
nn.Parameter |
| Multi-output |
Joint regression over several targets |
Output layer with k units |
| Binary classification |
Sigmoid + BCE fused for greater stability |
nn.BCEWithLogitsLoss |
| Residual blocks |
Skip connections for deep networks |
Manual out = F(x) + x |
| Weight initialisation |
Breaking symmetry, controlling variance |
torch.nn.init |