Neural Networks (and more!) with PyTorchRedes Neurais (e mais!) com PyTorch

Victor Coscrato

Introduction: What is PyTorch?Introdução: O que é PyTorch?

What is PyTorch?O que é PyTorch?

  • A high-performance numerical computing library for Python.Uma biblioteca de computação numérica de alto desempenho para Python.
  • It was born at Facebook’s AI Research lab (FAIR), to be more flexible than the frameworks of the time.Nasceu no laboratório de pesquisa em IA do Facebook (FAIR), para ser mais flexível que os frameworks da época.
  • It has been open source since its release in 2016, and that helped a lot: the community adopted it quickly and started contributing.É open source desde o lançamento, em 2016, e isso ajudou muito: a comunidade adotou rápido e passou a contribuir.
  • In 2022, Meta handed the project over to the PyTorch Foundation (under the Linux Foundation), and today several companies take part in running it.Em 2022, a Meta passou o projeto para a PyTorch Foundation (da Linux Foundation), e hoje várias empresas participam da gestão.
  • It popularized dynamic computation graphs, which we will see in a moment.Popularizou os grafos de computação dinâmicos, que vamos ver daqui a pouco.

Why PyTorch?Por que PyTorch?

  • Automatic differentiation (autograd) computes the gradient of any function you define on its own. No more deriving complicated loss functions by hand, which is tedious and easy to get wrong.A diferenciação automática (autograd) calcula sozinha o gradiente de qualquer função que você definir. Nada de derivar funções de perda complicadas à mão, o que é chato e fácil de errar.
  • With GPU acceleration, operations on tensors (multidimensional arrays, like NumPy’s) run in parallel. To train deep networks in a reasonable time, this is essential.Com aceleração por GPU, as operações com tensores (arrays multidimensionais, como os do NumPy) rodam em paralelo. Para treinar redes profundas em tempo razoável, isso é essencial.
  • It is flexible: it is hard to think of a parametric model that cannot be implemented in PyTorch.É flexível: é difícil (ou impossível) pensar num modelo paramétrico que não dê para implementar em PyTorch.

Tip

Think of PyTorch as NumPy with “superpowers”.Vale pensar no PyTorch como um NumPy com “superpoderes”.

Why PyTorch?Por que PyTorch?

  • It is mature and stable, with a large, active community.É madura e estável, com uma comunidade grande e ativa.
  • It dominates academic research: 80% of NeurIPS 2023 papers use PyTorch.Domina a pesquisa acadêmica: 80% dos artigos do NeurIPS 2023 usam PyTorch.
  • One thing feeds the other: the more people use it, the more libraries, tutorials and pretrained models appear, and the more people start using it.Uma coisa puxa a outra: quanto mais gente usa, mais aparecem bibliotecas, tutoriais e modelos prontos, e mais gente passa a usar.

Examples - Computer VisionExemplos - Computer Vision

Source: demo video fromFonte: vídeo de demonstração da Ultralytics.

Examples - Generative AIExemplos - IA Generativa

gemini chatgpt claude

Examples - Reinforcement LearningExemplos - Reinforcement Learning

Source: thumbnail fromFonte: thumbnail de GothamChess (YouTube).

OK, but why should I care?Tá, mas e eu com isso?

Tip

Even if you don’t plan to train deep neural networks, PyTorch can help you – a lot.Mesmo que você não pretenda treinar redes neurais profundas, o PyTorch pode te ajudar, e muito.

Important

This course will cover not only neural networks, but also everyday probabilistic and statistical applications.Este curso abordará não apenas redes neurais, mas também aplicações probabilísticas e estatísticas cotidianas.

Part 1: PyTorch BasicsParte 1: Conceitos Básicos de PyTorch

TensorsTensores

  • The fundamental data unit in PyTorch. Analogous to NumPy’s ndarrays, but with gradients and GPU support.A unidade de dados no PyTorch. Análogo aos ndarrays do NumPy, mas com gradientes e GPU.
  • A tensor has essential attributes:Um tensor possui atributos essenciais:
    • shape: the dimensionality of the tensor (e.g., scalar, vector, matrix).shape: a dimensionalidade do tensor (e.g., escalar, vetor, matriz).
    • dtype: the data type (torch.float32, torch.long, etc.).dtype: o tipo de dados (torch.float32, torch.long, etc.).
    • device: where the tensor is allocated in memory (cpu or cuda).device: onde o tensor está alocado na memória (cpu ou cuda).

TensorsTensores

# Creating tensors in various ways
x = torch.tensor([[1, 2], [3, 4]], dtype=torch.float32)
print(f"Tensor from list:\n{x}\n")

# Attributes
print(f"Shape: {x.shape}")
print(f"Data type: {x.dtype}")
print(f"Device: {x.device}\n")

# Interoperability with NumPy (they share the same memory on CPU)
a_np = np.array([5, 6, 7])
a_pt = torch.from_numpy(a_np)
print(f"Tensor from NumPy: {a_pt}")
a_pt[0] = 99
print(f"Original NumPy was modified: {a_np}")
Tensor from list:
tensor([[1., 2.],
        [3., 4.]])

Shape: torch.Size([2, 2])
Data type: torch.float32
Device: cpu

Tensor from NumPy: tensor([5, 6, 7])
Original NumPy was modified: [99  6  7]

Tensor OperationsOperações com Tensores

The syntax is familiar to NumPy users.A sintaxe é familiar para quem usa NumPy.

x = torch.tensor([[1., 2.], [3., 4.]])
y = torch.tensor([[5., 6.], [7., 8.]])

# Element-wise operations
print("Sum:", x + y)
print("Product (Hadamard):", x * y)

# Matrix multiplication
print("Matrix Product (@):", x @ y)
print("Matrix Product (matmul):", torch.matmul(x, y))

# Reshaping
print("Original shape:", x.shape)
print("Reshaped (view):", x.view(4, 1).shape)
Sum: tensor([[ 6.,  8.],
        [10., 12.]])
Product (Hadamard): tensor([[ 5., 12.],
        [21., 32.]])
Matrix Product (@): tensor([[19., 22.],
        [43., 50.]])
Matrix Product (matmul): tensor([[19., 22.],
        [43., 50.]])
Original shape: torch.Size([2, 2])
Reshaped (view): torch.Size([4, 1])

GPU AccelerationAceleração com GPU

Moving tensors to the GPU is trivial and can result in speed gains of orders of magnitude.Mover tensores para a GPU é trivial e pode resultar em ganhos de velocidade de ordens de magnitude.

# Check if GPU is available
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Using device: {device}")

# Create tensors on the chosen device
x_gpu = torch.randn(1000, 1000, device=device)
y_gpu = torch.randn(1000, 1000, device=device)

# The operation is executed on the device
z_gpu = x_gpu @ y_gpu

# To use with libraries like Matplotlib or NumPy, move back to CPU
z_cpu = z_gpu.to("cpu")
print(z_cpu.shape)
Using device: cuda
torch.Size([1000, 1000])

The Tensor “Superpower”O “superpoder” dos tensores

Important

autograd is the system that tracks all operations on tensors to automatically compute gradients. It is the foundation for model optimization.autograd é o sistema que rastreia todas as operações em tensores para calcular gradientes automaticamente. É a base para a otimização de modelos.

  • PyTorch builds the computation graph on the fly, while the code runs (hence dynamic).O PyTorch monta o grafo computacional na hora, enquanto o código roda (por isso dinâmico).
  • If x.requires_grad=True, PyTorch keeps the “history” of the operations done with x.Se x.requires_grad=True, o PyTorch guarda a “história” das operações feitas com x.
  • Calling .backward() on a scalar (for example, the loss function), PyTorch walks back through that history applying the chain rule.Ao chamar .backward() num escalar (por exemplo, a função de perda), o PyTorch percorre essa história de trás para frente, aplicando a regra da cadeia.

autograd in Practiceautograd na Prática

Let’s compute the derivative of \(y = x^2 \sin(x)\) at \(x = 2\).Vamos calcular a derivada de \(y = x^2 \sin(x)\) em \(x = 2\).

Tip

The analytical derivative is \(2x \sin(x) + x^2 \cos(x)\).A derivada analítica é \(2x \sin(x) + x^2 \cos(x)\).

# Define the tensor and enable gradient tracking
x = torch.tensor(2.0, requires_grad=True)

# Define the function
y = x**2 * torch.sin(x)

# Compute the gradient
y.backward()

# The gradient is stored in x.grad
print(f"Gradient of y with respect to x at x=2: {x.grad.item():.4f}")

# Analytical value for comparison
analytic_grad = 2 * 2 * np.sin(2) + 2**2 * np.cos(2)
print(f"Analytical value: {analytic_grad:.4f}")
Gradient of y with respect to x at x=2: 1.9726
Analytical value: 1.9726

Best Practices with TensorsBoas Práticas com Tensores

  • requires_grad=True only for parameters: input data generally does not need gradients.requires_grad=True apenas para parâmetros: dados de entrada geralmente não precisam de gradiente.
  • Use with torch.no_grad() during inference to save memory and time.Use with torch.no_grad() em inferência para economizar memória e tempo.
w = torch.tensor(1.0, requires_grad=True)
x_obs = torch.tensor(2.0)  # observed data

