Skip to main content

Deep Learning 0

Introduction to PyTorch

Colab link

Open In Colab

Before building neural networks, we need to get to know the tool and the “material” they work with.

PyTorch is the most widely used deep learning library in research, and increasingly in industry. It offers three things:

  1. Tensors: multidimensional arrays, similar to NumPy’s, that also run on a GPU;
  2. Autograd: automatic computation of derivatives (we’ll see it in class 2);
  3. Ready-made neural network building blocks (torch.nn): layers, activation functions, losses, optimizers.

Plan for this class

  1. What a tensor is
  2. Dimensions: scalar, vector, matrix and beyond
  3. A 2D tensor and a 3D tensor in practice
  4. Images as tensors: binary (1 channel) and color (3 channels)
  5. The perceptron: the simplest neuron
  6. An MLP learning a degree-5 polynomial
Code
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle, Circle, FancyArrowPatch
import torch
import torch.nn as nn


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)
print(f"PyTorch {torch.__version__}")
print(f"GPU (CUDA) available? {torch.cuda.is_available()}")
PyTorch 2.14.1
GPU (CUDA) disponível? False

1. What is a tensor?

A tensor is a collection of numbers organized in a grid with any number of dimensions (also called axes). All data that goes into a neural network (a table, an image, a video, a time series) becomes a tensor, and all of the network’s weights are tensors too.

Creating a tensor is similar to creating a NumPy array:

Code
t = torch.tensor([[1.0, 2.0, 3.0],
                  [4.0, 5.0, 6.0]])
print(t)
print()
print(f"shape  (shape):              {t.shape}")
print(f"ndim   (no. of dimensions):  {t.ndim}")
print(f"numel  (no. of elements):    {t.numel()}")
print(f"dtype  (number type):        {t.dtype}")
print(f"device (where it lives):     {t.device}")
tensor([[1., 2., 3.],
        [4., 5., 6.]])

shape  (formato):            torch.Size([2, 3])
ndim   (nº de dimensões):    2
numel  (nº de elementos):    6
dtype  (tipo dos números):   torch.float32
device (onde está guardado): cpu

The four attributes you’ll check all the time:

Attribute What it tells you Why it matters
shape the size of each dimension most deep learning errors are shape mismatches
ndim how many dimensions scalar = 0, vector = 1, matrix = 2, …
dtype the number type (float32, int64, uint8, …) networks work with float32; class labels with int64
device cpu or cuda (GPU) two tensors can only be combined if they’re in the same place

Tensors and NumPy arrays convert easily:

Code
a = np.array([1, 2, 3])
t_de_numpy = torch.from_numpy(a)           # NumPy -> PyTorch
volta_para_numpy = t_de_numpy.numpy()      # PyTorch -> NumPy
print(t_de_numpy, type(t_de_numpy))
print(volta_para_numpy, type(volta_para_numpy))

# move to the GPU, if there is one (on Colab: Runtime → Change runtime type → GPU)
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"\ntensor on device: {t.to(device).device}")
tensor([1, 2, 3]) <class 'torch.Tensor'>
[1 2 3] <class 'numpy.ndarray'>

tensor no dispositivo: cpu

2. Dimensions: scalar, vector, matrix and beyond

The number of dimensions is the number of indices needed to reach a single number:

ndim Name Example shape Example data
0 scalar () today’s temperature
1 vector (4,) the 4 variables of one sample
2 matrix (3, 4) a table: 3 rows × 4 columns; a grayscale image
3 3D tensor (3, 3, 4) a color image (channels × height × width)
4 4D tensor (64, 3, 28, 28) a batch of 64 color images
Code
def desenha_grade(ax, valores, x0=0.0, y0=0.0, cor=AZUL, alpha=0.25, tamanho=1.0, texto=True):
    """Draws a matrix as a grid of cells, with the upper-left corner at (x0, y0)."""
    valores = np.atleast_2d(valores)
    linhas, colunas = valores.shape
    for i in range(linhas):
        for j in range(colunas):
            x, y = x0 + j * tamanho, y0 - (i + 1) * tamanho
            ax.add_patch(Rectangle((x, y), tamanho, tamanho, facecolor=cor, alpha=alpha, edgecolor=TINTA, lw=1))
            if texto:
                ax.text(x + tamanho / 2, y + tamanho / 2, f"{valores[i, j]:g}", ha="center", va="center",
                        color=TINTA, fontsize=10)

