In this class we look at a neural network for what it really is: a mathematical function. No mystery: weighted sums, matrix multiplications and a few non-linear functions.
Plan
This week’s example: images of handwritten digits (MNIST)
The neuron: weighted sum + bias
The layer: a matrix multiplication, \(y = Wx + b\)
The forward pass by hand and in PyTorch
A real network applied to MNIST
Why we need activation functions
The Universal Approximation Theorem
This is the first of four notebooks in the deep learning block. They all use MNIST, and each one picks up where the previous one left off.
MNIST is the “Hello, world!” of deep learning: 60 thousand training images and 10 thousand test images, each with a handwritten digit from 0 to 9, in grayscale, at 28 × 28 pixels. The task is to classify each image as the correct digit (10 classes).
torchvision downloads the dataset the first time (≈ 60 MB) and stores it in the data/ folder. transforms.ToTensor() converts each image into a PyTorch tensor with values between 0 and 1.
Code
mnist = datasets.MNIST(root="data", train=True, download=True, transform=transforms.ToTensor() )imagem, rotulo = mnist[0]print(f"{len(mnist)} training images")print(f"shape of one image: {tuple(imagem.shape)} (channel, height, width)")print(f"values between {imagem.min():.0f} and {imagem.max():.0f}; label = {rotulo}")
60000 imagens de treino
formato de uma imagem: (1, 28, 28) (canal, altura, largura)
valores entre 0 e 1; rótulo = 5
An image is nothing more than a sequence of numbers
The network we’re going to build (an MLP, Multi-Layer Perceptron) takes a vector as input. So we “flatten” the image: the 28 rows of 28 pixels become a vector of 784 numbers. That’s exactly what the nn.Flatten() layer does.
Code
imagem.flatten().unsqueeze(0).shape
torch.Size([1, 784])
Code
vetor = nn.Flatten()(imagem.unsqueeze(0)) # PyTorch expects a batch of imagesprint(f"{tuple(imagem.shape)} > {tuple(vetor.shape)}")fig, axes = plt.subplots(2, 1, figsize=(12, 4), height_ratios=[3, 1])axes[0].imshow(imagem[0], cmap="gray_r")axes[0].set_title(f"28 × 28 image (label {rotulo})")axes[0].axis("off")axes[1].imshow(vetor, cmap="gray_r", aspect="auto")axes[1].set(yticks=[], xlabel="position in the vector (0 to 783)", title="The same image as a vector of 784 numbers")axes[1].grid(False)plt.tight_layout()plt.show()
(1, 28, 28) > (1, 784)
The neuron
A neuron can be seen as a weighted sum of its inputs plus a bias, as we saw in our theory class.
An artificial neuron receives inputs \(x_1, x_2, \dots, x_n\), multiplies each one by a weight\(w_i\), adds everything up and adds a bias\(b\):
The weights say how much each input matters (and whether it pushes the result up or down). The bias shifts the result. Weights and biases are the parameters the network will learn.
Code
def desenha_rede(camadas, ax, rotulos=None, titulo=""):"""Draws a fully connected network: camadas = number of neurons per layer.""" xs = np.linspace(0, 1, len(camadas)) pos = []for x, n inzip(xs, camadas): ys = np.linspace(0.5-0.15* (n -1), 0.5+0.15* (n -1), n) pos.append([(x, y) for y in ys])for a, b inzip(pos[:-1], pos[1:]):for (x0, y0) in a:for (x1, y1) in b: ax.plot([x0, x1], [y0, y1], color=CINZA, lw=1, zorder=1) cores = [AZUL] + [VERDE] * (len(camadas) -2) + [LARANJA]for camada, cor inzip(pos, cores):for (x, y) in camada: ax.scatter(x, y, s=900, color=cor, zorder=2, edgecolor="white", lw=2)if rotulos:for x, r inzip(xs, rotulos): ax.text(x, -0.05, r, ha="center", va="top", color=TINTA) ax.set(xlim=(-0.15, 1.15), ylim=(-0.2, 1.1), title=titulo) ax.axis("off")fig, ax = plt.subplots(figsize=(5, 3))desenha_rede([3, 1], ax, ["inputs x", "neuron z"], "One neuron with 3 inputs")plt.show()
Code
x = np.array([0.9, 0.3, 0.6]) # 3 inputs (for example, 3 pixels or 3 features)w = np.array([0.4, -0.6, 0.9]) # 1 weight per inputb =0.1# biasfor i inrange(3):print(f"w{i +1}·x{i +1} = {w[i]:+.1f} × {x[i]:.1f} = {w[i] * x[i]:+.2f}")## the magic happens here! # see how the multiplication is done in numpy, with @ (matrix multiplication)z = w @ x + bprint(f"\nz = sum + b = {(w * x).sum():+.2f}{b:+.1f} = {z:+.2f}")
A layer is a group of neurons that receive the same inputs, each with its own weights. Stacking the weight vectors as rows of a matrix \(W\), the whole layer becomes a single operation:
\[\mathbf{y} = W\mathbf{x} + \mathbf{b}\]
With 3 inputs and 2 neurons, \(W\) has shape \(2 \times 3\) (one row per neuron) and \(\mathbf{b}\) has 2 values. That’s why GPUs are so good for deep learning: they are matrix multiplication machines.
Code
W = np.array([[0.4, -0.6, 0.9], # weights of neuron 1 (same as the example above) [-0.3, 0.2, 0.5]]) # weights of neuron 2b = np.array([0.1, -0.2])y = W @ x + bprint(f"W: {W.shape}, x: {x.shape}, b: {b.shape} → y: {y.shape}")print(f"y = {y}")
In PyTorch, a layer like this is an nn.Linear(inputs, outputs). For MNIST, a layer from 784 inputs (the pixels) to 128 neurons has a \(128 \times 784\) weight matrix:
Code
camada = nn.Linear(784, 128)print(f"weights W: {tuple(camada.weight.shape)} bias b: {tuple(camada.bias.shape)}")print(f"parameters: {camada.weight.numel():,} weights + {camada.bias.numel()} biases = {sum(p.numel() for p in camada.parameters()):,}")
Stacking layers gives us an MLP. The forward pass is simply computing the output, layer by layer. Let’s do it by hand for a small network with 3 inputs, 2 hidden neurons and 1 output:
Look at step 2: the second neuron produced a negative value and the ReLU zeroed it out. For this input, it simply doesn’t contribute to the output: \(\hat{y} = 1.5 \times 0.82 - 2.0 \times 0 + 0.3 = 1.53\).
Now the same network in PyTorch. We copy the weights above into two nn.Linear layers and check that the result is identical. It has to be: PyTorch does nothing more than these calculations.
Code
rede = nn.Sequential(nn.Linear(3, 2), nn.ReLU(), nn.Linear(2, 1) )with torch.no_grad(): # no_grad: we only want to compute the forward pass rede[0].weight.copy_(torch.tensor(W1)); rede[0].bias.copy_(torch.tensor(b1)) rede[2].weight.copy_(torch.tensor(W2)); rede[2].bias.copy_(torch.tensor(b2))saida_torch = rede(torch.tensor(x, dtype=torch.float32) )print(f"by hand: {y_hat[0]:.6f}")print(f"PyTorch: {saida_torch.item():.6f}")
The same idea, bigger: 784 pixels → 128 hidden neurons → 10 outputs (one for each digit).
The 10 outputs are called logits: arbitrary numbers, positive or negative. To turn them into probabilities that sum to 1, we use the softmax function:
\[p_k = \frac{e^{z_k}}{\sum_{j=0}^{9} e^{z_j}}\]
We use softmax here instead of sigmoid because with softmax the probabilities of all the outputs sum to 1. With sigmoid, each output would also be a probability in [0,1], but their sum could be greater than 1. Constraining the probabilities to sum to 1, we classify the result as the most probable of the 10 possible outputs [0,9].
The predicted digit is the one with the highest probability.
Code
modelo = nn.Sequential( nn.Flatten(), # (batch, 1, 28, 28) to (batch, 784) nn.Linear(784, 128), # hidden layer nn.ReLU(), # activation nn.Linear(128, 10), # output layer: 10 logits)print(modelo)print(f"\nTotal parameters: {sum(p.numel() for p in modelo.parameters()):,}")
Sequential(
(0): Flatten(start_dim=1, end_dim=-1)
(1): Linear(in_features=784, out_features=128, bias=True)
(2): ReLU()
(3): Linear(in_features=128, out_features=10, bias=True)
)
Total de parâmetros: 101,770
Code
# a batch with the first 8 imageslote = torch.stack([mnist[i][0] for i inrange(8)])rotulos = torch.tensor([mnist[i][1] for i inrange(8)])logits = modelo(lote)probs = torch.softmax(logits, dim=1)print(f"input: {tuple(lote.shape)} to logits: {tuple(logits.shape)}")print(f"sum of the probabilities for the 1st image: {probs[0].sum():.3f}")print(f"Probability of each digit for the 8 inputs:{probs}")print(f"true labels: {rotulos.tolist()}")print(f"predicted digits: {probs.argmax(dim=1).tolist()}")
With the weights still random, the network gives ~10% to each digit: it’s a well-defined function, but useless. Teaching the network to adjust these 101,770 parameters is the subject of the next class.
Why do we need activation functions?
What if we removed the ReLU? Two linear layers in a row are:
In other words, they collapse into a single linear layer. No matter how many linear layers you stack, the result is always equivalent to just one, and a linear layer can only draw straight boundaries. Let’s check:
Code
linear1, linear2 = nn.Linear(784, 128), nn.Linear(128, 10)W_colapsado = linear2.weight @ linear1.weight # (10, 128) @ (128, 784) = (10, 784)b_colapsado = linear2.weight @ linear1.bias + linear2.biasduas_camadas = linear2(linear1(lote.flatten(1)))uma_camada = lote.flatten(1) @ W_colapsado.T + b_colapsadoprint(f"W' has shape {tuple(W_colapsado.shape)}: a single 784 to 10 layer")print(f"Two layers without activation == one layer? {torch.allclose(duas_camadas, uma_camada, atol=1e-5)}")
W' tem formato (10, 784): uma única camada 784 p/ 10
Duas camadas sem ativação == uma camada? True
The activation function breaks this linearity. Placed between layers, it introduces non-linearity, and that’s what allows the network to learn complex relationships. The most common ones:
Function
Formula
Output
Use
ReLU
\(\max(0, z)\)
\([0, \infty)\)
the default in hidden layers: simple and fast
Sigmoid
\(\frac{1}{1 + e^{-z}}\)
\((0, 1)\)
output for binary classification (probability)
Tanh
\(\frac{e^{z} - e^{-z}}{e^{z} + e^{-z}}\)
\((-1, 1)\)
like the sigmoid, but centered at zero
Below are the functions and their derivatives (slopes). The derivatives will be essential in the next class, because they’re how the network learns. Here we use PyTorch itself to compute them (backward(), which we’ll see in detail in class 2).
Code
z = torch.linspace(-5, 5, 401, requires_grad=True)ativacoes = {"ReLU": torch.relu, "Sigmoide": torch.sigmoid, "Tanh": torch.tanh}fig, axes = plt.subplots(2, 3, figsize=(13, 6), sharex=True)for j, (nome, f) inenumerate(ativacoes.items()): z.grad =None saida = f(z) saida.sum().backward() # derivative at each point with respect to z axes[0, j].plot(z.detach(), saida.detach(), color=AZUL, lw=2.5) axes[0, j].set_title(nome) axes[1, j].plot(z.detach(), z.grad, color=LARANJA, lw=2.5) axes[1, j].set_xlabel("z")axes[0, 0].set_ylabel("f(z)")axes[1, 0].set_ylabel("derivative f'(z)")axes[1, 1].annotate("maximum = 0.25", xy=(0, 0.25), xytext=(1.5, 0.2), color=TINTA, arrowprops={"arrowstyle": "->", "color": TINTA})plt.tight_layout()plt.show()
A warning for the future: the vanishing gradient
Notice that the sigmoid’s derivative is at most 0.25. In the next class we’ll see that, during training, the derivatives of each layer are multiplied together (the chain rule). With 10 sigmoid layers, the signal reaching the first layers can be multiplied by as little as \(0.25^{10}\), less than one millionth. The first layers practically stop learning: this is the vanishing gradient problem. The ReLU’s derivative is 1 for positive inputs, which is why it became the default.
Code
camadas = np.arange(1, 11)fig, ax = plt.subplots(figsize=(8, 3.5))ax.plot(camadas, np.ones(len(camadas)), color=AZUL, lw=2, marker="o", label="ReLU (positive inputs): 1ⁿ")ax.plot(camadas, 0.25** camadas, color=LARANJA, lw=2, marker="o", label="sigmoid (best case): 0.25ⁿ")ax.set(yscale="log", xlabel="number of layers", ylabel="gradient multiplier", xticks=camadas, ylim=(3e-7, 5), title="How much of the gradient survives to the first layer?")ax.legend(frameon=False, loc="lower left")plt.show()
The Universal Approximation Theorem
A network with a single hidden layer and a non-linear activation can approximate any continuous function (on a bounded interval) as closely as desired, as long as it has enough neurons.
We won’t prove the theorem, but we’ll see it in action. We fit \(\sin(x)\) with \(1 \to n \to 1\) ReLU networks, for \(n\) = 2, 4, 16 and 128 neurons.
Each ReLU neuron contributes one bend (a straight segment). With few neurons the approximation is coarse, but with many neurons the bends become so small that the curve looks smooth.
How the network finds the right weights (the treina function below) is the subject of classes 2 and 3. For now, treat it as a black box.
The network’s output is the sum of the contributions of each hidden neuron: \(\hat{y} = \sum_i w_{2,i} \cdot \text{ReLU}(w_{1,i}\,x + b_{1,i}) + b_2\). Each term is a “ramp” that starts at a different point. Looking at the 4-neuron network:
Code
rede4 = redes_sen[4]with torch.no_grad(): h = torch.relu(rede4[0](x_sen)) # (400, 4): output of each hidden neuron contribuicoes = h * rede4[2].weight[0] # each neuron multiplied by its output weight soma = contribuicoes.sum(dim=1) + rede4[2].biasfig, ax = plt.subplots(figsize=(10, 4))cores = [AZUL, VERDE, "#e87ba4", "#4a3aa7"]for i inrange(4): ax.plot(x_sen, contribuicoes[:, i], color=cores[i], lw=1.5, ls="--", label=f"neuron {i +1}")ax.plot(x_sen, soma, color=LARANJA, lw=3, label="sum (network output)")ax.plot(x_sen, y_sen, color=CINZA, lw=4, alpha=0.4, label="sin(x)")ax.set(xlabel="x", ylabel="y", title="The output is a sum of ReLU ramps (4-neuron network)")ax.legend(frameon=False, loc="upper left", bbox_to_anchor=(1, 1))plt.tight_layout()plt.show()mortos = [i +1for i inrange(4) if h[:, i].max() ==0]print(f"Neurons that never activate on this interval: {mortos if mortos else'none'}")
Neurônios que nunca ativam neste intervalo: [1]
Each active neuron contributes a ramp that switches on at a different value of \(x\), and the sum of the ramps draws the curve. If a neuron stays at zero over the whole interval, it’s a dead neuron (dead ReLU): its input is always negative, the ReLU always returns zero and it doesn’t help at all. That’s why the 2-neuron network above can only make one bend. Dead neurons are a common side effect of ReLU; having spare neurons helps.
The big catch
The theorem guarantees that a set of weights approximating the function exists. It does not say:
how many neurons are needed (it could be a huge number);
how to find those weights;
whether the network will work well on data it has never seen.
This gap between “a solution exists” and “we can find it” is exactly what motivates training, the topic of the next class.
8. Discussion
A neural network is a function: inputs → matrix multiplications + activations → outputs.
A neuron is a weighted sum plus a bias; a layer is \(W\mathbf{x} + \mathbf{b}\); an MLP is stacked layers with activations between them.
Without activations, any number of layers collapses into one. Activations provide the non-linear power.
ReLU is the default in hidden layers; the sigmoid suffers from the vanishing gradient in deep networks.
With enough neurons, one hidden layer approximates any continuous function, but finding the weights is another story.
Exercises
Change the W1 weights in section 4 so that both hidden neurons are negative before the ReLU. What is the network’s output? Why?
Replace nn.ReLU() with nn.Tanh() in the networks that approximate \(\sin(x)\). Do the curves change?
Approximate another function, like \(|x|\) or \(x^2\), with 4 neurons. How many “bends” do you need for \(|x|\)?
How many parameters does a 784 → 256 → 128 → 10 MLP have? Check your math with sum(p.numel() for p in modelo.parameters()).