Skip to main content

Deep Learning 2

How Neural Networks Learn

Colab link

Open In Colab

In class 1 we saw that a neural network is a function with many parameters (101,770 in our MNIST MLP) and that, with random weights, it guesses ~10% for each digit. Today we’ll see how the weights are adjusted.

The learning cycle has three pieces:

  1. Loss function: a number that measures how wrong the network is
  2. Gradient: which direction to move each weight so the loss goes down (computed by backpropagation)
  3. Update: take a small step in that direction (gradient descent)

Repeating this cycle thousands of times, the network learns.

Code
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import datasets, transforms
from torch.utils.data import DataLoader


AZUL, LARANJA, VERDE, CINZA, TINTA = "#2a78d6", "#eb6834", "#1baf7a", "#898781", "#52514e"
plt.rcParams.update({
    "axes.spines.top": False, "axes.spines.right": False,
    "axes.edgecolor": CINZA, "axes.labelcolor": TINTA,
    "xtick.color": TINTA, "ytick.color": TINTA,
    "axes.grid": True, "grid.color": "#e6e5e1", "figure.dpi": 110,
})

torch.manual_seed(42)
np.set_printoptions(precision=3, suppress=True)

# the same MNIST and the same MLP as in class 1
treino = datasets.MNIST(root="data", train=True, download=True, transform=transforms.ToTensor())
teste = datasets.MNIST(root="data", train=False, download=True, transform=transforms.ToTensor())

def cria_mlp():
    return nn.Sequential(nn.Flatten(), nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 10))

modelo = cria_mlp()

1. Loss functions

The loss compares the prediction \(\hat{y}\) with the true value \(y\) and returns a single number: the smaller, the better. Training the network means searching for the weights that minimize the loss.

Regression: mean squared error (MSE)

When the output is a continuous number (temperature, rainfall, price):

\[\text{MSE} = \frac{1}{N}\sum_{i=1}^{N}(\hat{y}_i - y_i)^2\]

Squaring makes every error positive and punishes large errors much more.

Code
y_real = torch.tensor([2.0, 3.5, 1.0])
y_prev = torch.tensor([2.5, 3.0, 2.0])

erros = y_prev - y_real
print(f"errors:           {erros.tolist()}")
print(f"squared errors:    {(erros ** 2).tolist()}")
print(f"MSE by hand: {(erros ** 2).mean():.4f}")
print(f"nn.MSELoss:  {nn.MSELoss()(y_prev, y_real):.4f}")
erros:            [0.5, -0.5, 1.0]
erros ao quadrado: [0.25, 0.25, 1.0]
MSE à mão:   0.5000
nn.MSELoss:  0.5000

Classification: cross-entropy

We saw in the previous class that, with the MNIST dataset and our MLP, the network returns 10 logits, which the softmax at the output turns into probabilities.

Cross-entropy looks only at the probability the network gave to the correct class, \(p_{\text{correct}}\):

\[\text{CE} = -\log(p_{\text{correct}})\]

  • If the network gives 100% to the right class: \(-\log(1) = 0\), zero loss.
  • If it gives almost 0% to the right class: \(-\log(0.001) \approx 6.9\), a huge loss.

Let’s compute it by hand for one image and compare with PyTorch. In PyTorch, F.cross_entropy takes the logits directly (it applies the softmax internally).

Code
imagem, rotulo = treino[0]
logits = modelo(imagem.unsqueeze(0))            # (1, 10)
probs = torch.softmax(logits, dim=1)

p_correta = probs[0, rotulo]
print(f"true label: {rotulo}")
print(f"probability given to digit {rotulo}: {p_correta:.4f}")
print(f"CE by hand:       -log({p_correta:.4f}) = {-torch.log(p_correta):.4f}")
print(f"F.cross_entropy:  {F.cross_entropy(logits, torch.tensor([rotulo])):.4f}")
rótulo verdadeiro: 5
probabilidade dada ao dígito 5: 0.1020
CE à mão:         -log(0.1020) = 2.2828
F.cross_entropy:  2.2828
Code
p = np.linspace(0.005, 1, 400)
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(p, -np.log(p), color=AZUL, lw=2.5)
for valor, texto, cor in [(0.9, "confident and right", VERDE), (0.1, "guess (10%)", CINZA), (0.01, "confident and wrong", LARANJA)]:
    ax.scatter(valor, -np.log(valor), s=80, color=cor, zorder=3)
    ax.annotate(f"{texto}\np = {valor}  loss = {-np.log(valor):.2f}", (valor, -np.log(valor)),
                xytext=(15, 10), textcoords="offset points", color=TINTA, fontsize=9)