escalar = torch.tensor(7)
vetor = torch.tensor([3, 1, 4, 1])
matriz = torch.arange(12).reshape(3, 4)
tensor3d = torch.arange(36).reshape(3, 3, 4)

fig, axes = plt.subplots(1, 4, figsize=(17, 4.2), width_ratios=[0.6, 1.3, 1.3, 1.8])
desenha_grade(axes[0], escalar.numpy(), 0, 1, cor="#cde2fb", alpha=1)
desenha_grade(axes[1], vetor.numpy(), 0, 1, cor="#cde2fb", alpha=1)
desenha_grade(axes[2], matriz.numpy(), 0, 3, cor="#cde2fb", alpha=1)
for k, cor in zip(range(2, -1, -1), ["#bfe9d8", "#f9d0bf", "#cde2fb"]):   # draw from back to front
    desenha_grade(axes[3], tensor3d[k].numpy(), 0.6 * k, 3 + 0.6 * k, cor=cor, alpha=1, texto=(k == 0))

titulos = [f"Scalar (0D)\nshape {tuple(escalar.shape)}", f"Vector (1D)\nshape {tuple(vetor.shape)}",
           f"Matrix (2D)\nshape {tuple(matriz.shape)}", f"Tensor 3D\nshape {tuple(tensor3d.shape)}"]
limites = [(-0.3, 1.3, -0.3, 1.3), (-0.3, 4.3, -0.3, 1.3), (-0.3, 4.3, -0.3, 3.3), (-0.3, 5.7, -0.3, 4.6)]
for ax, titulo, (x0, x1, y0, y1) in zip(axes, titulos, limites):
    ax.set(xlim=(x0, x1), ylim=(y0, y1), title=titulo)
    ax.set_aspect("equal")
    ax.axis("off")
axes[2].annotate("", xy=(4.15, 0), xytext=(4.15, 3), arrowprops={"arrowstyle": "->", "color": TINTA})
axes[2].text(4.25, 1.5, "dim 0\n(rows)", va="center", fontsize=9, color=TINTA)
axes[2].annotate("", xy=(4, -0.2), xytext=(0, -0.2), arrowprops={"arrowstyle": "->", "color": TINTA})
axes[2].text(2, -0.45, "dim 1 (columns)", ha="center", va="top", fontsize=9, color=TINTA)
axes[3].text(2.8, 4.45, "dim 0: 3 stacked layers", ha="center", fontsize=9, color=TINTA)
plt.tight_layout()
plt.show()

3. 2D and 3D tensors in practice

A 2D tensor: a table

Imagine the maximum temperature (°C) of 3 cities over 4 days. Dimension 0 is the cities (rows) and dimension 1 is the days (columns).

Code
temperaturas = torch.tensor([[31.0, 29.5, 33.2, 30.1],    # Santos
                             [27.4, 26.8, 28.0, 25.9],    # São Paulo
                             [35.1, 34.7, 36.3, 35.8]])   # Cuiabá
print(f"shape: {tuple(temperaturas.shape)}  → 3 cities × 4 days\n")

print(f"temperaturas[0]       = {temperaturas[0]}   ← row 0: Santos, all 4 days")
print(f"temperaturas[:, 2]    = {temperaturas[:, 2]}   ← column 2: the 3 cities on day 3")
print(f"temperaturas[2, 3]    = {temperaturas[2, 3].item():.1f}                                 ← a single number: Cuiabá, day 4")
shape: (3, 4)  → 3 cidades × 4 dias

temperaturas[0]       = tensor([31.0000, 29.5000, 33.2000, 30.1000])   ← linha 0: Santos, os 4 dias
temperaturas[:, 2]    = tensor([33.2000, 28.0000, 36.3000])   ← coluna 2: as 3 cidades no 3º dia
temperaturas[2, 3]    = 35.8                                 ← um único número: Cuiabá, 4º dia

Many operations take a dim argument: it says which dimension disappears in the result.

  • dim=0 runs over the rows → result per column (mean of each day, across cities)
  • dim=1 runs over the columns → result per row (mean of each city, across days)