y_hat = w * x_obs
y_hat.backward() # We'll see more about this later
print("gradient at w:", w.grad)

with torch.no_grad():
    pred = w * 10
print("prediction without tracking gradient:", pred)
gradient at w: tensor(2.)
prediction without tracking gradient: tensor(10.)

The Dynamic Graph and grad_fnO Grafo Dinâmico e o grad_fn

In PyTorch, results of operations on tensors with gradients carry a pointer to the operation that created them.No PyTorch, resultados de operações sobre tensores com gradiente carregam um ponteiro para a operação que os criou.

a = torch.tensor(5.0, requires_grad=True)
b = torch.tensor(3.0, requires_grad=True)
d = a * b + a

print("d:", d)
print("grad_fn of d:", d.grad_fn)
d: tensor(20., grad_fn=<AddBackward0>)
grad_fn of d: <AddBackward0 object at 0x7f0a296605e0>

Visualizing the Computation GraphVisualizando o Grafo Computacional

make_dot(d, params={'d': d, 'a': a, 'b': b})

  • Blue rectangles are the leaves (our parameters)Os retângulos azuis são as folhas (nossos parâmetros)
  • Gray rectangles are the intermediate operationsOs retângulos cinzas são as operações intermediárias
  • The arrow indicates the information flow (forward pass)A seta indica o fluxo de informação (forward pass)

Computing the DerivativesCalculando as derivadas

make_dot(d, params={'d': d, 'a': a, 'b': b})

We can compute gradients automatically through the backward pass: PyTorch traverses the graph in reverse and applies the chain rule to compute partial derivatives.Podemos calcular gradientes automaticamente através do backward pass: o PyTorch percorre o grafo de trás para frente e aplica a regra da cadeia para calcular as derivadas parciais.

d.backward()
print("dd/da:", a.grad.item())
print("dd/db:", b.grad.item())
dd/da: 4.0
dd/db: 5.0

Tip

Recall that:Lembrando que:

  • \(a = 5\) and \(b = 3\)\(a = 5\) e \(b = 3\)
  • \(d = a \cdot b + a\)

It follows that:Segue que:

  • \(\frac{\partial d}{\partial a} = b + 1 = 4\)
  • \(\frac{\partial d}{\partial b} = a = 5\).

Summary of the BasicsResumo dos Conceitos Básicos

  • Tensors are PyTorch’s core data structure (shape, dtype, device).Tensores são a estrutura central do PyTorch (shape, dtype, device).
  • requires_grad=True enables tracking for parameters that will be optimized.requires_grad=True ativa o rastreamento para parâmetros que serão otimizados.
  • autograd builds the dynamic graph and computes gradients with .backward().O autograd constrói o grafo dinâmico e calcula gradientes com .backward().

Important

With this, we already have the basics to define models and train parameters via numerical optimization.Com isso, já temos o básico para definir modelos e treinar parâmetros por otimização numérica.

Part 2: Statistical Models with PyTorchParte 2: Modelos Estatísticos com PyTorch

Example: Linear RegressionExemplo: Regressão Linear

Let’s recall the analytical least squares solution for the linear regression model:Vamos recordar a solução analítica de mínimos quadrados do modelo de regressão linear:

\[ y = X \beta + \epsilon \]

The quadratic loss is:A perda quadrática é: \[ L(\beta) = \sum_{i=1}^{n} (y_i - X_i^T\beta)^2 \]

Differentiating and setting to zero, we obtain the closed-form solution:Derivando e igualando a zero, obtemos a solução fechada:

\[ \hat{\beta} = (X^T X)^{-1}X^Ty \]

Let’s compare this solution with optimization via autograd.Vamos comparar essa solução com a otimização via autograd.

Analytical SolutionSolução analítica

# Generate synthetic data
np.random.seed(0)
n_samples = 10000
n_features = 3
X = np.random.rand(n_samples, n_features)
true_beta = np.array([2.0, -3.5, 1.0])
y = X @ true_beta + np.random.randn(n_samples) * 0.5

# Convert to PyTorch tensors
X_tensor = torch.tensor(X, dtype=torch.float32)
y_tensor = torch.tensor(y, dtype=torch.float32).view(-1, 1)

# Analytical solution
XTX_inv = torch.inverse(X_tensor.t() @ X_tensor)
beta_analytical = XTX_inv @ X_tensor.t() @ y_tensor
print("Analytical solution for beta:")
print(beta_analytical.numpy())
Analytical solution for beta:
[[ 1.9843934]
 [-3.5015233]
 [ 1.0014043]]

Numerical Solution with autogradSolução Numérica com autograd

beta = torch.randn(n_features, 1, requires_grad=True)
optimizer = torch.optim.SGD([beta], lr=0.01)

n_epochs = 10000
for epoch in range(n_epochs):
    optimizer.zero_grad()
    y_pred = X_tensor @ beta
    loss = torch.mean((y_tensor - y_pred) ** 2)
    loss.backward()
    optimizer.step()

print("Optimized beta via autograd:")
print(beta.detach().numpy())
# make_dot(loss, params={"loss": loss, "beta": beta})
Optimized beta via autograd:
[[ 1.9843445]
 [-3.5014405]
 [ 1.0013771]]

Interpretation and Practical GainInterpretação e Ganho Prático

  • In the example, autograd recovers a solution very close to the analytical one.No exemplo, o autograd recupera uma solução muito próxima da analítica.
  • The real gain is not finding the least squares solution, but having a universal optimizer for models without closed-form solutions.O ganho real não é encontrar a solução de mínimos quadrados, mas ter um otimizador universal para modelos sem solução fechada.
  • The same code pattern extends to logistic regression, neural networks, and custom models.O mesmo padrão de código se estende para regressão logística, redes neurais e modelos customizados.

Warning

In the loop, backward() adds the new gradient to .grad instead of overwriting it. That is why each step starts with zero_grad(): without it, the step uses the sum of the gradients of every previous iteration.No laço, o backward() soma o gradiente novo ao que já está em .grad, em vez de sobrescrever. Por isso cada passo começa com zero_grad(): sem ele, o passo usa a soma dos gradientes de todas as iterações anteriores.

Example: Logistic RegressionExemplo: Regressão Logística

For logistic regression:Para regressão logística:

\[ P(y=1|X) = \sigma(X^T\beta), \quad \sigma(z)=\frac{1}{1+e^{-z}} \]

The loss function is the negative log-likelihood:A função de perda é a log-verossimilhança negativa:

\[ L(\beta) = -\sum_{i=1}^{n} \left[ y_i \log(\sigma(X_i^T\beta)) + (1-y_i)\log(1-\sigma(X_i^T\beta)) \right] \]

Numerical Solution with autogradSolução Numérica com autograd

# Generate synthetic data
np.random.seed(0)
n_samples = 10000
n_features = 3
X = np.random.rand(n_samples, n_features)
true_beta = np.array([-2.0, 1.5, -1.0])
logits = X @ true_beta
probabilities = 1 / (1 + np.exp(-logits))
y = np.random.binomial(1, probabilities)

# Convert to PyTorch tensors
X_tensor = torch.tensor(X, dtype=torch.float32)
y_tensor = torch.tensor(y.reshape(-1, 1), dtype=torch.float32)

Numerical Solution with autogradSolução Numérica com autograd

beta = torch.randn(n_features, 1, requires_grad=True)
bias = torch.zeros(1, requires_grad=True)
optimizer = torch.optim.SGD([beta, bias], lr=0.1)

n_epochs = 10000
for epoch in range(n_epochs):
    optimizer.zero_grad()
    logits = X_tensor @ beta + bias
    y_pred = torch.sigmoid(logits)
    loss = -torch.mean(y_tensor * torch.log(y_pred) +
        (1 - y_tensor) * torch.log(1 - y_pred))
    loss.backward()
    optimizer.step()

print("Optimized beta via autograd:")
print(beta.detach().numpy(), bias.detach().numpy())
# make_dot(loss, params={"loss": loss, "beta": beta, "bias": bias})
Optimized beta via autograd:
[[-1.9755266]
 [ 1.5227014]
 [-0.9161106]] [-0.06488332]

Bonus: Standard Errors with autogradBônus: Erros-Padrão com autograd

The MLE is approximately normal, with covariance equal to the inverse Hessian of the NLL (the observed information):O EMV é aproximadamente normal, com covariância igual à inversa da hessiana da NLL (a informação observada):

\[ \hat\theta \approx \mathcal{N}\left(\theta,\ H(\hat\theta)^{-1}\right), \qquad H(\hat\theta) = \nabla^2_\theta \, L(\hat\theta) \]

autograd also computes second derivatives, so the Hessian comes for free:O autograd também calcula derivadas segundas, então a hessiana sai de graça:

y_obs = y_tensor.squeeze()
def nll(theta):                       # theta = (b0, b1, b2, b3), b0 = intercept
    p = torch.sigmoid(theta[0] + X_tensor @ theta[1:])
    return -torch.sum(y_obs * torch.log(p) + (1 - y_obs) * torch.log(1 - p))  # sum, not mean