ax.set(xlabel="probability given to the correct class", ylabel="cross-entropy = -log(p)",
       title="Probabilidade vs Loss com Cross-Entropy", xlim=(0, 1.05))
plt.show()

Sanity check: a network that hasn’t learned anything yet gives ~10% to each of the 10 digits, so the mean loss should be close to \(-\log(0.1) = \ln(10) \approx 2.30\). If a model’s initial loss is very different from that, something is wrong in the code.

Code
lote_grande = next(iter(DataLoader(treino, batch_size=1000)))
x_lote, y_lote = lote_grande
with torch.no_grad():
    perda_inicial = F.cross_entropy(modelo(x_lote), y_lote)
print(f"mean loss of the untrained network (1000 images): {perda_inicial:.3f}")
print(f"ln(10) = {np.log(10):.3f}")
perda média da rede não treinada (1000 imagens): 2.298
ln(10) = 2.303

Gradient Descent

Imagine the loss as a landscape, where each combination of weights is a point and the height is the loss. We want to reach the valley as fast as possible. The gradient \(\nabla L\) points to where the loss rises fastest. The trick is to go in the opposite direction:

\[\theta_i \leftarrow \theta - \eta \, \nabla L(\theta)\]

  • \(\theta\): the parameters (weights and biases)
  • \(\eta\) (eta): the learning rate, the step size

We start with a single parameter and a simple loss, \(L(\theta) = (\theta - 3)^2\), whose minimum is at \(\theta = 3\) and whose gradient is \(\nabla L = 2(\theta - 3)\).

Code
def perda_1d(theta):
    return (theta - 3) ** 2

def gradiente_1d(theta):
    return 2 * (theta - 3)

def descida_1d(theta0, eta, passos=15):
    caminho = [theta0]
    for _ in range(passos):
        caminho.append(caminho[-1] - eta * gradiente_1d(caminho[-1]))
    return np.array(caminho)

thetas = np.linspace(-3, 9, 300)
fig, axes = plt.subplots(1, 3, figsize=(15, 4), sharey=True)
for ax, (eta, titulo) in zip(axes, [(0.03, "η = 0.03: too small"), (0.3, "η = 0.3: good"), (1.05, "η = 1.05: too large")]):
    caminho = descida_1d(theta0=-1.0, eta=eta)
    ax.plot(thetas, perda_1d(thetas), color=CINZA, lw=2)
    ax.plot(caminho, perda_1d(caminho), color=LARANJA, lw=1, marker="o", ms=5)
    ax.scatter(caminho[0], perda_1d(caminho[0]), s=90, color=AZUL, zorder=3, label="start")
    ax.set(title=titulo, xlabel="θ", ylim=(-2, 40), xlim=(-3, 9))
    ax.text(0.03, 0.95, f"after 15 steps: θ = {caminho[-1]:.2f}", transform=ax.transAxes, va="top", color=TINTA)
axes[0].set_ylabel("loss L(θ)")
axes[0].legend(frameon=False, loc="upper right")
plt.tight_layout()
plt.show()

  • η too small: gets there, but slowly (many steps = a lot of training time).
  • η good: quickly reaches the minimum \(\theta = 3\).
  • η too large: each step overshoots and lands farther away on the other side: the loss blows up (divergence).

In two dimensions

A real network has thousands of parameters, but the idea is the same. With 2 parameters we can draw the landscape as a contour map. We use \(L(\theta_1, \theta_2) = \theta_1^2 + 25\,\theta_2^2\), an elongated valley: very steep in the \(\theta_2\) direction and almost flat in the \(\theta_1\) direction. Landscapes like this are common in neural networks.