Code
temperaturas
tensor([[31.0000, 29.5000, 33.2000, 30.1000],
        [27.4000, 26.8000, 28.0000, 25.9000],
        [35.1000, 34.7000, 36.3000, 35.8000]])
Code
print(f"mean per day     (dim=0): {temperaturas.mean(dim=0)}   shape {tuple(temperaturas.mean(dim=0).shape)}")
print(f"mean per city    (dim=1): {temperaturas.mean(dim=1)}          shape {tuple(temperaturas.mean(dim=1).shape)}")
print(f"overall mean:             {temperaturas.mean():.2f}                          shape {tuple(temperaturas.mean().shape)}")
média por dia    (dim=0): tensor([31.1667, 30.3333, 32.5000, 30.6000])   shape (4,)
média por cidade (dim=1): tensor([30.9500, 27.0250, 35.4750])          shape (3,)
média geral:              31.15                          shape ()

A 3D tensor: several stacked tables

Now the temperature of the 3 cities over 4 days, for 2 weeks. We just stack two tables: the new dimension 0 is the weeks.

Code
semana2 = temperaturas + torch.randn(3, 4)          # week 2: similar values with noise
duas_semanas = torch.stack([temperaturas, semana2])  # stack along a new dimension 0
print(f"shape: {tuple(duas_semanas.shape)}  → 2 weeks × 3 cities × 4 days\n")

print(f"duas_semanas[1].shape        = {tuple(duas_semanas[1].shape)}    the whole of week 2 (a table)")
print(f"duas_semanas[:, 0].shape     = {tuple(duas_semanas[:, 0].shape)}    Santos over the 2 weeks")
print(f"duas_semanas[1, 2, 0]        = {duas_semanas[1, 2, 0]:.1f}      Cuiabá, week 2, day 1")
print(f"mean per week (dim=(1,2))    = {duas_semanas.mean(dim=(1, 2))}")
shape: (2, 3, 4)  → 2 semanas × 3 cidades × 4 dias

duas_semanas[1].shape        = (3, 4)    a 2ª semana inteira (uma tabela)
duas_semanas[:, 0].shape     = (2, 4)    Santos nas 2 semanas
duas_semanas[1, 2, 0]        = 36.5      Cuiabá, 2ª semana, 1º dia
média por semana (dim=(1,2)) = tensor([31.1500, 31.3599])

Changing the shape without changing the data is very common. reshape rearranges the same numbers into another grid; flatten squashes everything into a vector. The only rule: the total number of elements doesn’t change.

Code
x = torch.arange(24)
print(f"original:          {tuple(x.shape)}")
print(f"reshape(2, 3, 4):  {tuple(x.reshape(2, 3, 4).shape)}")
print(f"reshape(6, -1):    {tuple(x.reshape(6, -1).shape)}")
print(f"flatten of (2,3,4): {tuple(x.reshape(2, 3, 4).flatten().shape)}")
original:          (24,)
reshape(2, 3, 4):  (2, 3, 4)
reshape(6, -1):    (6, 4)
flatten de (2,3,4): (24,)

4. Images as tensors

Binary image, 1 channel

A black-and-white image is a matrix of pixels: 1 = pixel on, 0 = off. In PyTorch, images follow the (C, H, W) convention: channels, height, width. A binary image has 1 channel, so its shape is (1, H, W).

Let’s draw a digit “7” by hand on an 8 × 8 grid:

Code
sete = torch.tensor([[0, 0, 0, 0, 0, 0, 0, 0],
                     [0, 1, 1, 1, 1, 1, 1, 0],
                     [0, 0, 0, 0, 0, 1, 1, 0],
                     [0, 0, 0, 0, 1, 1, 0, 0],
                     [0, 0, 0, 1, 1, 0, 0, 0],
                     [0, 0, 0, 1, 1, 0, 0, 0],
                     [0, 0, 1, 1, 0, 0, 0, 0],
                     [0, 0, 0, 0, 0, 0, 0, 0]], dtype=torch.float32).unsqueeze(0)   # (8, 8) → (1, 8, 8)

print(f"shape: {tuple(sete.shape)}  (channels, height, width)")
print(f"unique values: {sete.unique().tolist()}")