theta_hat = torch.cat([bias, beta.squeeze()]).detach()
H = torch.autograd.functional.hessian(nll, theta_hat)
se = torch.linalg.inv(H).diagonal().sqrt().numpy()
import pandas as pd, statsmodels.api as sm
bse = sm.Logit(y, sm.add_constant(X)).fit(disp=0).bse   # same model, for comparison
print(pd.DataFrame([se, bse], ["autograd", "statsmodels"], ["b0", "b1", "b2", "b3"]).round(4))
                 b0    b1      b2      b3
autograd     0.0678  0.08  0.0791  0.0781
statsmodels  0.0678  0.08  0.0791  0.0781

Transition to torch.nnTransição para torch.nn

So far, we have worked with tensors and autograd directly. The torch.nn API organizes this into reusable modules. Let’s repeat logistic regression using nn.Module.Até aqui, trabalhamos com tensores e autograd de forma direta. A API torch.nn organiza isso em módulos reutilizáveis. Vamos repetir a regressão logística usando nn.Module.

class LogisticRegressionModel(nn.Module):
    def __init__(self, n_features):
        super(LogisticRegressionModel, self).__init__()
        self.linear = nn.Linear(n_features, 1)

    def forward(self, x):
        return self.linear(x)   # logit; the loss applies the sigmoid

Logistic Regression with torch.nnRegressão Logística com torch.nn

model_logistic = LogisticRegressionModel(n_features)
criterion = nn.BCEWithLogitsLoss()
optimizer = optim.SGD(model_logistic.parameters(), lr=0.1)

n_epochs = 10000
for epoch in range(n_epochs):
    optimizer.zero_grad()
    y_pred = model_logistic(X_tensor)
    loss = criterion(y_pred, y_tensor)
    loss.backward()
    optimizer.step()

print("Optimized beta via torch.nn for logistic regression:")
print(model_logistic.linear.weight.detach().numpy(), model_logistic.linear.bias.detach().numpy())
# make_dot(loss, params=dict(model_logistic.named_parameters()))
Optimized beta via torch.nn for logistic regression:
[[-1.975529   1.5226989 -0.9161131]] [-0.06487944]

The torch.nn APIA API torch.nn

  1. nn.Module: standard container for parameters and forward logic.nn.Module: container padrão para parâmetros e lógica forward.
  2. nn.Linear: pre-built module with weights and bias.nn.Linear: módulo pré-construído com pesos e intercepto.
  3. nn.MSELoss / nn.BCEWithLogitsLoss: ready-made losses. The model returns the logit and the loss applies the sigmoid inside, which is numerically more stable. nn.CrossEntropyLoss does the same with the softmax.nn.MSELoss / nn.BCEWithLogitsLoss: losses prontas. O modelo devolve o logito e a perda aplica a sigmoide por dentro, o que é numericamente mais estável. A nn.CrossEntropyLoss faz o mesmo com o softmax.
  4. torch.optim: parameter updates + zero_grad().torch.optim: atualização dos parâmetros + zero_grad().

Saving ModelsSalvando Modelos

Every nn.Module has a state_dict: a dictionary with all its parameter tensors. That is what gets saved, not the object.Todo nn.Module tem um state_dict: um dicionário com todos os seus tensores de parâmetros. É isso que precisamos salvar para recuperar o modelo posteriormente.

print(model_logistic.state_dict())
OrderedDict({'linear.weight': tensor([[-1.9755,  1.5227, -0.9161]]), 'linear.bias': tensor([-0.0649])})
torch.save(model_logistic.state_dict(), "logistic.pt")

model = LogisticRegressionModel(n_features)     # same architecture, new parameters
model.load_state_dict(torch.load("logistic.pt"))

Tip

Seeds: torch.manual_seed(...) (and np.random.seed(...)) at the start make initialization and shuffling reproducible. With neural networks this matters: two seeds can give quite different results, so before concluding that a change helped, repeat with a few seeds.Sementes: torch.manual_seed(...) (e np.random.seed(...)) no início tornam a inicialização e o embaralhamento reproduzíveis. Em redes neurais isso importa, pois duas sementes podem dar resultados bem diferentes.

Part 3: Neural Networks with PyTorchParte 3: Redes Neurais com PyTorch

Review: Neural NetworksRevisão: Redes Neurais

  • A neuron receives inputs \(\mathbf{x} \in \mathbb{R}^d\), computes a parametric linear combination, and applies a non-linear transformation \(\phi\):Um neurônio recebe entradas \(\mathbf{x} \in \mathbb{R}^d\), calcula uma combinação linear paramétrica e aplica uma transformação não-linear \(\phi\): \[ y = \phi(\mathbf{w}^T\mathbf{x} + b) \]
  • The function \(\phi\) (e.g., ELU, ReLU, \(\tanh\)) is essential. Without it, a composition of neurons would collapse into a single affine function:A função \(\phi\) (e.g., ELU, ReLU, \(\tanh\)) é essencial. Sem ela, uma composição de neurônios colapsaria em uma única função afim: \[ (W_2 (W_1 \mathbf{x} + b_1) + b_2) = (W_2 W_1)\mathbf{x} + (W_2 b_1 + b_2) = W'\mathbf{x} + b' \]

Note

Logistic regression is essentially a single neuron with \(\phi = \sigma\) (sigmoid function), where:A regressão logística é essencialmente um único neurônio com \(\phi = \sigma\) (função sigmóide), onde: \[ P(y=1|\mathbf{x}) = \sigma(\beta^T\mathbf{x}) \]

Review: Neural NetworksRevisão: Redes Neurais

  • Universal approximation theorem: A feedforward neural network with at least one hidden layer and a non-linear activation function is capable of approximating any continuous function \(\mathbb{R}^n \to \mathbb{R}^m\), given enough neurons.Teorema da aproximação universal: Uma rede neural do tipo feedforward com pelo menos uma camada oculta e uma função de ativação não-linear é capaz de aproximar qualquer função contínua \(\mathbb{R}^n \to \mathbb{R}^m\), desde que haja neurônios o suficiente.
  • Deep networks: In practice, multiple layers tend to be a more efficient representation, with better generalization.Redes profundas: Na prática, múltiplas camadas tendem a ser uma representação mais eficiente, e com melhor generalização.

Multi-Layer Perceptron

An MLP with two hidden layers maps the data \(\mathbf{X}\) through the operations:Um MLP com duas camadas ocultas mapeia os dados \(\mathbf{X}\) através das operações:

\[ \mathbf{h_1} = \phi_1(\mathbf{X}\mathbf{W}_1 + \mathbf{b}_1), \quad \mathbf{h_2} = \phi_1(\mathbf{h_1}\mathbf{W}_2 + \mathbf{b}_2), \quad \hat{\mathbf{y}} = \phi_2(\mathbf{h_2}\mathbf{W}_3 + \mathbf{b}_3) \]

\[ \hat{\mathbf{y}} = \phi_2 \left( \phi_1 \left( \phi_1 \left( \mathbf{X}\mathbf{W}_1 + \mathbf{b}_1 \right) \mathbf{W}_2 + \mathbf{b}_2 \right) \mathbf{W}_3 + \mathbf{b}_3 \right) \]

NeuralNetwork cluster_input Input (X) cluster_h1 Layer h 1 cluster_h2 Layer h 2 cluster_output Output (ŷ) x1 x 1 h1_1 h 1,1 x1->h1_1 h1_2 h 1,2 x1->h1_2 h1_3 h 1,3 x1->h1_3 x2 x 2 x2->h1_1 x2->h1_2 x2->h1_3 h2_1 h 2,1 h1_1->h2_1 h2_2 h 2,2 h1_1->h2_2 h2_3 h 2,3 h1_1->h2_3 h1_2->h2_1 h1_2->h2_2 h1_2->h2_3 h1_3->h2_1 h1_3->h2_2 h1_3->h2_3 y_hat ŷ h2_1->y_hat h2_2->y_hat h2_3->y_hat

NeuralNetwork cluster_input Entrada (X) cluster_h1 Camada h 1 cluster_h2 Camada h 2 cluster_output Saída (ŷ) x1 x 1 h1_1 h 1,1 x1->h1_1 h1_2 h 1,2 x1->h1_2 h1_3 h 1,3 x1->h1_3 x2 x 2 x2->h1_1 x2->h1_2 x2->h1_3 h2_1 h 2,1 h1_1->h2_1 h2_2 h 2,2 h1_1->h2_2 h2_3 h 2,3 h1_1->h2_3 h1_2->h2_1 h1_2->h2_2 h1_2->h2_3 h1_3->h2_1 h1_3->h2_2 h1_3->h2_3 y_hat ŷ h2_1->y_hat h2_2->y_hat h2_3->y_hat

Backpropagation

How do we optimize the parameters \(\mathbf{W}_1, \mathbf{W}_2, \mathbf{W}_3\) of a neural network? We need the gradients \(\nabla_{\mathbf{W}_k} \ell\) for each layer.Como otimizar os parâmetros \(\mathbf{W}_1, \mathbf{W}_2, \mathbf{W}_3\) de uma rede neural? Precisamos dos gradientes \(\nabla_{\mathbf{W}_k} \ell\) para cada camada.

Consider the quadratic loss as an example:Considere a perda quadrática como exemplo:

\[ \ell(\hat{\mathbf{y}}, \mathbf{y}) = \|\hat{\mathbf{y}} - \mathbf{y}\|^2 \]