Code
def perda_2d(t1, t2):
    return t1 ** 2 + 25 * t2 ** 2

def gradiente_2d(t1, t2):
    return np.array([2 * t1, 50 * t2])

def descida_2d(inicio, eta, passos=30):
    caminho = [np.array(inicio, dtype=float)]
    for _ in range(passos):
        caminho.append(caminho[-1] - eta * gradiente_2d(*caminho[-1]))
    return np.array(caminho)

T1, T2 = np.meshgrid(np.linspace(-5, 5, 300), np.linspace(-2, 2, 300))
fig, axes = plt.subplots(1, 2, figsize=(14, 4.5))
for ax, eta in zip(axes, [0.01, 0.035]):
    caminho = descida_2d([-4.5, 1.0], eta)
    ax.contour(T1, T2, perda_2d(T1, T2), levels=np.logspace(-1, 1.8, 12), colors=CINZA, linewidths=0.8)
    ax.plot(caminho[:, 0], caminho[:, 1], color=LARANJA, marker="o", ms=4, lw=1.5)
    ax.scatter(0, 0, marker="*", s=250, color=VERDE, zorder=3, label="minimum")
    ax.scatter(*caminho[0], s=80, color=AZUL, zorder=3, label="start")
    ax.set(title=f"η = {eta}: 30 steps, final loss = {perda_2d(*caminho[-1]):.3f}", xlabel="θ₁", ylabel="θ₂")
    ax.set_aspect("equal")
    ax.grid(False)
axes[0].legend(frameon=False, loc="lower right")
plt.tight_layout()
plt.show()

With a small η, the path is smooth but doesn’t reach the minimum in 30 steps. With a larger η, it moves faster along \(\theta_1\) but zigzags along \(\theta_2\), the steep direction. There’s no η that’s perfect for both directions at once. In class 3 we’ll see optimizers (momentum, Adam) that solve this.

Backpropagation: the chain rule, layer by layer

To use gradient descent we need \(\frac{\partial L}{\partial w}\) for every weight. Backpropagation computes this efficiently using the chain rule: if \(L\) depends on \(\hat{y}\), which depends on \(h\), which depends on \(w\), then

\[\frac{\partial L}{\partial w} = \frac{\partial L}{\partial \hat{y}} \cdot \frac{\partial \hat{y}}{\partial h} \cdot \frac{\partial h}{\partial w}\]

Let’s do it by hand for a tiny network with only two weights:

\[z = w_1 x \qquad h = \text{ReLU}(z) \qquad \hat{y} = w_2 h \qquad L = (\hat{y} - y)^2\]

with \(x = 2\), \(y = 1\), \(w_1 = 0.5\) and \(w_2 = 0.8\).

Code
x, y = 2.0, 1.0
w1, w2 = 0.5, 0.8

# forward pass: from the input to the loss
z = w1 * x
h = max(0.0, z)
y_hat = w2 * h
L = (y_hat - y) ** 2
print("FORWARD")
print(f"  z = w1·x = {z:.3f}   h = ReLU(z) = {h:.3f}   ŷ = w2·h = {y_hat:.3f}   L = (ŷ - y)² = {L:.4f}")

# backward pass: from the loss to the weights, multiplying local derivatives
dL_dyhat = 2 * (y_hat - y)
dyhat_dw2 = h
dyhat_dh = w2
dh_dz = 1.0 if z > 0 else 0.0          # ReLU derivative
dz_dw1 = x

dL_dw2 = dL_dyhat * dyhat_dw2
dL_dw1 = dL_dyhat * dyhat_dh * dh_dz * dz_dw1
print("\nBACKWARD (chain rule)")
print(f"  ∂L/∂ŷ = 2(ŷ - y) = {dL_dyhat:.3f}")
print(f"  ∂L/∂w2 = ∂L/∂ŷ · h = {dL_dyhat:.3f} × {dyhat_dw2:.3f} = {dL_dw2:.4f}")
print(f"  ∂L/∂w1 = ∂L/∂ŷ · w2 · ReLU'(z) · x = {dL_dyhat:.3f} × {dyhat_dh:.3f} × {dh_dz:.0f} × {dz_dw1:.0f} = {dL_dw1:.4f}")
FORWARD
  z = w1·x = 1.000   h = ReLU(z) = 1.000   ŷ = w2·h = 0.800   L = (ŷ - y)² = 0.0400