fig, axes = plt.subplots(1, 2, figsize=(10, 4.5))
axes[0].imshow(sete[0], cmap="gray_r", vmin=0, vmax=1)
axes[0].set_title("how we see it")
for i in range(8):
    for j in range(8):
        v = int(sete[0, i, j])
        axes[1].add_patch(Rectangle((j, 7 - i), 1, 1, facecolor=TINTA if v else "white", edgecolor=CINZA))
        axes[1].text(j + 0.5, 7.5 - i, v, ha="center", va="center", color="white" if v else TINTA)
axes[1].set(xlim=(0, 8), ylim=(0, 8), title="how the computer sees it: sete[0]")
axes[1].set_aspect("equal")
for ax in axes:
    ax.set_xticks([]); ax.set_yticks([]); ax.grid(False)
axes[0].axis("off")
plt.tight_layout()
plt.show()
shape: (1, 8, 8)  (canais, altura, largura)
valores únicos: [0.0, 1.0]

Color image, 3 channels (RGB)

A color image has 3 channels: red (R), green (G) and blue (B). Each channel is a matrix with the intensity of that color, from 0 to 1. The shape is (3, H, W): a 3D tensor. The color of each pixel is the mix of the three channels: red + green = yellow, all three at maximum = white.

Let’s build an 8 × 8 image with four colored squares:

Code
rgb = torch.zeros(3, 8, 8)            # (channels, height, width), all black
rgb[0, :4, :4] = 1.0                  # top-left corner: red only                   red
rgb[1, :4, 4:] = 1.0                  # top-right corner: green only               green
rgb[2, 4:, :4] = 1.0                  # bottom-left corner: blue only               yellow
rgb[1, 4:, 4:] = 1.0
rgb[:, 3:5, 3:5] = 1.0                # center: all three channels at maximum      white

print(f"shape: {tuple(rgb.shape)}   (channels, height, width)")

fig, axes = plt.subplots(1, 4, figsize=(15, 4))
for ax, c, nome, cmap in zip(axes, range(3), ["R channel (red)", "G channel (green)", "B channel (blue)"],
                             ["Reds", "Greens", "Blues"]):
    ax.imshow(rgb[c], cmap=cmap, vmin=0, vmax=1)
    ax.set_title(f"{nome}\nrgb[{c}], shape {tuple(rgb[c].shape)}")
# matplotlib expects (H, W, C): permute reorders the dimensions
axes[3].imshow(rgb.permute(1, 2, 0))
axes[3].set_title(f"combined image\nrgb.permute(1, 2, 0), shape {tuple(rgb.permute(1, 2, 0).shape)}")
for ax in axes:
    ax.set_xticks([]); ax.set_yticks([]); ax.grid(False)
plt.tight_layout()
plt.show()
shape: (3, 8, 8)   (canais, altura, largura)

Notice the permute(1, 2, 0): PyTorch stores images as (C, H, W), but matplotlib (and NumPy, OpenCV, PIL…) expects (H, W, C). Reordering dimensions is one of the most common everyday operations.

Batches of images: 4 dimensions

Neural networks process several images at once, in a batch. Stacking images adds one more dimension at the front: (N, C, H, W). A satellite image with 13 bands (Sentinel-2) would be (13, H, W), and a batch of 16 of them (16, 13, H, W): the same idea, just with more channels.

Code
lote = torch.stack([rgb, rgb.flip(dims=[2]), rgb.flip(dims=[1]), 1 - rgb])   # 4 variations of the image
print(f"batch shape: {tuple(lote.shape)}  → (images, channels, height, width)")

fig, axes = plt.subplots(1, 4, figsize=(10, 2.8))
for i, (ax, titulo) in enumerate(zip(axes, ["original", "mirrored", "upside down", "inverted colors"])):
    ax.imshow(lote[i].permute(1, 2, 0))
    ax.set_title(f"lote[{i}]: {titulo}", fontsize=10)
    ax.set_xticks([]); ax.set_yticks([]); ax.grid(False)
plt.tight_layout()
plt.show()
shape do lote: (4, 3, 8, 8)  → (imagens, canais, altura, largura)

5. The perceptron: the simplest neuron

