Skip to main content

Deep Learning 1

Neural Networks and MLPs

Colab link

Open In Colab

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

  1. This week’s example: images of handwritten digits (MNIST)
  2. The neuron: weighted sum + bias
  3. The layer: a matrix multiplication, \(y = Wx + b\)
  4. The forward pass by hand and in PyTorch
  5. A real network applied to MNIST
  6. Why we need activation functions
  7. 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.

Code
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from torchvision import datasets, transforms


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.random.seed(42)
np.set_printoptions(precision=3, suppress=True)
torch.__version__
'2.14.1'

The MNIST dataset

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
Code
imagem.
torch.Size([1, 28, 28])
Code
fig, axes = plt.subplots(3, 8, figsize=(12, 5))
for ax, i in zip(axes.flat, range(24)):
    img, y = mnist[i]
    ax.imshow(img[0], cmap="gray_r")
    ax.set_title(str(y), color=TINTA)
    ax.axis("off")
plt.suptitle(" MNIST Dataset")
plt.tight_layout()
plt.show()

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 images
print(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\):

\[z = w_1 x_1 + w_2 x_2 + \dots + w_n x_n + b = \mathbf{w} \cdot \mathbf{x} + 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 in zip(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 in zip(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 in zip(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 in zip(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 input
b = 0.1                           # bias

for i in range(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 + b

print(f"\nz = sum + b = {(w * x).sum():+.2f} {b:+.1f} = {z:+.2f}")
w1·x1 = +0.4 × 0.9 = +0.36
w2·x2 = -0.6 × 0.3 = -0.18
w3·x3 = +0.9 × 0.6 = +0.54

z = soma + b = +0.72 +0.1 = +0.82

Adding more neurons

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 2
b = np.array([0.1, -0.2])

y = W @ x + b
print(f"W: {W.shape}, x: {x.shape}, b: {b.shape}  →  y: {y.shape}")
print(f"y = {y}")
W: (2, 3), x: (3,), b: (2,)  →  y: (2,)
y = [ 0.82 -0.11]
Code
fig, ax = plt.subplots(figsize=(5, 3))
desenha_rede([3, 2], ax, ["inputs x", "neuron z"], "2 neurons with 3 inputs")
plt.show()

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()):,}")
pesos W: (128, 784)   viés b: (128,)
parâmetros: 100,352 pesos + 128 vieses = 100,480

4. The forward pass

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:

\[\mathbf{h} = \text{ReLU}(W_1\mathbf{x} + \mathbf{b}_1) \qquad \hat{y} = W_2\mathbf{h} + b_2\]

\(\text{ReLU}(z) = \max(0, z)\) is an activation function: it zeroes out negative values. In section 6 we’ll see why it’s indispensable.

Code
fig, ax = plt.subplots(figsize=(6, 3.5))
desenha_rede([3, 2, 1], ax, ["input x (3)", "hidden layer h (2)", "output ŷ (1)"], "MLP 3 - 2 - 1")
plt.show()

Code
x = np.array([0.9, 0.3, 0.6])
W1 = np.array([[0.4, -0.6, 0.9],
               [-0.3, 0.2, 0.5]])
b1 = np.array([0.1, -0.2])
W2 = np.array([[1.5, -2.0]])
b2 = np.array([0.3])

z1 = W1 @ x + b1
h = np.maximum(0, z1)          # ReLU
y_hat = W2 @ h + b2

print(f"1) z1 = W1·x + b1      = {z1}")
print(f"2) h  = ReLU(z1)        = {h}")
print(f"3) ŷ  = W2·h + b2       = {y_hat}")
1) z1 = W1·x + b1      = [ 0.82 -0.11]
2) h  = ReLU(z1)        = [0.82 0.  ]
3) ŷ  = W2·h + b2       = [1.53]

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}")
à mão:   1.530000
PyTorch: 1.530000
Code
rede.parameters
<bound method Module.parameters of Sequential(
  (0): Linear(in_features=3, out_features=2, bias=True)
  (1): ReLU()
  (2): Linear(in_features=2, out_features=1, bias=True)
)>