BACKWARD (regra da cadeia)
  ∂L/∂ŷ = 2(ŷ - y) = -0.400
  ∂L/∂w2 = ∂L/∂ŷ · h = -0.400 × 1.000 = -0.4000
  ∂L/∂w1 = ∂L/∂ŷ · w2 · ReLU'(z) · x = -0.400 × 0.800 × 1 × 2 = -0.6400

PyTorch does this by itself: autograd

By marking the weights with requires_grad=True, PyTorch records every operation of the forward pass. When you call L.backward(), it walks back through this record applying the chain rule, and stores each derivative in the .grad attribute of the corresponding weight. The numbers must match ours:

Code
w1_t = torch.tensor(0.5, requires_grad=True)
w2_t = torch.tensor(0.8, requires_grad=True)

L_t = (w2_t * torch.relu(w1_t * x) - y) ** 2

## here it computes the gradients automatically
L_t.backward()

print(f"∂L/∂w1: by hand = {dL_dw1:.4f}   autograd = {w1_t.grad:.4f}")
print(f"∂L/∂w2: by hand = {dL_dw2:.4f}   autograd = {w2_t.grad:.4f}")
∂L/∂w1: à mão = -0.6400   autograd = -0.6400
∂L/∂w2: à mão = -0.4000   autograd = -0.4000

Both gradients are negative: increasing \(w_1\) and \(w_2\) decreases the loss (the prediction 0.8 is below the target 1.0). One gradient descent step with \(\eta = 0.1\):

Code
eta = 0.1
with torch.no_grad():                        # the update itself must not be recorded by autograd
    w1_t -= eta * w1_t.grad
    w2_t -= eta * w2_t.grad
    L_novo = (w2_t * torch.relu(w1_t * x) - y) ** 2

print(f"new weights: w1 = {w1_t:.3f}, w2 = {w2_t:.3f}")
print(f"loss: {L:.4f} → {L_novo:.4f}")
novos pesos: w1 = 0.564, w2 = 0.840
perda: 0.0400 → 0.0028

One step, and the loss dropped from 0.04 to ~0.003. That’s the whole of learning: forward, loss, backward, update. Now let’s do the same with the 101,770 parameters of the MNIST MLP.

Training the MNIST MLP from scratch

First, a single step: forward, loss and backward(). Each parameter of the network gets a .grad with exactly the same shape as the parameter.

Code
torch.manual_seed(0)
modelo = cria_mlp()
loader = DataLoader(treino, 
                    batch_size=64, 
                    shuffle=True)

x_lote, y_lote = next(iter(loader))
perda = F.cross_entropy(modelo(x_lote), y_lote)
perda.backward()

print(f"batch loss: {perda.item():.3f}\n")
for nome, p in modelo.named_parameters():
    print(f"{nome:<10} parameter {str(tuple(p.shape)):<12} gradient {str(tuple(p.grad.shape)):<12} mean |grad| = {p.grad.abs().mean():.2e}")
perda do lote: 2.302

1.weight   parâmetro (128, 784)   gradiente (128, 784)   |grad| médio = 9.83e-04
1.bias     parâmetro (128,)       gradiente (128,)       |grad| médio = 3.34e-03
3.weight   parâmetro (10, 128)    gradiente (10, 128)    |grad| médio = 4.07e-03
3.bias     parâmetro (10,)        gradiente (10,)        |grad| médio = 2.02e-02

We’ve seen that the fundamental steps are: - Run the forward pass - Compute the loss - Run backpropagation - Update the weight parameters


And that’s exactly 1 step.

Now a full training run, without any ready-made optimizer: just the rule \(\theta \leftarrow \theta - \eta\nabla L\) applied to each parameter. We use mini-batches of 64 images: instead of computing the gradient over all 60 thousand images at every step (slow), we estimate it with 64 randomly drawn images. This is stochastic gradient descent (SGD).