The perceptron (Rosenblatt, 1958) is the ancestor of all neural networks. It:

  1. receives inputs \(x_1, x_2, \dots\);
  2. multiplies each one by a weight \(w_i\) and sums them, plus a bias \(b\): \(z = w_1x_1 + w_2x_2 + b\);
  3. applies an activation function. In the original perceptron, a step: the output is 1 if \(z > 0\), otherwise 0.
Code
fig, ax = plt.subplots(figsize=(11, 4.5))

def seta(xy_de, xy_para, texto=None, pos=0.5, desloc=(0, 0.15)):
    ax.add_patch(FancyArrowPatch(xy_de, xy_para, arrowstyle="-|>", mutation_scale=15, color=CINZA, lw=1.5))
    if texto:
        xm = xy_de[0] + pos * (xy_para[0] - xy_de[0]) + desloc[0]
        ym = xy_de[1] + pos * (xy_para[1] - xy_de[1]) + desloc[1]
        ax.text(xm, ym, texto, ha="center", color=LARANJA, fontsize=13)

entradas = {"x₁": (0.5, 3.0), "x₂": (0.5, 1.0)}
for nome, (x, y) in entradas.items():
    ax.add_patch(Circle((x, y), 0.35, color=AZUL))
    ax.text(x, y, nome, ha="center", va="center", color="white", fontsize=14)
ax.add_patch(Circle((0.5, -0.6), 0.3, color=CINZA, alpha=0.4))
ax.text(0.5, -0.6, "1", ha="center", va="center", color=TINTA, fontsize=12)

soma = (4.0, 1.5)
ax.add_patch(Circle(soma, 0.6, color=VERDE))
ax.text(*soma, "Σ", ha="center", va="center", color="white", fontsize=22)
seta((0.85, 3.0), (3.45, 1.75), "w₁", pos=0.4, desloc=(0, 0.25))
seta((0.85, 1.0), (3.4, 1.4), "w₂", pos=0.4, desloc=(0, 0.15))
seta((0.8, -0.6), (3.5, 1.15), "b", pos=0.4, desloc=(0, -0.35))

ax.add_patch(Rectangle((5.6, 0.95), 1.5, 1.1, facecolor="white", edgecolor=TINTA, lw=1.5))
xs = np.linspace(5.75, 6.95, 50)
ax.plot(xs, np.where(xs > 6.35, 1.8, 1.2), color=TINTA, lw=2)
ax.text(6.35, 0.7, "step", ha="center", va="top", color=TINTA)
seta((4.6, 1.5), (5.6, 1.5))
ax.text(5.1, 1.75, "z", ha="center", color=TINTA, fontsize=13)

ax.add_patch(Circle((8.6, 1.5), 0.4, color=LARANJA))
ax.text(8.6, 1.5, "ŷ", ha="center", va="center", color="white", fontsize=15)
seta((7.1, 1.5), (8.2, 1.5))

ax.text(4.0, -0.9, "z = w₁x₁ + w₂x₂ + b", ha="center", color=TINTA, fontsize=12)
ax.text(8.6, 0.8, "ŷ = 1 if z > 0\nŷ = 0 otherwise", ha="center", va="top", color=TINTA, fontsize=11)
ax.set(xlim=(-0.2, 9.8), ylim=(-1.5, 3.7))
ax.set_aspect("equal")
ax.axis("off")
ax.set_title("The perceptron")
plt.show()

A perceptron that computes logical “AND”

With the right weights, a perceptron implements the AND logic gate: the output is 1 only when both inputs are 1. With \(w_1 = w_2 = 1\) and \(b = -1.5\):