Substituting \(\hat{\mathbf{y}}\) with the MLP expression, the loss becomes a composition of functions:Substituindo \(\hat{\mathbf{y}}\) pela expressão do MLP, a perda se torna uma composição de funções:

\[ \ell(\hat{\mathbf{y}}, \mathbf{y}) = \left\| \phi_2 \left( \underbrace{\phi_1 \left( \underbrace{\phi_1 \left( \mathbf{X}\mathbf{W}_1 + \mathbf{b}_1 \right)}_{\mathbf{h}_1} \mathbf{W}_2 + \mathbf{b}_2 \right)}_{\mathbf{h}_2} \mathbf{W}_3 + \mathbf{b}_3 \right) - \mathbf{y} \right\|^2 \]

Backpropagation

By the chain rule, gradients propagate layer by layer, from back to front:Pela regra da cadeia, os gradientes se propagam camada a camada, de trás para frente:

\[ \begin{gathered} \frac{\partial \ell}{\partial \mathbf{W}_3} = \frac{\partial \ell}{\partial \hat{\mathbf{y}}} \cdot \frac{\partial \hat{\mathbf{y}}}{\partial \mathbf{W}_3}, \qquad \frac{\partial \ell}{\partial \mathbf{W}_2} = \frac{\partial \ell}{\partial \hat{\mathbf{y}}} \cdot \frac{\partial \hat{\mathbf{y}}}{\partial \mathbf{h}_2} \cdot \frac{\partial \mathbf{h}_2}{\partial \mathbf{W}_2}, \\[0.5em] \frac{\partial \ell}{\partial \mathbf{W}_1} = \frac{\partial \ell}{\partial \hat{\mathbf{y}}} \cdot \frac{\partial \hat{\mathbf{y}}}{\partial \mathbf{h}_2} \cdot \frac{\partial \mathbf{h}_2}{\partial \mathbf{h}_1} \cdot \frac{\partial \mathbf{h}_1}{\partial \mathbf{W}_1} \end{gathered} \]

Tip

This is exactly the computation that autograd performs when we call loss.backward(). No matter how many layers the network has, the chain rule applies recursively.Esse é exatamente o cálculo que o autograd realiza ao chamarmos loss.backward(). Não importa quantas camadas a rede tenha, a regra da cadeia se aplica recursivamente.

OptimizersOtimizadores

With the gradients \(\nabla_\theta \ell\) in hand, we need an update rule for the parameters.Com os gradientes \(\nabla_\theta \ell\) em mãos, precisamos de uma regra de atualização para os parâmetros.

  • SGD (Stochastic Gradient Descent): the simplest update:SGD (Stochastic Gradient Descent): a atualização mais simples: \[ \theta \leftarrow \theta - \eta \, \nabla_\theta \ell \] where \(\eta\) is the learning rate.onde \(\eta\) é a taxa de aprendizado (learning rate).
  • Adam: combines moving averages of the gradient (\(1^{\text{st}}\) moment) and the squared gradient (\(2^{\text{nd}}\) moment), adapting the learning rate for each parameter individually. It is the default optimizer in most modern applications.Adam: combina médias móveis do gradiente (\(1^{\circ}\) momento) e do gradiente ao quadrado (\(2^{\circ}\) momento), adaptando a taxa de aprendizado para cada parâmetro individualmente. É o otimizador padrão na maioria das aplicações modernas.
  • In practice, just swap optim.SGD(...) for optim.Adam(...), the API is identical.Na prática, basta trocar optim.SGD(...) por optim.Adam(...), a API é idêntica.

Important

There is no need to implement backpropagation or optimizers manually: PyTorch handles everything. Just define the network, the loss, and call loss.backward() + optimizer.step().Não é necessário implementar backpropagation nem os otimizadores manualmente: o PyTorch cuida de tudo. Basta definir a rede, a perda, e chamar loss.backward() + optimizer.step().

Mini-batches and EpochsMini-batches e Épocas

So far each step used the whole dataset. In practice, each step uses a random mini-batch \(B\):Até aqui, cada passo usou a base inteira. Na prática, cada passo usa um mini-batch aleatório \(B\):

\[ \theta \leftarrow \theta - \eta \, \frac{1}{|B|} \sum_{i \in B} \nabla_\theta \, \ell(f_\theta(x_i), y_i) \]

  • The mini-batch gradient is an unbiased estimator of the full gradient, at a fraction of the cost.O gradiente do mini-batch é um estimador não viesado do gradiente completo, por uma fração do custo.
  • Memory: only one batch needs to be on the GPU at a time.Memória: só um lote precisa estar na GPU por vez.
  • The noise in the estimate helps escape poor regions of the loss surface.O ruído da estimativa ajuda a escapar de regiões ruins da superfície de perda.
  • Epoch: one full pass over the training data, that is, \(n / |B|\) steps.Época: uma passada completa pelos dados de treino, ou seja, \(n / |B|\) passos.

Tip

Batch size and learning rate interact, since larger batches give less noisy gradients and tolerate larger learning rates. Typical values range from 32 to 512.Tamanho do lote e taxa de aprendizado interagem, porque lotes maiores dão gradientes menos ruidosos e toleram taxas maiores. Valores típicos vão de 32 a 512.

Train, Validation and TestTreino, Validação e Teste

The goal is the risk on new data, \(R(f) = \mathbb{E}\left[\ell(f(X), Y)\right]\), not the loss on the training sample.O objetivo é o risco em dados novos, \(R(f) = \mathbb{E}\left[\ell(f(X), Y)\right]\), não a perda na amostra de treino.

  • A flexible enough network drives the training loss to zero by memorizing the sample: overfitting.Uma rede flexível o bastante leva a perda de treino a zero memorizando a amostra: sobreajuste.
  • Train fits \(\theta\); validation chooses everything else (architecture, learning rate, regularization, epochs); test estimates the risk of the final model, once, at the end.Treino ajusta \(\theta\); validação escolhe todo o resto (arquitetura, taxa de aprendizado, regularização, épocas); teste estima o risco do modelo final, uma vez, no fim.

Note

None of this is specific to neural networks. What changes is how fast it shows up: with thousands of parameters, overfitting is the rule.Nada disso é exclusivo de redes neurais. O que muda é que com milhares de parâmetros o sobreajuste é quase garantido.

MLP for Binary ClassificationMLP para Classificação Binária

class SimpleMLP(nn.Module):
    def __init__(self, input_dim, hidden_dim, output_dim):
        super(SimpleMLP, self).__init__()
        self.layer1 = nn.Linear(input_dim, hidden_dim)
        self.layer2 = nn.Linear(hidden_dim, hidden_dim)
        self.output = nn.Linear(hidden_dim, output_dim)
        self.activation = nn.ReLU()

    def forward(self, x):
        h1 = self.activation(self.layer1(x))
        h2 = self.activation(self.layer2(h1))
        return self.output(h2)   # logit

model = SimpleMLP(input_dim=3, hidden_dim=5, output_dim=1)
y_pred = model(torch.tensor([0, 0, 0], dtype=torch.float32))
# make_dot(y_pred, params=dict(model.named_parameters()))

MLP for Binary ClassificationMLP para Classificação Binária

from torch.utils.data import DataLoader, TensorDataset

loader = DataLoader(TensorDataset(X_tensor, y_tensor), batch_size=64, shuffle=True)
model = SimpleMLP(input_dim=X.shape[1], hidden_dim=5, output_dim=1)
criterion = nn.BCEWithLogitsLoss()
optimizer = optim.SGD(model.parameters(), lr=0.1)

for epoch in range(50):
    for xb, yb in loader:              # one mini-batch at a time
        optimizer.zero_grad()
        loss = criterion(model(xb), yb)
        loss.backward()
        optimizer.step()

Note

TensorDataset pairs each row of X with its y; the DataLoader shuffles and hands out one mini-batch at a time. Each pass of the outer loop is one epoch. shuffle=True for training only.O TensorDataset junta cada linha de X ao seu y; o DataLoader embaralha e entrega um mini-batch por vez. Cada volta do laço externo é uma época. shuffle=True só no treino.

Part 4: Avoiding OverfittingParte 4: Evitando o Sobreajuste

Avoiding OverfittingEvitando o Sobreajuste

Deep networks usually have more parameters than observations and can interpolate the noise. ResNet-50, a classic image network, has 25 million parameters and was trained on 1.3 million images.Redes profundas costumam ter mais parâmetros do que observações e conseguem interpolar o ruído. A ResNet-50, uma rede clássica para imagens, tem 25 milhões de parâmetros e foi treinada com 1,3 milhão de imagens.

They generalize only with controls, all chosen on validation:Elas só generalizam com controles, todos escolhidos na validação:

IdeaIdeia TechniqueTécnica
Penalize the size of the weightsPenalizar o tamanho dos pesos Weight decay
Inject noise during trainingInjetar ruído no treino Dropout, data augmentation
Stop before memorizingParar antes de memorizar Early stopping
Calibrate everything aboveCalibrar tudo isso Hyperparameter searchBusca de hiperparâmetros

Tip

None of these ideas is new to anyone who has seen ridge, bagging or cross-validation.Nenhuma dessas ideias é nova para quem viu ridge, bagging ou validação cruzada.