Two important details:

  • the update happens inside torch.no_grad(), so autograd doesn’t record the update itself;
  • after updating, we zero the gradients (p.grad.zero_()). In class 3 we’ll see what happens if we forget.
Code
def acuracia(modelo, dataset, n=10000):
    x, y = next(iter(DataLoader(dataset, batch_size=n)))
    with torch.no_grad():
        return (modelo(x).argmax(dim=1) == y).float().mean().item()

torch.manual_seed(0)
modelo = cria_mlp()
lr = 0.1
steps = 600
print(f"test accuracy BEFORE training: {acuracia(modelo, teste):.1%}")

historico = []
for passo, (x_lote, y_lote) in enumerate(loader):
    if passo == steps:
        break
    perda = F.cross_entropy(modelo(x_lote), y_lote)   # 1. forward + loss
    perda.backward()                                   # 2. backward: computes all the .grad
    with torch.no_grad():
        for p in modelo.parameters():                  # 3. update: θ ← θ - η·∇L
            p -= lr * p.grad
            p.grad.zero_()                             # 4. zero the gradients for the next step
    historico.append(perda.item())

print(f"test accuracy AFTER {steps} steps: {acuracia(modelo, teste):.1%}")
acurácia no teste ANTES de treinar: 10.4%
acurácia no teste DEPOIS de 600 passos: 91.6%
Code
historico = np.array(historico)
media_movel = np.convolve(historico, np.ones(20) / 20, mode="valid")

fig, ax = plt.subplots(figsize=(10, 4))
ax.plot(historico, color=AZUL, alpha=0.3, lw=1, label="loss of each batch")
ax.plot(np.arange(19, len(historico)), media_movel, color=AZUL, lw=2.5, label="moving average (20 batches)")
ax.axhline(np.log(10), color=CINZA, ls="--", lw=1)
ax.text(len(historico), np.log(10) + 0.05, "ln(10): random guess", ha="right", va="bottom", color=TINTA, fontsize=9)
ax.set(xlabel="step (batch of 64 images)", ylabel="cross-entropy", title="Training the MNIST MLP without an optimizer")
ax.legend(frameon=False)
plt.show()

Code
x_ex, y_ex = next(iter(DataLoader(teste, batch_size=12)))
with torch.no_grad():
    probs_ex = torch.softmax(modelo(x_ex), dim=1)

fig, axes = plt.subplots(2, 6, figsize=(12, 4.5))
for ax, img, y_true, p in zip(axes.flat, x_ex, y_ex, probs_ex):
    pred = p.argmax().item()
    ax.imshow(img[0], cmap="gray_r")
    ax.set_title(f"predicted {pred} ({p[pred]:.0%})", color=VERDE if pred == y_true else LARANJA, fontsize=10)
    ax.axis("off")
plt.suptitle("Predictions on the test set after training (green = correct, orange = wrong)")
plt.tight_layout()
plt.show()

In a few seconds, the network went from ~10% to ~90% accuracy on images it has never seen. We used nothing but: a loss, backward() for the gradients and a hand-written update rule.

5. Discussion

  • The loss turns “how wrong the network is” into a number: MSE for regression, cross-entropy for classification. The initial loss of a 10-class classifier should be ≈ ln(10) ≈ 2.30.
  • Gradient descent takes steps against the gradient: \(\theta \leftarrow \theta - \eta\nabla L\). The learning rate η is the most important hyperparameter: too small is slow; too large diverges.
  • Backpropagation is the chain rule applied from the output back to the input. PyTorch’s autograd does this with loss.backward() and stores the result in .grad.
  • Using mini-batches (SGD) makes each step cheap; the per-batch loss is noisy, but the trend goes down.

Exercises

  1. In section 3, change \(w_1\) to \(-0.5\). What happens to \(\frac{\partial L}{\partial w_1}\)? Why? (Hint: ReLU.)
  2. In the MNIST training, try eta = 0.01 and eta = 2.0. Plot the three loss curves together.
  3. Comment out the line p.grad.zero_() and train again. What happens to the loss? Try to explain before class 3.
  4. Compute by hand the cross-entropy of a network that gives 50% to the correct class. And 99%?