\(x_1\) \(x_2\) \(z = x_1 + x_2 - 1.5\) \(\hat{y}\)
0 0 −1.5 0
0 1 −0.5 0
1 0 −0.5 0
1 1 +0.5 1
Code
class Perceptron(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(2, 1)                 # z = w·x + b

    def forward(self, x):
        z = self.linear(x)
        return (z > 0).float()                        # step

perceptron = Perceptron()
with torch.no_grad():                                  # set the weights by hand (no training)
    perceptron.linear.weight.copy_(torch.tensor([[1.0, 1.0]]))
    perceptron.linear.bias.copy_(torch.tensor([-1.5]))

entradas_and = torch.tensor([[0.0, 0.0], [0.0, 1.0], [1.0, 0.0], [1.0, 1.0]])
saidas = perceptron(entradas_and)
for x, y in zip(entradas_and, saidas):
    print(f"x = {x.tolist()}  →  ŷ = {int(y.item())}")
x = [0.0, 0.0]  →  ŷ = 0
x = [0.0, 1.0]  →  ŷ = 0
x = [1.0, 0.0]  →  ŷ = 0
x = [1.0, 1.0]  →  ŷ = 1

Geometrically, the perceptron draws a line (\(w_1x_1 + w_2x_2 + b = 0\)) and classifies each point by the side it falls on:

Code
g1, g2 = torch.meshgrid(torch.linspace(-0.5, 1.5, 300), torch.linspace(-0.5, 1.5, 300), indexing="xy")
grade = torch.stack([g1.flatten(), g2.flatten()], dim=1)
with torch.no_grad():
    regioes = perceptron(grade).reshape(300, 300)

fig, ax = plt.subplots(figsize=(5.5, 5))
ax.contourf(g1, g2, regioes, levels=[-0.5, 0.5, 1.5], colors=[AZUL, LARANJA], alpha=0.15)
ax.plot([-0.5, 1.5], [2.0, 0.0], color=TINTA, lw=2, label="boundary: x₁ + x₂ − 1.5 = 0")
for x, y in zip(entradas_and, saidas):
    ax.scatter(*x, s=250, color=LARANJA if y else AZUL, edgecolor="white", lw=2, zorder=3)
    ax.annotate(f"ŷ = {int(y)}", x, xytext=(12, -14), textcoords="offset points", color=TINTA)
ax.set(xlim=(-0.5, 1.5), ylim=(-0.5, 1.5), xlabel="x₁", ylabel="x₂", title="Perceptron computing x₁ AND x₂")
ax.set_aspect("equal")
ax.legend(frameon=False, loc="upper right")
plt.show()

A single line is also the perceptron’s limit: it can only separate classes that a line can separate. More complicated problems require several layers of neurons, with non-linear activations between them: an MLP (Multi-Layer Perceptron).

6. An MLP learning a degree-5 polynomial

Let’s give the MLP a task that no line can solve: learning the curve of a degree-5 polynomial,

\[p(x) = x^5 - 5x^3 + 4x = x(x^2 - 1)(x^2 - 4)\]

which crosses zero 5 times. But the network doesn’t know the formula: it only sees 200 noisy \((x, y)\) points, as if they were measurements. The network has 1 input (\(x\)), two hidden layers of 32 neurons and 1 output (\(\hat{y}\)).

Code
def desenha_mlp(ax, camadas, rotulos, titulo):
    xs = np.linspace(0, 1, len(camadas))
    pos = []
    for x, n_neur in zip(xs, camadas):
        ys = np.linspace(0.5 - 0.09 * (n_neur - 1), 0.5 + 0.09 * (n_neur - 1), n_neur)
        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=0.6, alpha=0.6, 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=260, color=cor, zorder=2, edgecolor="white", lw=1.5)
    for x, r in zip(xs, rotulos):
        ax.text(x, -0.25, r, ha="center", va="top", color=TINTA, fontsize=10)
    ax.set(xlim=(-0.12, 1.12), ylim=(-0.5, 1.25), title=titulo)
    ax.axis("off")

fig, ax = plt.subplots(figsize=(8, 4))
desenha_mlp(ax, [1, 8, 8, 1], ["input\nx", "hidden layer 1\n32 neurons + ReLU",
                               "hidden layer 2\n32 neurons + ReLU", "output\nŷ"],
            "MLP 1 → 32 → 32 → 1 (drawn with 8 neurons per layer)")
plt.show()

Code
def polinomio(x):
    return x ** 5 - 5 * x ** 3 + 4 * x

torch.manual_seed(0)
x_dados = torch.rand(200, 1) * 4.4 - 2.2                     # 200 random points in [-2.2, 2.2]
y_dados = polinomio(x_dados) + 0.5 * torch.randn(200, 1)     # noisy measurements
x_curva = torch.linspace(-2.2, 2.2, 400).unsqueeze(1)