Weight Decay

Add a penalty on the size of the parameters:Somamos uma penalidade sobre o tamanho dos parâmetros:

\[ \hat{R}_n(\theta) + \lambda \|\theta\|^2 \]

  • This is ridge regression applied to the whole network.É a regressão ridge aplicada à rede inteira.
  • Bayesian reading: the minimizer is the MAP estimate under a Gaussian prior centered at zero for \(\theta\).Leitura bayesiana: o minimizador é o estimador MAP sob uma priori gaussiana centrada em zero para \(\theta\).
  • In PyTorch it is an optimizer argument, no need to change the loss:No PyTorch é um argumento do otimizador, sem mexer na perda:
optimizer = optim.AdamW(model.parameters(), lr=1e-3, weight_decay=1e-2)

Tip

Prefer AdamW to Adam(..., weight_decay=...). In Adam the penalty goes through the adaptive scaling and loses part of its effect; AdamW applies the decay directly to the weights.Prefira AdamW a Adam(..., weight_decay=...). No Adam a penalidade passa pelo reescalonamento adaptativo e perde parte do efeito; o AdamW aplica o decaimento direto nos pesos.

Dropout

  • During training, each neuron is zeroed with probability \(p\), and the survivors are multiplied by \(1/(1-p)\) to keep the expected value.Durante o treino, cada neurônio é zerado com probabilidade \(p\), e os sobreviventes são multiplicados por \(1/(1-p)\) para manter o valor esperado.
  • The network cannot rely on any single neuron. It behaves like an average over many subnetworks.A rede não pode depender de nenhum neurônio isolado. Ela se comporta como uma média de muitas sub-redes.
  • In eval() mode, dropout is the identity.No modo eval(), o dropout é a identidade.
torch.manual_seed(1)
dropout = nn.Dropout(p=0.5)
h = torch.ones(8)

dropout.train()
print("train:", dropout(h))
dropout.eval()
print("eval: ", dropout(h))
train: tensor([2., 2., 2., 2., 0., 2., 2., 0.])
eval:  tensor([1., 1., 1., 1., 1., 1., 1., 1.])

Early Stopping

Monitor the validation loss, keep the best parameters and stop after patience epochs without improvement. In the example we have 25 noisy points from \(\sin(2\pi x)\), 200 for validation and a wide MLP (make_mlp, two layers of 256 neurons with dropout after each ReLU):Acompanhamos a perda de validação, guardamos os melhores parâmetros e paramos depois de patience épocas sem melhora. No exemplo, são 25 pontos com ruído vindos de \(\sin(2\pi x)\), 200 de validação e um MLP largo (make_mlp, duas camadas de 256 neurônios com dropout depois de cada ReLU):

torch.manual_seed(0)
model = make_mlp(dropout=0.2)
optimizer = optim.AdamW(model.parameters(), lr=3e-3, weight_decay=1e-1)
train_loader = DataLoader(TensorDataset(x_train, y_train), batch_size=25, shuffle=True)
val_loader = DataLoader(TensorDataset(x_val, y_val), batch_size=200)

best, patience, waited, curve = float("inf"), 100, 0, []
for epoch in range(2000):
    train_one_epoch(model, train_loader, optimizer, F.mse_loss)
    curve.append(evaluate(model, val_loader, F.mse_loss))
    if curve[-1] < best:
        best, waited = curve[-1], 0
        best_state = copy.deepcopy(model.state_dict())
    else:
        waited += 1
        if waited >= patience:
            break
model.load_state_dict(best_state)
print(f"stopped at epoch {epoch}, best validation MSE: {best:.3f}")
stopped at epoch 417, best validation MSE: 0.127

Regularization in PracticeRegularização na Prática

HyperparametersHiperparâmetros

In rough order of importance:Em ordem aproximada de importância:

  1. Learning rate: too high diverges, too low does not leave the place. Try powers of 10 (\(10^{-4}\) to \(10^{-2}\) with Adam).Taxa de aprendizado: alta demais diverge, baixa demais não sai do lugar. Teste potências de 10 (\(10^{-4}\) a \(10^{-2}\) com Adam).
  2. Model size: width and depth.Tamanho do modelo: largura e profundidade.
  3. Regularization: weight decay and dropout.Regularização: weight decay e dropout.
  4. Optimizer and batch size.Otimizador e tamanho do lote.
  5. Number of epochs: or use early stopping instead.Número de épocas: ou use early stopping no lugar.

Note

Prefer random search to grid search. Optuna automates the search and uses past trials to pick the next values.Prefira busca aleatória à busca em grade. O Optuna automatiza a busca e usa os resultados anteriores para escolher os próximos valores.

Part 5: Notable ArchitecturesParte 5: Arquiteturas Notáveis

Choosing the ArchitectureEscolhendo a Arquitetura

An MLP can, in principle, approximate anything, but there are specific architectures suited to each type of data.Um MLP pode, em princípio, aproximar qualquer coisa, mas existem arquiteturas específicas adequadas a cada tipo de dado.

Arquiteturas ids Identifiers emb Embeddings ids->emb tab Tabular data tab->emb mlp MLP tab->mlp att Attention tab->att txt Text txt->emb rnn RNN txt->rnn txt->att ts Time series ts->rnn ts->att cnn CNN ts->cnn img Images img->att img->cnn

Arquiteturas ids Identificadores emb Embeddings ids->emb tab Dados tabulares tab->emb mlp MLP tab->mlp att Atenção tab->att txt Texto txt->emb rnn RNN txt->rnn txt->att ts Séries temporais ts->rnn ts->att cnn CNN ts->cnn img Imagens img->att img->cnn

Tip

The knowledge about the data built into the architecture is called inductive bias.O conhecimento sobre os dados embutido na arquitetura se chama viés indutivo.

Embeddings

For identifiers and other categorical variables with many levels, we use embeddings.Para identificadores e outras variáveis categóricas com muitos níveis, usamos embeddings.

  • Take the variable country, with about 200 levels. Instead of one dummy per country, each country becomes a learned vector in \(\mathbb{R}^d\), with small \(d\) (say, 8).Pense na variável país, com cerca de 200 níveis. Em vez de uma dummy para cada país, cada país vira um vetor aprendido em \(\mathbb{R}^d\), com \(d\) pequeno (digamos, 8).
  • Countries that behave alike end up with close vectors, even if they are far apart on the map. It resembles random effects, but multivariate.Países que se comportam de forma parecida ficam com vetores próximos, mesmo que estejam longe no mapa. Lembra efeitos aleatórios, só que multivariado.
  • It is exactly one-hot encoding followed by a linear layer without intercept: \(e_k = \mathbf{1}_k^\top W\). The lookup just avoids the multiplication by zeros.É exatamente o one-hot seguido de uma camada linear sem intercepto: \(e_k = \mathbf{1}_k^\top W\). A consulta só evita multiplicar por zeros.

Tip

Recommender systems use the same idea, with one embedding per user and one per item. Recommendations come from how close the two are.Sistemas de recomendação usam a mesma ideia, com um embedding para cada usuário e um para cada item. A recomendação sai da proximidade entre os dois.

Embeddings in PyTorchEmbeddings no PyTorch

nn.Embedding is a \(195 \times 8\) table, trained along with the rest of the network, in which each country looks up its row:O nn.Embedding é uma tabela \(195 \times 8\), treinada junto com o resto da rede, em que cada país consulta sua linha:

torch.manual_seed(0)
emb = nn.Embedding(195, 8)   # 195 countries, d = 8
countries = torch.tensor([0, 23, 23, 194])
print(emb(countries).shape)
torch.Size([4, 8])

Illustration with \(d = 2\).Ilustração com \(d = 2\).

Convolutional NetworksRedes Convolucionais

For images, the standard architecture is the convolutional network (CNN). A small filter \(K\) (e.g., \(3 \times 3\)) slides over the image \(X\). At each position, it multiplies the pixels in the window by the filter weights and adds them up:Para imagens, a arquitetura padrão é a rede convolucional (CNN). Um filtro pequeno \(K\) (por exemplo, \(3 \times 3\)) desliza sobre a imagem \(X\). Em cada posição, multiplica os pixels da janela pelos pesos do filtro e soma:

\[ (X * K)_{ij} = \sum_{a=0}^{2} \sum_{b=0}^{2} K_{ab} \, X_{i+a,\, j+b} \]

  • Locality: each output depends only on a neighborhood.Localidade: cada saída depende só de uma vizinhança.
  • Weight sharing: the same 9 weights are used at every position. A pattern learned in one corner is recognized anywhere.Compartilhamento de pesos: os mesmos 9 pesos são usados em todas as posições. Um padrão aprendido num canto é reconhecido em qualquer lugar.

\(3 \times 3\) filter over a \(4 \times 4\) image. Animation from Dumoulin and Visin (2016).Filtro \(3 \times 3\) sobre uma imagem \(4 \times 4\). Animação de Dumoulin e Visin (2016).

Padding and StridePadding e Stride

Padding: zeros around the border, so that the filter also passes over the edge pixels and the output does not shrink.Padding: zeros em volta da borda, para que o filtro também passe pelos pixels da beirada e a saída não encolha.

