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.
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 waysx = torch.tensor([[1, 2], [3, 4]], dtype=torch.float32)print(f"Tensor from list:\n{x}\n")# Attributesprint(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] =99print(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 operationsprint("Sum:", x + y)print("Product (Hadamard):", x * y)# Matrix multiplicationprint("Matrix Product (@):", x @ y)print("Matrix Product (matmul):", torch.matmul(x, y))# Reshapingprint("Original shape:", x.shape)print("Reshaped (view):", x.view(4, 1).shape)
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 availabledevice ="cuda"if torch.cuda.is_available() else"cpu"print(f"Using device: {device}")# Create tensors on the chosen devicex_gpu = torch.randn(1000, 1000, device=device)y_gpu = torch.randn(1000, 1000, device=device)# The operation is executed on the devicez_gpu = x_gpu @ y_gpu# To use with libraries like Matplotlib or NumPy, move back to CPUz_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 trackingx = torch.tensor(2.0, requires_grad=True)# Define the functiony = x**2* torch.sin(x)# Compute the gradienty.backward()# The gradient is stored in x.gradprint(f"Gradient of y with respect to x at x=2: {x.grad.item():.4f}")# Analytical value for comparisonanalytic_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 datay_hat = w * x_obsy_hat.backward() # We'll see more about this laterprint("gradient at w:", w.grad)with torch.no_grad(): pred = w *10print("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 + aprint("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.
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.
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.
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):
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):returnself.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 =10000for epoch inrange(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
nn.Module: standard container for parameters and forward logic.nn.Module: container padrão para parâmetros e lógica forward.
nn.Linear: pre-built module with weights and bias.nn.Linear: módulo pré-construído com pesos e intercepto.
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.
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.
torch.save(model_logistic.state_dict(), "logistic.pt")model = LogisticRegressionModel(n_features) # same architecture, new parametersmodel.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:
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:
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:
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:
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\):
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
MLP for Binary ClassificationMLP para Classificação Binária
from torch.utils.data import DataLoader, TensorDatasetloader = 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 inrange(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:
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.
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):
Regularization in PracticeRegularização na Prática
HyperparametersHiperparâmetros
In rough order of importance:Em ordem aproximada de importância:
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).
Model size: width and depth.Tamanho do modelo: largura e profundidade.
Regularization: weight decay and dropout.Regularização: weight decay e dropout.
Optimizer and batch size.Otimizador e tamanho do lote.
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.
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:
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:
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.
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\).
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.
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\):
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:
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:
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:
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}\):
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, 8x = 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 pairweights = scores.softmax(dim=-1) # each row sums to 1out = weights @ v # weighted averages of the valuesprint(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:
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:
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.
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.
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.
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.
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.