An MLP for MNIST

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 images
lote = torch.stack([mnist[i][0] for i in range(8)])
rotulos = torch.tensor([mnist[i][1] for i in range(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()}")
entrada: (8, 1, 28, 28) p/ logits: (8, 10)
soma das probabilidades da 1ª imagem: 1.000
Probabilidade de cada dígito para as 8 entradas:tensor([[0.0897, 0.1027, 0.1016, 0.1079, 0.0843, 0.0978, 0.1086, 0.0963, 0.1120,
         0.0991],
        [0.0868, 0.1159, 0.0995, 0.1092, 0.0786, 0.0848, 0.1176, 0.1049, 0.1114,
         0.0913],
        [0.0913, 0.1105, 0.1072, 0.1195, 0.0839, 0.0965, 0.1022, 0.0938, 0.1010,
         0.0941],
        [0.0892, 0.1078, 0.1013, 0.1123, 0.0871, 0.0977, 0.1103, 0.0984, 0.1019,
         0.0940],
        [0.0897, 0.1212, 0.1012, 0.1145, 0.0814, 0.1005, 0.1030, 0.0937, 0.1042,
         0.0905],
        [0.0937, 0.1094, 0.1014, 0.1220, 0.0818, 0.0972, 0.1093, 0.0952, 0.0990,
         0.0911],
        [0.0967, 0.1077, 0.0940, 0.1083, 0.0906, 0.0930, 0.1107, 0.1002, 0.1071,
         0.0917],
        [0.0947, 0.1113, 0.1132, 0.1245, 0.0751, 0.0861, 0.1055, 0.1012, 0.0989,
         0.0895]], grad_fn=<SoftmaxBackward0>)
rótulos reais:     [5, 0, 4, 1, 9, 2, 1, 3]
dígitos previstos: [8, 6, 3, 3, 1, 3, 6, 3]
Code
fig, axes = plt.subplots(1, 2, figsize=(11, 3.5), width_ratios=[1, 3])
axes[0].imshow(lote[0, 0], cmap="gray_r")
axes[0].set_title(f"true label: {rotulos[0].item()}")
axes[0].axis("off")
axes[1].bar(range(10), probs[0].detach(), color=AZUL, width=0.6)
axes[1].axhline(0.1, color=CINZA, ls="--", lw=1, label="random guess (10%)")
axes[1].set(xticks=range(10), xlabel="digit", ylabel="probability", ylim=(0, 0.3),
            title="What the (untrained) network thinks it is")
axes[1].legend(frameon=False)
axes[1].grid(axis="x", visible=False)
plt.tight_layout()
plt.show()

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:

\[W_2(W_1\mathbf{x} + \mathbf{b}_1) + \mathbf{b}_2 = \underbrace{(W_2W_1)}_{W'}\mathbf{x} + \underbrace{(W_2\mathbf{b}_1 + \mathbf{b}_2)}_{\mathbf{b}'}\]

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.bias

duas_camadas = linear2(linear1(lote.flatten(1)))
uma_camada = lote.flatten(1) @ W_colapsado.T + b_colapsado

print(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) in enumerate(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.

Code
x_sen = torch.linspace(-2 * np.pi, 2 * np.pi, 400).unsqueeze(1)   # (400, 1)
y_sen = torch.sin(x_sen)

def treina(rede, x, y, passos=4000):
    """fits the network's weights so that rede(x) ≈ y."""
    otimizador = torch.optim.Adam(rede.parameters(), lr=0.01)
    for _ in range(passos):
        otimizador.zero_grad()
        perda = ((rede(x) - y) ** 2).mean()
        perda.backward()
        otimizador.step()
    return perda.item()

redes_sen = {}
for n_neuronios in [2, 4, 16, 128]:
    torch.manual_seed(0)
    rede = nn.Sequential(nn.Linear(1, n_neuronios), nn.ReLU(), nn.Linear(n_neuronios, 1))
    erro = treina(rede, x_sen, y_sen)
    redes_sen[n_neuronios] = rede
    print(f"{n_neuronios:>4} neurons: mean squared error = {erro:.4f}")
   2 neurônios: erro quadrático médio = 0.3893
   4 neurônios: erro quadrático médio = 0.1409
  16 neurônios: erro quadrático médio = 0.0033
 128 neurônios: erro quadrático médio = 0.0016
Code
fig, axes = plt.subplots(1, 4, figsize=(16, 3.8), sharey=True)
for ax, (n_neuronios, rede) in zip(axes, redes_sen.items()):
    with torch.no_grad():
        ax.plot(x_sen, y_sen, color=CINZA, lw=4, alpha=0.5, label="sin(x)")
        ax.plot(x_sen, rede(x_sen), color=LARANJA, lw=2, label="network")
    ax.set(title=f"{n_neuronios} neurons", xlabel="x")
axes[0].set_ylabel("y")
axes[0].legend(frameon=False, loc="lower left")
plt.suptitle("One ReLU hidden layer approximating sin(x)", y=1.03)
plt.tight_layout()
plt.show()

Where do the “bends” come from?

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].bias

fig, ax = plt.subplots(figsize=(10, 4))
cores = [AZUL, VERDE, "#e87ba4", "#4a3aa7"]
for i in range(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 + 1 for i in range(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

  1. Change the W1 weights in section 4 so that both hidden neurons are negative before the ReLU. What is the network’s output? Why?
  2. Replace nn.ReLU() with nn.Tanh() in the networks that approximate \(\sin(x)\). Do the curves change?
  3. Approximate another function, like \(|x|\) or \(x^2\), with 4 neurons. How many “bends” do you need for \(|x|\)?
  4. How many parameters does a 784 → 256 → 128 → 10 MLP have? Check your math with sum(p.numel() for p in modelo.parameters()).