Stride: the step size. With stride=2, the filter skips every other position and the output has about half the height and width.Stride: o tamanho do passo. Com stride=2, o filtro pula uma posição a cada passo e a saída fica com cerca de metade da altura e da largura.

The output has size \(\lfloor (n + 2p - k)/s \rfloor + 1\), for input \(n\), filter \(k\), padding \(p\) and stride \(s\).A saída tem tamanho \(\lfloor (n + 2p - k)/s \rfloor + 1\), com entrada \(n\), filtro \(k\), padding \(p\) e stride \(s\).

Animations from Dumoulin and Visin (2016).Animações de Dumoulin e Visin (2016).

FiltersFiltros

The convolution output is large where the image window looks like the filter. In the digit below, pixels go from 0 (white, background) to 1 (black, stroke):A saída da convolução é grande onde a janela da imagem se parece com o filtro. No dígito abaixo, os pixels vão de 0 (branco, fundo) a 1 (preto, traço):

  • The first filter adds the two pixels below and subtracts the two above. The output is high only where there is stroke below and background above, i.e., on the top edge of the stroke.O primeiro filtro soma os dois pixels de baixo e subtrai os dois de cima. A saída é alta só onde há traço embaixo e fundo em cima, ou seja, na borda de cima do traço.
  • These filters are just an example. In a CNN, the filter weights are learned during training.Esses filtros são só um exemplo. Numa CNN, os pesos dos filtros são aprendidos no treinamento.

Many FiltersVários Filtros

A layer uses several filters, and each one produces a map, called a channel. With the 4 filters above, the \(1 \times 28 \times 28\) image becomes a \(4 \times 28 \times 28\) tensor:Uma camada usa vários filtros, e cada um produz um mapa, chamado canal. Com os 4 filtros anteriores, a imagem \(1 \times 28 \times 28\) vira um tensor \(4 \times 28 \times 28\):

  • Each filter of the next convolution looks at the same window in all channels. With 4 input channels, a \(3 \times 3\) filter actually has \(4 \times 3 \times 3\) weights and combines edges into larger patterns, such as corners and curves.Cada filtro da convolução seguinte olha a mesma janela em todos os canais. Com 4 canais na entrada, um filtro \(3 \times 3\) tem, na verdade, \(4 \times 3 \times 3\) pesos e combina bordas em padrões maiores, como cantos e curvas.
  • A layer with 16 filters of \(3 \times 3\) on a \(28 \times 28\) image has \(16 \times 9 + 16 = 160\) parameters, against \(784 \times 16 + 16 = 12{,}560\) for a dense layer with 16 outputs.Uma camada com 16 filtros \(3 \times 3\) sobre uma imagem \(28 \times 28\) tem \(16 \times 9 + 16 = 160\) parâmetros, contra \(784 \times 16 + 16 = 12.560\) de uma camada densa com 16 saídas.

Pooling

It is common to alternate convolutional layers with pooling layers, which reduce the height and width of each channel. \(2 \times 2\) max pooling splits the channel into \(2 \times 2\) blocks and keeps the maximum of each block:É comum alternar camadas convolucionais com camadas de pooling, que reduzem a altura e a largura de cada canal. O max pooling \(2 \times 2\) divide o canal em blocos \(2 \times 2\) e guarda o máximo de cada bloco:

  • Pooling has no weights and does not change the number of channels. Its window size has nothing to do with the filter size.O pooling não tem pesos e não muda o número de canais. O tamanho da janela dele não tem relação com o do filtro.
  • With smaller channels, the next layers are cheaper and each \(3 \times 3\) filter covers a larger region of the original image.Com canais menores, as camadas seguintes ficam mais baratas e cada filtro \(3 \times 3\) cobre uma região maior da imagem original.
  • If an edge moves one pixel inside its block, the maximum does not change, so the output tolerates small shifts.Se uma borda se desloca um pixel dentro do bloco, o máximo não muda, e a saída tolera pequenos deslocamentos.

The Typical CNNA CNN Típica

Convolution and pooling alternate: the channels get smaller and more numerous. At the end, the channels are flattened into a vector and dense layers make the prediction.Convolução e pooling se alternam, e os canais ficam menores e mais numerosos. No fim, os canais são achatados num vetor e camadas densas fazem a previsão.

The first two stages use the edge maps from the previous slides. In a trained CNN, all filters are learned and the later ones combine edges into more complex patterns.As duas primeiras etapas usam os mapas de borda dos slides anteriores. Numa CNN treinada, todos os filtros são aprendidos, e os das camadas mais profundas combinam bordas em padrões mais complexos.

A CNN in PyTorchUma CNN em PyTorch

cnn = nn.Sequential(
    nn.Conv2d(in_channels=1, out_channels=4, kernel_size=3, padding=1), nn.ReLU(),
    nn.MaxPool2d(2),
    nn.Conv2d(4, 8, kernel_size=3, padding=1), nn.ReLU(),
    nn.MaxPool2d(2),
    nn.Flatten(),
    nn.Linear(8 * 7 * 7, 10),   # 10 classes (digits)
)
x = torch.randn(32, 1, 28, 28)   # (batch, channels, height, width)
for layer in cnn:
    x = layer(x)
    print(f"{layer.__class__.__name__:<18} {tuple(x.shape)}")
Conv2d             (32, 4, 28, 28)
ReLU               (32, 4, 28, 28)
MaxPool2d          (32, 4, 14, 14)
Conv2d             (32, 8, 14, 14)
ReLU               (32, 8, 14, 14)
MaxPool2d          (32, 8, 7, 7)
Flatten            (32, 392)
Linear             (32, 10)

CNN HyperparametersHiperparâmetros da CNN

The number of blocks, the number of filters, and the filter and pooling sizes are hyperparameters. Common starting values:O número de blocos, o número de filtros e os tamanhos do filtro e do pooling são hiperparâmetros. Valores comuns para começar:

HyperparameterHiperparâmetro Common valuesValores comuns
Filter sizeTamanho do filtro \(3 \times 3\) in every layer\(3 \times 3\) em todas as camadas
Filters per layerFiltros por camada 32 or 64 at first, doubling at each pooling32 ou 64 no início, dobrando a cada pooling
Pooling \(2 \times 2\) max pooling after each blockmax pooling \(2 \times 2\) depois de cada bloco
Convolution + pooling blocksBlocos de convolução + pooling 2 to 5, depending on the image size2 a 5, conforme o tamanho da imagem

Note

Like any hyperparameter, they are chosen on validation. Starting from a known architecture and adjusting it is usually faster than searching from scratch.Como qualquer hiperparâmetro, eles são escolhidos na validação. Partir de uma arquitetura conhecida e ajustar costuma ser mais rápido do que buscar do zero.

Recurrent NetworksRedes Recorrentes

For time series, the order of the observations matters. A sequence \(x_1, \dots, x_T\) is read one step at a time, updating a hidden state with an activation function \(\phi\):Para séries temporais, a ordem das observações importa. Uma sequência \(x_1, \dots, x_T\) é lida um passo por vez, atualizando um estado oculto com uma função de ativação \(\phi\):

\[ \mathbf{h}_t = \phi\left(W_x \mathbf{x}_t + W_h \mathbf{h}_{t-1} + \mathbf{b}\right) \]

RNN h0 h 0 h1 h 1 h0->h1 h2 h 2 h1->h2 dots ⋯ h2->dots h3 h T y ŷ h3->y dots->h3 x1 x 1 x1->h1 x2 x 2 x2->h2 x3 x T x3->h3

  • The same weights \(W_x, W_h\) are used at every step, so the network handles sequences of any length.Os mesmos pesos \(W_x, W_h\) são usados em todos os passos, então a rede lida com sequências de qualquer tamanho.
  • The last state \(\mathbf{h}_T\) is a learned summary of the whole sequence.O último estado \(\mathbf{h}_T\) é um resumo aprendido da sequência inteira.

GRU

In the simple RNN, the state goes through \(W_h\) and \(\phi\) at every step, and the effect of the first steps vanishes. The GRU (gated recurrent unit) averages between copying the old state and a new candidate \(\tilde{\mathbf{h}}_t\), computed as in the simple RNN:Na RNN simples, o estado passa por \(W_h\) e \(\phi\) a cada passo, e o efeito dos primeiros passos some. A GRU (gated recurrent unit) faz uma média entre copiar o estado antigo e um candidato novo \(\tilde{\mathbf{h}}_t\), calculado como na RNN simples:

\[ \mathbf{h}_t = (1 - \mathbf{z}_t) \odot \mathbf{h}_{t-1} + \mathbf{z}_t \odot \tilde{\mathbf{h}}_t, \qquad \mathbf{z}_t = \sigma\left(W_z \mathbf{x}_t + U_z \mathbf{h}_{t-1} + \mathbf{b}_z\right) \]

GRU hprev h t−1 mix + hprev->mix 1 − z t cand h̃ t cand->mix z t h h t mix->h

  • It is exponential smoothing whose weight \(\mathbf{z}_t \in (0, 1)\), the gate, is learned and changes at every step.É uma suavização exponencial cujo peso \(\mathbf{z}_t \in (0, 1)\), o portão, é aprendido e muda a cada passo.
  • With \(\mathbf{z}_t\) near 0, the state is copied without going through \(W_h\) and \(\phi\), and the memory survives many steps.Com \(\mathbf{z}_t\) perto de 0, o estado é copiado sem passar por \(W_h\) e \(\phi\), e a memória sobrevive a muitos passos.