mlp = nn.Sequential(
    nn.Linear(1, 32), nn.ReLU(),
    nn.Linear(32, 32), nn.ReLU(),
    nn.Linear(32, 1),
)
print(mlp)
print(f"parameters: {sum(p.numel() for p in mlp.parameters()):,}")
Sequential(
  (0): Linear(in_features=1, out_features=32, bias=True)
  (1): ReLU()
  (2): Linear(in_features=32, out_features=32, bias=True)
  (3): ReLU()
  (4): Linear(in_features=32, out_features=1, bias=True)
)
parâmetros: 1,153

The training below uses pieces we’ll see in detail in the next classes: a loss that measures the error (class 2), backward(), which computes how to adjust each weight (class 2), and an optimizer that applies the adjustment (class 3). For now, just look at the result: we save the network’s curve at a few moments during training.

Code
otimizador = torch.optim.Adam(mlp.parameters(), lr=0.01)
momentos = [0, 50, 200, 2000]
curvas, perdas = {}, []

for passo in range(2001):
    if passo in momentos:
        with torch.no_grad():
            curvas[passo] = mlp(x_curva).clone()
    otimizador.zero_grad()
    perda = ((mlp(x_dados) - y_dados) ** 2).mean()   # mean squared error
    perda.backward()
    otimizador.step()
    perdas.append(perda.item())

print(f"mean squared error: start = {perdas[0]:.2f}   end = {perdas[-1]:.3f}  (the noise alone gives ≈ 0.25)")
erro quadrático médio: início = 4.82   final = 0.233  (o ruído sozinho dá ≈ 0,25)
Code
fig, axes = plt.subplots(1, 4, figsize=(17, 4), sharey=True)
for ax, passo in zip(axes, momentos):
    ax.scatter(x_dados, y_dados, s=10, color=CINZA, alpha=0.6, label="data (noisy)")
    ax.plot(x_curva, polinomio(x_curva), color=AZUL, lw=2, ls="--", label="true polynomial")
    ax.plot(x_curva, curvas[passo], color=LARANJA, lw=2.5, label="MLP")
    ax.set(title=f"step {passo}", xlabel="x", ylim=(-10, 10))
axes[0].set_ylabel("y")
axes[0].legend(frameon=False, loc="lower right", fontsize=8)
plt.suptitle("The MLP learning p(x) = x⁵ − 5x³ + 4x from data", y=1.03)
plt.tight_layout()
plt.show()

fig, ax = plt.subplots(figsize=(8, 3))
ax.plot(perdas, color=LARANJA, lw=2)
ax.set(yscale="log", xlabel="training step", ylabel="error (log scale)", title="The error drops during training")
plt.show()

At step 0 the network, with random weights, is practically a straight line. As training goes on it “bends” the curve until it follows the polynomial, without ever having seen the formula: only the points. That’s what a neural network does: it learns a function from examples.

Notice also that the final curve is made of small straight segments: each ReLU neuron contributes one “bend”. In class 1 we’ll see why this works.

7. Summary

  • Tensor = a grid of numbers with any number of dimensions. Key attributes: shape, ndim, dtype, device.
  • Scalar (0D) → vector (1D) → matrix (2D) → 3D tensor → 4D… In operations like mean(dim=...), dim says which dimension disappears.
  • Images in PyTorch are (C, H, W): 1 channel (gray/binary) or 3 channels (RGB). Batches of images are (N, C, H, W). For matplotlib, use permute(1, 2, 0).
  • The perceptron computes a weighted sum plus a bias and applies a step: it separates classes with a line.
  • An MLP stacks layers of neurons with non-linear activations and learns complex curves from data.

Exercises

  1. Create a tensor with shape (2, 3, 4, 5). How many elements does it have? What is the shape of t.mean(dim=1)?
  2. Draw your own digit (for example a “1” or a “4”) on an 8 × 8 grid and show it with imshow.
  3. In the RGB image, paint the center magenta (red + blue). Which channels do you need to turn on?
  4. Change the perceptron’s bias to \(b = -0.5\). Which logic gate does it compute now?
  5. In the MLP, replace the polynomial with \(\sin(3x)\) and shrink the network to 1 → 8 → 1. Can the network still learn?