AttentionAtenção

For text, the standard architecture today is based on attention. To understand it, recall the Nadaraya–Watson kernel regression estimator:Para texto, a arquitetura padrão hoje é baseada em atenção. Para entendê-la, lembre do estimador de regressão por kernel de Nadaraya–Watson:

\[ \hat{f}(x) = \sum_{i} w_i(x) \, y_i, \qquad w_i(x) = \frac{K(x, x_i)}{\sum_j K(x, x_j)} \]

The prediction at \(x\) is an average of the \(y_i\), with more weight on the points whose \(x_i\) is close to \(x\).A previsão em \(x\) é uma média dos \(y_i\), com mais peso nos pontos com \(x_i\) perto de \(x\).

Query, Key and ValueQuery, Key e Value

  • There are three roles: the point where we predict (\(x\)), the points it is compared with (\(x_i\)) and what gets averaged (\(y_i\)).Há três papéis: o ponto onde se prevê (\(x\)), os pontos com que ele é comparado (\(x_i\)) e os valores que entram na média (\(y_i\)).
  • Attention gives these roles names: query (\(x\)), keys (\(x_i\)) and values (\(y_i\)).A atenção dá nome a esses papéis: query (\(x\)), keys (\(x_i\)) e values (\(y_i\)).

Tip

Think of a library search. The query is what you type, the keys are the titles and the values are the books. Attention is a soft search, which takes an average of all the books, with more weight on the titles that match.Pense numa busca na biblioteca. A query é o que você digita, as keys são os títulos e os values são os livros. A atenção é uma busca suave, que leva uma média de todos os livros, com mais peso nos títulos que combinam.

A Learned KernelUm Kernel Aprendido

In Nadaraya–Watson the kernel is fixed. In attention, the three roles are learned linear projections of each \(\mathbf{x} \in \mathbb{R}^p\) of the sequence (in text, the embedding of the word), with the same \(d \times p\) matrices for all:No Nadaraya–Watson o kernel é fixo. Na atenção, os três papéis são projeções lineares aprendidas de cada \(\mathbf{x} \in \mathbb{R}^p\) da sequência (em texto, o embedding da palavra), com as mesmas matrizes \(d \times p\) para todos:

\[ \mathbf{q} = W_Q \mathbf{x}, \qquad \mathbf{k} = W_K \mathbf{x}, \qquad \mathbf{v} = W_V \mathbf{x} \]

  • Similarity is the inner product \(\mathbf{q}^\top \mathbf{k}' = \mathbf{x}^\top W_Q^\top W_K \, \mathbf{x}'\). The network learns which notion of “similar” helps to predict.A semelhança é o produto interno \(\mathbf{q}^\top \mathbf{k}' = \mathbf{x}^\top W_Q^\top W_K \, \mathbf{x}'\). A rede aprende qual noção de “parecido” ajuda a prever.
  • \(W_Q \neq W_K\) because the relation need not be symmetric: what \(a\) looks for in \(b\) is not what \(b\) looks for in \(a\).\(W_Q \neq W_K\) porque a relação não precisa ser simétrica: o que \(a\) procura em \(b\) não é o que \(b\) procura em \(a\).
  • Queries and keys decide the weights, and the values are what gets averaged. For example, the query of “it” looks for a noun and matches the key of “cat”. It then receives the value of “cat”, and the output for “it” comes to represent the cat.Queries e keys decidem os pesos, e os values são o que entra na média. Por exemplo, a query de “ele” procura um substantivo e combina com a key de “gato”. Ela recebe o value de “gato”, e a saída de “ele” passa a representar o gato.

The Attention FormulaA Fórmula da Atenção

It is Nadaraya–Watson with the kernel \(K(\mathbf{q}, \mathbf{k}) = \exp(\mathbf{q}^\top \mathbf{k} / \sqrt{d})\), where \(d\) is the dimension of \(\mathbf{q}\) and \(\mathbf{k}\):É o Nadaraya–Watson com o kernel \(K(\mathbf{q}, \mathbf{k}) = \exp(\mathbf{q}^\top \mathbf{k} / \sqrt{d})\), onde \(d\) é a dimensão de \(\mathbf{q}\) e \(\mathbf{k}\):

\[ \text{Attention}(\mathbf{q}) = \sum_i \underbrace{\frac{\exp(\mathbf{q}^\top \mathbf{k}_i / \sqrt{d})}{\sum_j \exp(\mathbf{q}^\top \mathbf{k}_j / \sqrt{d})}}_{\text{softmax}} \, \mathbf{v}_i \]

With the query “it”, almost all the weight goes to “cat”. Dividing by \(\sqrt{d}\) keeps the scores from getting huge when \(d\) is large.Com a query “ele”, quase todo o peso vai para “gato”. Dividir por \(\sqrt{d}\) evita escores enormes quando \(d\) é grande.

Self-Attention

In self-attention, every word is a query, a key and a value at the same time. Each row shows the weights of one query and sums to 1:Na self-attention, cada palavra é query, key e value ao mesmo tempo. Cada linha mostra os pesos de uma query e soma 1:

The highlighted row is the “it” chart from the previous slide.A linha destacada é o gráfico de “ele” do slide anterior.

Self-Attention in CodeSelf-Attention em Código

Each output is a weighted average of the values of the whole sequence:Cada saída é uma média ponderada dos values da sequência inteira:

torch.manual_seed(0)
batch, T, d = 2, 5, 8
x = torch.randn(batch, T, d)
W_q, W_k, W_v = nn.Linear(d, d), nn.Linear(d, d), nn.Linear(d, d)

q, k, v = W_q(x), W_k(x), W_v(x)
scores = q @ k.transpose(1, 2) / d**0.5      # (batch, T, T): one kernel value per pair
weights = scores.softmax(dim=-1)            # each row sums to 1
out = weights @ v                           # weighted averages of the values
print(tuple(weights.shape), tuple(out.shape))
(2, 5, 5) (2, 5, 8)

PyTorch has ready-made versions, with several “heads” (several \(W_Q, W_K, W_V\)) in parallel:O PyTorch tem versões prontas, com várias “cabeças” (vários \(W_Q, W_K, W_V\)) em paralelo:

layer = nn.TransformerEncoderLayer(d_model=8, nhead=2, batch_first=True)
print(tuple(layer(x).shape))
(2, 5, 8)

Transformers

T cluster_block × N words words emb embedding + position words->emb s1 emb->s1 attn attention s1->attn add1 + s1:n->add1:n attn->add1 mlp MLP add1->mlp add2 + add1:n->add2:n mlp->add2 out prediction add2->out

T cluster_block × N words palavras emb embedding + posição words->emb s1 emb->s1 attn atenção s1->attn add1 + s1:n->add1:n attn->add1 mlp MLP add1->mlp add2 + add1:n->add2:n mlp->add2 out previsão add2->out

  • A Transformer stacks \(N\) identical blocks. Each block has an attention layer and an MLP applied to each word separately.Um Transformer empilha \(N\) blocos iguais. Cada bloco tem uma atenção e um MLP aplicado a cada palavra separadamente.
  • The arrows going around the attention and the MLP are residual connections. Each part outputs \(\mathbf{x} + f(\mathbf{x})\), a correction to its input, as in boosting.As setas que contornam a atenção e o MLP são conexões residuais. Cada parte devolve \(\mathbf{x} + f(\mathbf{x})\), uma correção da entrada, como no boosting.
  • Attention does not see the order, so “dog bites man” would give the same as “man bites dog”. That is why the position of each word is added to the input (positional encoding).A atenção não vê a ordem, e “cachorro morde homem” daria o mesmo que “homem morde cachorro”. Por isso, a posição de cada palavra é somada à entrada (positional encoding).

Important

Language models like ChatGPT, Gemini and Claude are Transformers trained to predict the next token, a classification over the vocabulary with the same nn.CrossEntropyLoss used for any classification.Modelos de linguagem como ChatGPT, Gemini e Claude são Transformers treinados para prever o próximo token, uma classificação sobre o vocabulário com a mesma nn.CrossEntropyLoss de qualquer classificação.

Bonus: Bimodal NetworksBônus: Redes Bimodais

Bimodal NetworksRedes Bimodais

Sometimes each observation comes in two types of data. To price a house, for example, we have a photo and a table (area, bedrooms, neighborhood).Às vezes cada observação vem em dois tipos de dado. Para precificar um imóvel, por exemplo, temos uma foto e uma tabela (área, quartos, bairro).

Each part goes through the architecture suited to it, and the results are concatenated:Cada parte passa pela arquitetura adequada a ela, e os resultados são concatenados:

Bimodal img Photo cnn CNN img->cnn tab Table mlp MLP tab->mlp cat concatenate cnn->cat mlp->cat head MLP cat->head y ŷ head->y

Bimodal img Foto cnn CNN img->cnn tab Tabela mlp MLP tab->mlp cat concatenação cnn->cat mlp->cat head MLP cat->head y ŷ head->y

Tip

Everything is trained together, end to end, and the loss on \(\hat{y}\) adjusts the CNN and both MLPs at the same time. The same idea works for any pair, such as text and image or series and table.Tudo é treinado junto, de ponta a ponta, e a perda em \(\hat{y}\) ajusta a CNN e os dois MLPs ao mesmo tempo. A mesma ideia vale para qualquer par, como texto e imagem ou série e tabela.

Bimodal Networks in CodeRedes Bimodais em Código

class HouseDataset(Dataset):
    def __init__(self, photos, tabular, y):
        self.photos, self.tabular, self.y = photos, tabular, y
    def __len__(self):
        return len(self.y)
    def __getitem__(self, i):
        return self.photos[i], self.tabular[i], self.y[i]

class Bimodal(nn.Module):
    def __init__(self, n_tabular):
        super().__init__()
        self.cnn = nn.Sequential(nn.Conv2d(3, 8, 3, padding=1), nn.ReLU(),
                                 nn.AdaptiveMaxPool2d(1), nn.Flatten())
        self.mlp_table = nn.Sequential(nn.Linear(n_tabular, 8), nn.ReLU())
        self.mlp_final = nn.Sequential(nn.Linear(16, 8), nn.ReLU(), nn.Linear(8, 1))
    def forward(self, photo, tab):
        z = torch.cat([self.cnn(photo), self.mlp_table(tab)], dim=1)
        return self.mlp_final(z).squeeze(-1)

data = HouseDataset(torch.rand(100, 3, 64, 64), torch.randn(100, 5), torch.randn(100))
photo, tab, price = next(iter(DataLoader(data, batch_size=8)))
print(Bimodal(n_tabular=5)(photo, tab).shape)
torch.Size([8])

Exercises: Optimization with PyTorchExercícios: Otimização com PyTorch

1: Poisson Regression (GLM)1: Regressão de Poisson (GLM)

Objective: implement and optimize a Poisson regression with a custom loss function.Objetivo: implementar e otimizar uma regressão de Poisson com função de perda customizada.

We want to model:Queremos modelar:

\[ y_i \sim \text{Poisson}(\lambda_i), \quad \log(\lambda_i) = \mathbf{x}_i^\top \mathbf{w} + b \]

The corresponding NLL is:A NLL correspondente é:

\[ L = \sum_i \left(e^{\mathbf{x}_i^\top \mathbf{w} + b} - y_i(\mathbf{x}_i^\top \mathbf{w} + b)\right) \]

TaskTarefa

  • Generate synthetic data with torch.poisson.Gerar dados sintéticos com torch.poisson.
  • Implement the linear model in PyTorch.Implementar o modelo linear em PyTorch.
  • Implement poisson_nll_loss.Implementar poisson_nll_loss.
  • Train with gradient descent and visualize convergence.Treinar com gradiente descendente e visualizar convergência.

2: Gaussian Mixture Model (GMM)

Objective: fit the parameters of a 1D GMM with two components directly via autograd.Objetivo: ajustar os parâmetros de um GMM 1D com duas componentes diretamente via autograd.

\[ p(y_i) = \pi_1 \mathcal{N}(y_i | \mu_1, \sigma_1^2) + \pi_2 \mathcal{N}(y_i | \mu_2, \sigma_2^2) \]

To enforce constraints:Para impor restrições: - softmax for mixture weights.softmax para pesos da mistura. - exp on log-standard deviations to ensure \(\sigma_k > 0\).exp nos log-desvios para garantir \(\sigma_k > 0\).

TaskTarefa

  • Generate data from a 1D GMM with two Gaussians.Gerar dados de um GMM 1D com duas gaussianas.
  • Define parameters as torch.nn.Parameter.Definir parâmetros como torch.nn.Parameter.
  • Implement gmm_nll_loss with torch.logsumexp.Implementar gmm_nll_loss com torch.logsumexp.
  • Optimize parameters and compare learned density with actual data.Otimizar parâmetros e comparar densidade aprendida com dados reais.

3: Heteroscedastic Linear Regression3: Regressão Linear Heterocedástica

Objective: model conditional mean and variance simultaneously.Objetivo: modelar média e variância condicional simultaneamente.

\[ y_i \sim \mathcal{N}(\mu_i, \sigma_i^2), \quad \mu_i = f_\mu(\mathbf{x}_i), \quad \log(\sigma_i^2) = f_\sigma(\mathbf{x}_i) \]

The NLL can be written as:A NLL pode ser escrita como:

\[ L = \frac{1}{n} \sum_i \left[\frac{1}{2}s_i + \frac{(y_i - \mu_i)^2}{2e^{s_i}}\right], \quad s_i = \log(\sigma_i^2) \]

TaskTarefa

  • Create an nn.Module with two outputs (mu_head and logvar_head).Criar um nn.Module com duas saídas (mu_head e logvar_head).
  • Implement heteroscedastic_gaussian_nll.Implementar heteroscedastic_gaussian_nll.
  • Train on simulated data with increasing variance.Treinar em dados simulados com variância crescente.
  • Plot predicted mean and uncertainty bands (\(\pm 2\sigma\)).Plotar média prevista e bandas de incerteza (\(\pm 2\sigma\)).

Exercises: ArchitecturesExercícios: Arquiteturas

4: CNN (MNIST)

Objective: build and train a CNN to classify digits.Objetivo: construir e treinar uma CNN para classificar dígitos.

Given an image \(\mathbf{X} \in \mathbb{R}^{28 \times 28}\), classify it (0 to 9) by minimizing the Cross-Entropy Loss:Dada uma imagem \(\mathbf{X} \in \mathbb{R}^{28 \times 28}\), classifique-a (0 a 9) minimizando a entropia cruzada (Cross-Entropy Loss): \[ L = -\frac{1}{n}\sum_{i,c} y_{i,c} \log(\hat{y}_{i,c}) \]

TaskTarefa

  • Load MNIST via torchvision.datasets.Carregar o MNIST via torchvision.datasets.
  • Create a model with nn.Conv2d, nn.MaxPool2d, and nn.Linear.Criar modelo com nn.Conv2d, nn.MaxPool2d e nn.Linear.
  • Train in mini-batches (DataLoader) with nn.CrossEntropyLoss(). The network returns the 10 logits, without softmax.Treinar em mini-batches (DataLoader) com nn.CrossEntropyLoss(). A rede devolve os 10 logitos, sem softmax.
  • Evaluate accuracy on the test set.Avaliar a acurácia no teste.

5: MF for Movie Recommendation5: MF para Recomendação de filmes

Objective: apply matrix factorization for recommendation systems.Objetivo: aplicar fatorização matricial para sistemas de recomendação.

We approximate the rating \(r_{u,i}\) (user \(u\), item \(i\)) by:Aproximamos a avaliação \(r_{u,i}\) (usuário \(u\), item \(i\)) por: \[ \hat{r}_{u,i} = \mu + b_u + b_i + \mathbf{p}_u^\top \mathbf{q}_i \]

Minimizing the mean squared error over the \(N\) observed ratings, with \(L_2\) regularization:Minimizando o erro quadrático médio nas \(N\) avaliações observadas, com penalização (\(L_2\)): \[ L = \frac{1}{N} \sum_{(u,i)} (r_{u,i} - \hat{r}_{u,i})^2 + \lambda \left( \sum_u \left(\|\mathbf{p}_u\|^2 + b_u^2\right) + \sum_i \left(\|\mathbf{q}_i\|^2 + b_i^2\right) \right) \]

TaskTarefa

  • Use nn.Embedding for \(p_u, q_i, b_u, b_i\).Usar nn.Embedding para \(p_u, q_i, b_u, b_i\).
  • Compute \(\hat{r}_{u,i}\) in forward and minimize \(L\) (MSE plus the penalty).Calcular \(\hat{r}_{u,i}\) no forward e minimizar \(L\) (MSE mais a penalização).
  • Train on movielens-100k (u1.base) and measure the RMSE on the test set (u1.test).Treinar no movielens-100k (u1.base) e medir o RMSE no teste (u1.test).
  • Provide top-K recommendations for a user.Indicar top-K recomendações para um usuário.

6: RNN for Time Series6: RNN para Séries Temporais

Objective: predict values in a time series using recurrent networks.Objetivo: prever valores em uma série temporal usando redes recorrentes.

Given a sequence \((x_{t-k}, \dots, x_{t})\), predict \(x_{t+1}\) by updating the hidden state \(\mathbf{h}_t\):Dada uma sequência \((x_{t-k}, \dots, x_{t})\), preveja \(x_{t+1}\) atualizando o estado oculto \(\mathbf{h}_t\): \[ \mathbf{h}_t = f(\mathbf{x}_t, \mathbf{h}_{t-1}), \quad \hat{x}_{t+1} = \mathbf{w}^\top \mathbf{h}_t + b \]

TaskTarefa

  • Use the Sunspots dataset (statsmodels.api.datasets.sunspots).Utilizar os dados de manchas solares (statsmodels.api.datasets.sunspots).
  • Format data using history windows.Formatar dados usando janelas do histórico.
  • Implement a model with nn.RNN or nn.GRU and nn.Linear.Implementar modelo com nn.RNN ou nn.GRU e nn.Linear.
  • Train by minimizing MSE and plot predictions against original data.Treinar minimizando MSE e plotar previsões contra dados originais.