Skip to main content

Layer L1

ML / DL Basics

The layer

What this layer is about

The goal of this layer is concrete: you have trained a neural network yourself, and you can explain three things: why it learned, why it sometimes "learns too much", and why the metric you used to score it was chosen the way it was.

Why learn this first, instead of going straight to large language models? Because everything in L2 uses this layer's words: the loss that pretraining watches, how data is split for fine-tuning, which metrics evals use. Without this foundation, LLM training code reads like a string of API calls; with it, you can see which step of the training loop each line belongs to.

The whole layer revolves around one thing: the training loop. First, run it once in your head:

  1. Take a batch of data, say 32 images of handwritten digits;
  2. Have the model make predictions: for each image, how confident it is that it's 0, 1, and so on up to 9;
  3. Compare the predictions with the correct answers and compute one number for "how badly wrong it was", called the loss;
  4. Backpropagation: work out which way each parameter should move a little so the loss goes down; that direction is called the gradient;
  5. Move each parameter a small step in that direction;
  6. Take the next batch and do it again.

Repeat enough times and the model recognizes digits. Every node in this layer covers one step of this loop, or how to judge whether it learned well once the loop has run. Three finish lines: train a small network from scratch, explain overfitting and generalization, and say why an evaluation metric was chosen.

The map of this layer

Five nodes, in learning order:

  • Classical machine learning: learning from examples: the vocabulary, and also the most important discipline: don't test on the questions you practiced on. Data is split into a training set (practice problems), a validation set (mock exams, used to choose settings) and a test set (the real exam, used only once). Scoring perfectly on questions you've already practiced isn't skill; that's called overfitting. Add to that loss, a few classic models, and "when accuracy lies to you".
  • Loss and backpropagation: the two middle steps of the loop. Why the loss is cross-entropy (for classification) or mean squared error (for predicting a number), and why backpropagation is just the chain rule walked backwards along the computation. The best way to learn it is to follow the videos and write your own automatic gradient engine of a hundred-odd lines; once you have, this layer clicks. It connects directly to L0's Optimization and Information theory.
  • PyTorch: train a network yourself: swapping the previous step for a framework. Tensors (multi-dimensional arrays), autograd, and the few-lines-long training loop. Once you know it, no training code you read later will feel foreign.
  • Generalization: explaining the curves you drew. The training loss keeps falling, but the validation loss starts climbing back at some point. Why? Bias and variance are two different kinds of error, regularization is the way to force a model to learn patterns rather than memorize the questions, and there's a strange phenomenon specific to deep networks called "double descent".
  • Classic architectures: CNN, RNN / LSTM, residuals: what the three inventions before the Transformer each solved. CNNs let a vision model share one set of weights across every part of an image, LSTMs use "gates" to let a sequence model remember distant content, and residual connections give the gradient a direct path through. You learn them to understand what the Transformer kept and what it threw away.

Order: classical machine learning → loss and backpropagation → PyTorch; after that, generalization and classic architectures can come in either order.

What you can skip for now

  • You don't need all of classical machine learning. Support vector machines, naive Bayes and clustering can be skipped for now; keep linear models, decision trees and ensembles, and evaluation metrics.
  • Don't learn PyTorch as a big framework. Treat it as "numpy that computes gradients for you", and writing the training loop by hand once is enough.
  • You don't need to know how to tune CNNs and LSTMs. You only need to explain what structure in the data each one assumes up front; leave the details of vision tasks until you actually use them.
  • In Goodfellow et al.'s "Deep Learning", only flip through chapter 5, and use it as a dictionary.
  • Keras, TensorFlow and every high-level training library can be skipped. What they hide is exactly what this layer wants you to see.

Top picks

In reading order; each pick links to its node below.

  1. 1

    Machine Learning Crash Course — Google free

    Short interactive modules that walk you through the vocabulary of loss, data splits and evaluation metrics, words every later node uses → Classical machine learning: learning from examples

  2. 2

    The spelled-out intro to neural networks and backpropagation: building micrograd free

    Write a hundred-odd lines of Python along with it and build automatic gradients yourself. Backpropagation stops being a black box inside a framework → Loss and backpropagation

  3. 3

    Calculus on Computational Graphs: Backpropagation free

    Half an hour on why one pass backwards from the loss gives you every gradient, while computing front to back would be far slower → Loss and backpropagation

  4. 4

    Neural Networks: Zero to Hero — Andrej Karpathy free

    Keep going after micrograd: each episode adds one part, building all the way up to a small GPT → PyTorch: train a network yourself

  5. 5

    Learn the Basics — PyTorch tutorials free

    The framework's own guide to tensors, autograd and the training loop. Keep it open as a manual while you code → PyTorch: train a network yourself

  6. 6

    An Introduction to Statistical Learning with Applications in Python free

    One figure shows how bias and variance trade off, then it explains why cross-validation can estimate how a model does on new data → Generalization

  7. 7

    Deep Double Descent: Where Bigger Models and More Data Hurt free

    Explains why large models with far more parameters than data don't overfit badly the way the textbooks predict → Generalization

  8. 8

    Dive into Deep Learning free

    What flaw of the previous generation CNN, ResNet, RNN and LSTM each fixed, with runnable code in every chapter → Classic architectures: CNN, RNN / LSTM, residuals

  9. 9

    Understanding LSTM Networks free

    Four diagrams show how the LSTM's gates let it remember distant content. The shortest path to understanding what attention replaced → Classic architectures: CNN, RNN / LSTM, residuals

The nodes

Classical machine learning: learning from examples

errortraining time →stop heretraining datanew dataoverfitting

Machine learning means not writing the rules yourself, and letting the program find the patterns in examples. Take deciding whether an email is spam. The traditional way is to write rules by hand ("if it says 'you've won', it's spam"); the machine learning way is to give it a few thousand emails labeled "spam / not spam" and let it work out which features are related to the outcome. For decades before language models, this idea was already mature on tabular data; an LLM is the same idea taken to an enormous size.

How a model "learns"

A model is a function with lots of adjustable numbers (called parameters): it takes the features of an email and outputs how confident it is that the email is spam. Learning means adjusting these parameters, guided by the loss: a number that measures how badly the model does on examples whose answers are known. The more mistakes, the bigger the loss, and training is adjusting the parameters again and again to make the loss smaller (for how to adjust them, see Optimization).

A few common model families, from simple to strong: linear models (multiply each feature by a coefficient and add them up, as in logistic regression); decision trees (a chain of yes-or-no questions, like a guessing game); ensembles (many trees voting, or one tree after another correcting the mistakes of the ones before, as in gradient-boosted trees). On tabular data, gradient-boosted trees still often work better than neural networks.

The most important rule: don't test on questions it has practiced

Picture a student who memorized a workbook together with its answers. Test him with questions from that workbook and he gets full marks; give him a set he has never seen, and he falls apart. A model is the same, so the data is split into three parts:

  • Training set: the practice questions the model drills on.
  • Validation set: the mock exam. You use it to compare different models and tune settings (how long to train, how big the model is).
  • Test set: the real exam, used only once, at the end. You have looked at the validation set again and again and used it to make choices, so over time it too has effectively been "drilled"; only a test set you have never touched gives an honest estimate of real performance.

If you evaluate on the training set, the model will look better than it really is. If you train too long with a model that is too flexible, it memorizes the training examples along with the random noise in them, and does worse on new data. This is called overfitting. Why it happens, how to measure it and how to treat it are the subject of Generalization.

Metrics: get the score right

A metric is the number you finally report to say how good the model is. The most intuitive one is accuracy (the share of guesses that are right), but it often misleads. Suppose only ten out of a thousand emails are spam: a model that always answers "not spam" has 99% accuracy and catches none of them. Here you need precision (of the emails it called spam, how many really are) and recall (of the emails that really are spam, how many it caught). Which metric to pick depends on which mistake costs more: missing a scam email or wrongly blocking a work email, which can you less afford?

Where it shows up later

This node is the vocabulary for everything that follows: the loss that LLM pretraining watches, the metrics in Evals: knowing whether it got better, and the data splits in Fine-tuning: teach it your task all use the words from here. Fall into these traps first on small tabular data, where one training run takes a few seconds; that is much cheaper than falling into them on a large model. That is exactly this node's project: train a logistic regression and a gradient-boosted tree on the same tabular dataset, with the three splits kept clean, then find an example where accuracy misleads.

Builds on
Math: learn it when you need it
Leads to
Generalization · PyTorch: train a network yourself
On the routes
Foundations (Machine learning, the classical way)
  • Machine Learning Crash Course — Google free

    course · about 15 hours — The fundamentals — loss, generalisation, splits, classification metrics — in short interactive modules, updated by Google in 2024.

Hands-on project: A baseline you can defend — Train logistic regression and gradient-boosted trees on one tabular dataset with a proper train, validation and test split, and explain one case where accuracy is the wrong metric.

Not picked (3)
  • An Introduction to Statistical Learning (ISLP) — Very good, but the bias–variance and cross-validation chapters fit better in the generalization node, and the model-family part overlaps with Google's course.
  • Raschka, Machine Learning with PyTorch and Scikit-Learn — Paid and thick; the hands-on part is already covered by Google's course and PyTorch: train a network yourself.
  • scikit-learn User Guide — For looking up the API, not a learning path.

Loss and backpropagation

ml-mathoptimizationinformation-theorybackprop-and-lossclassic-architecturespytorchtransformer

Training a network means repeating the same four-step loop thousands upon thousands of times. Run it once in your head first:

  1. Forward: take a small batch of data (say, 32 images of handwritten digits) and let the model compute its predictions: for each image, how confident it is that the digit is 0, 1, and so on up to 9.
  2. Compute the loss: compare the predictions with the correct answers and get a single number that says how badly this batch went.
  3. Backpropagate: compute the gradient of every parameter, that is, "if this parameter moves up a little, does the loss go up or down, and how fast?"
  4. Update: move every parameter a small step in the direction that lowers the loss.

Then take the next batch and do it again. After enough rounds, the model recognizes digits. Step 1 is the model itself; step 4 is the optimizer from Optimization. This node covers the two steps in the middle.

The loss function: one number for how wrong it was

A loss has to meet two conditions: the worse the prediction, the bigger it gets; and it changes smoothly with the parameters, so you can take its gradient. Two kinds are used most:

  • Cross-entropy (for classification): look only at the probability the model gave the correct answer, and take its negative log. If the model gives the right answer 0.9, the loss is about 0.1; if it gives it only 0.01, the loss is about 4.6. Being wrong and confident is punished hard.
  • Mean squared error (MSE, for predicting a number, such as a house price): square the difference between the prediction and the true value, then average. The further off you are, the harsher the penalty.

Why these two in particular? Each one matches an assumption about the data. Cross-entropy matches "the answer is one pick out of a few categories"; MSE matches "the true value is scattered randomly around the prediction, along a bell curve (a normal distribution)". Under its own assumption, minimizing each one is the same as doing maximum likelihood (Probability and statistics, Information theory).

Backpropagation: handing the "blame" back layer by layer

The loss is a single number, but there are thousands upon thousands of parameters. Backpropagation answers this question: this time the model was wrong, so how much of the blame does each parameter carry? It works by the chain rule. First see how the loss changes with the last layer, then how the last layer changes with the one before it, and so on. Multiply these "rates of change" together layer by layer, from the back to the front, and you have the gradient of every parameter.

The key is "from the back to the front". You can draw the model's computation as a graph, called the computation graph, where each node is one operation. Start from the single loss and walk the graph backwards once, and you get the gradients of all the parameters in one pass. Go the other way, starting from each parameter and computing forward, and you need one pass per parameter. That is why it is called "back" propagation, and it is also why training large models is affordable at all. The method was made widely known in 1986 by a paper, and it made multi-layer networks trainable in practice for the first time.

One result you cannot skip: p − y

The last step of a classification model is usually softmax: it turns the model's output, a list of scores of any size (called logits), into a set of probabilities that add up to 1. Put cross-entropy after softmax, take the gradient with respect to the logits, and the result is surprisingly simple: p − y. Here p is the probability the model gives each class, and y is the correct answer (1 for the right class, 0 for all the others).

In words: for the correct class, the gradient is "probability minus 1", a negative number, so the update pushes its score up, by as much as its probability still falls short of 1. For each wrong class, the gradient is just its probability, a positive number, so the update pushes its score down, and the more probability it was given, the harder it gets pushed. The more right the model is, the closer p is to y, the smaller the gradient, and the gentler the update. The L0 self-check asks you to derive this result on paper.

The fastest way to learn it

In PyTorch, the one line loss.backward() does everything this node describes. The fastest way to learn it is to write it once yourself without a framework: follow the video in the picks, write a small engine that computes gradients automatically in a hundred-odd lines of Python, then train a small network with it. After that, go to PyTorch: train a network yourself, and you will see clearly which steps the framework saves you. The L1 reproduction project hangs here too: train a two-layer network using only tensor operations, and plot the training loss and the validation loss as two curves. Why the two lines split apart at some point is explained in Generalization.

Builds on
Math: learn it when you need it · Optimization · Information theory
Leads to
Classic architectures: CNN, RNN / LSTM, residuals · PyTorch: train a network yourself · Transformer
  • The spelled-out intro to neural networks and backpropagation: building micrograd free

    video · 2.5 hours + 3 hours coding · only 0:00–2:25:52 — Write a scalar autograd engine in 100-odd lines, train a small MLP on it. Backprop becomes code you can write and check yourself: this layer's 'train a small network from scratch'.

  • Calculus on Computational Graphs: Backpropagation free

    article · 30 minutes — Frames backprop as forward and reverse mode differentiation on a graph. One page shows why reverse mode is cheap for many inputs and one loss. It answers 'why not forward mode?'

Hands-on project: Train a small network from scratch and plot training/validation curves — Write a two-layer MLP using only tensor operations (no nn.Module, no optimizer). Train it on MNIST or make_moons, record training and validation loss each epoch, and plot them as one chart. First let it overfit (the curves diverge), then add weight decay or dropout to close the gap. The output is two charts and a short explanation.

Not picked (3)
  • 3Blue1Brown「Backpropagation calculus」 — Fourth episode of the series, same source as the intro video in Math: fill in when needed; watching episode one leads into it naturally.
  • CS231n notes「Backpropagation, Intuitions」 — Well explained, but Olah's piece is shorter and also covers the forward/reverse mode comparison.
  • Goodfellow 等《Deep Learning》ch. 6.5 — Formal but dense; writing micrograd along with it gives more.

PyTorch: train a network yourself

Who asks for it

forwardmodel(x)lossloss_fn(out, y)backwardloss.backward()stepopt.step()every batch

PyTorch is the Python library most of today's models are written and trained with. When you first learn it, you can think of it as "numpy that computes gradients automatically and runs on a GPU".

Two core things

  • Tensor: a multi-dimensional array of numbers. A single number is zero-dimensional, a list of numbers is one-dimensional, a table is two-dimensional, and a batch of color images (number of images × color channels × height × width) is four-dimensional. A model's inputs, outputs and weights are all tensors.
  • autograd (automatic differentiation): you just write the forward computation, and behind the scenes PyTorch records every step and links them into a computation graph; call loss.backward() and it walks the graph backwards and works out the gradient of every weight. This is the backpropagation from Loss and backpropagation, done for you by the framework.

What a training loop looks like

PyTorch training code is almost always the same short loop, matching the four steps in Loss and backpropagation one to one: take a batch of data → the model computes predictions → compute the loss → backward() computes the gradients → the optimizer's step() updates the weights, and then the gradients from this round are reset to zero (PyTorch adds gradients up by default, so if you don't reset them, the next round comes out wrong). The whole of training is these few lines repeated thousands upon thousands of times. Once you understand them, you can open the training script of any open-source model and find where they are.

Why write it yourself instead of just calling it

High-level training libraries, the kind where a few lines of config train a model, are convenient, but what they hide is exactly what you need to see: how the loss is computed, when the gradients are reset, how the data is split into batches. So this node's way of learning is bottom-up: first write that loop by hand, then build all the way from a tiny network up to a small GPT. The video series in the picks follows exactly this path, with Andrej Karpathy adding just one new part per episode; keep the official tutorials as a manual to look things up in.

Where it leads

By this point, a model's structure diagram is no longer just a picture to you: you know which lines of code each box is. It is a prerequisite for Transformer (writing a GPT from scratch) and Fine-tuning: teach it your task (continuing to train a model someone else trained). This node's project is to reproduce a small GPT, then change just one design choice and compare the loss curves before and after. This kind of "change one thing and see how the result moves" experiment is called an ablation, and it is the basic skill for understanding the experiments section of any paper.

Builds on
Classical machine learning: learning from examples · Math: learn it when you need it · Loss and backpropagation
Leads to
Classic architectures: CNN, RNN / LSTM, residuals · Fine-tuning: teach it your task · Transformer
On the routes
Foundations (Machine learning, the classical way) · AI Engineer (Train and post-train)
  • Neural Networks: Zero to Hero — Andrej Karpathy free

    course · about 15 hours + coding — Backprop to a GPT in PyTorch, one video at a time — the fastest way for an engineer to read and debug model code.

  • Learn the Basics — PyTorch tutorials free

    docs · 2 hours — Tensors, autograd, datasets and the training loop in the framework's own words; a reference you will return to.

Hands-on project: Train a small GPT and change one thing — Reproduce a small model with nanochat or nanoGPT on a modest dataset, change one design choice, and show the ablation with its loss curves.

Not picked (3)
  • fast.ai Practical Deep Learning for Coders — Top-down: you get results first with a high-level library. This layer needs you to see the training loop itself, so Zero to Hero fits better.
  • Dive into Deep Learning — Already a candidate under Classic architectures: CNN, RNN / LSTM, residuals, so not repeated here.
  • PyTorch 官方「60 Minute Blitz」 — Overlaps with Learn the Basics, which is more recent.

Generalization

classical-mlgeneralization

Generalization is about whether a model does well on data it has never seen. A low loss on the training set only shows that the model can do the questions it practiced; what we really care about is whether it can do new ones.

A gap: training error and test error

Back to the analogy from Classical machine learning: learning from examples: the training set is the workbook, the test set is the real exam, and the gap between the two scores is the gap that generalization studies. You will see it with your own eyes in the project for Loss and backpropagation: the training loss keeps going down, the validation loss goes down with it at first, then at some point stops and starts climbing, and the two curves split from there. After the split, the model is memorizing questions rather than learning patterns. This is overfitting.

Bias and variance: two different kinds of error

  • High bias: the model is too simple to do even the workbook well, like trying to trace a curved pattern with a single straight line. This is called underfitting.
  • High variance: the model is too flexible and memorizes the accidental details of every question in the workbook; give it a different batch of training data and what it learns changes a lot. This is overfitting.

The bigger a model's capacity (how complex a pattern it can express; roughly, how many parameters it has), the lower the bias and the higher the variance. The classic textbook conclusion: there is a best point in the middle, and test error first falls and then rises as capacity grows, which draws a U shape.

Regularization: forcing the model to learn patterns

Regularization is a family of methods that deliberately "make trouble" for the model, forcing it to learn patterns instead of memorizing details:

  • weight decay: at every step, pull the weights a little towards 0, so they don't grow too large just to accommodate a few individual examples.
  • dropout: during training, randomly switch off some of the neurons at each step, so the model cannot lean entirely on a few particular "memory spots".
  • Early stopping: watch the validation loss, and stop training as soon as it starts to rise.
  • Data augmentation: flip an image, crop it, change its brightness, and feed it in again as a new example; it is like asking the same question in different words.

There is also a way to estimate generalization called cross-validation: when data is scarce, cut it into several parts, take turns using one part as the validation set and the rest for training, and average at the end. The estimate is steadier.

A strange thing about deep networks: double descent

By the U-shaped curve, a large network with far more parameters than data points should overfit badly, yet in practice such networks often generalize well. Researchers found that as you make the model bigger and bigger, test error first rises along the U, peaks around the point where "there are just enough parameters to memorize the training set completely", and then comes down again. This is called double descent. It shows that the classic bias–variance picture tells only the first half of the story for deep networks.

Where it leads

Generalization is the theory behind "why the data has to be split" in Classical machine learning: learning from examples, and it is the key to reading your own training curves. In Pretraining and scaling, scaling laws are still about the same question: how the amount of data, the number of parameters and the model's error on new data relate to each other. This node's project is to produce overfitting on purpose: make a small network's parameter count ten times, then a hundred times larger, plot how error changes with the parameter count, and see whether you can spot double descent on a small dataset.

Builds on
Classical machine learning: learning from examples
  • An Introduction to Statistical Learning with Applications in Python free

    book · about 12 hours · only ch. 2–5 — Ch. 2 draws the bias–variance trade-off and train/test error in one picture; ch. 5 shows why cross-validation estimates generalization error. The standard answer on overfitting.

  • Deep Double Descent: Where Bigger Models and More Data Hurt free

    paper · 1 hour — The classic U-shaped curve falls again in overparameterized deep networks. When asked why huge models don't overfit, you can answer one layer deeper than the textbook.

Hands-on project: Make overfitting happen, then fix it — Take the small network from the [[backprop-and-loss]] project. Raise the parameter count to 10× and then 100×, plot training and validation error against parameter count, and see whether you can reproduce double descent on a small dataset. Write a paragraph explaining the cause of each part of the curve.

Not picked (3)
  • Goodfellow 等《Deep Learning》ch. 5, 7 — Thorough, but the two ISLP chapters are shorter and come with code; ch. 5 is already a candidate in Classical machine learning: learning from samples.
  • Zhang 等「Understanding deep learning requires rethinking generalization」(2017) — A landmark paper that posed the problem, but the double descent paper gives a more usable picture.
  • Bishop, Pattern Recognition and Machine Learning ch. 1 — A solid Bayesian view, but too slow to read.

Classic architectures: CNN, RNN / LSTM, residuals

backprop-and-losspytorchclassic-architecturesmultimodal

The simplest neural network is the fully connected network (MLP): every output of each layer is connected to every input of the layer before. It can learn anything, but it assumes nothing about the data, and that causes two problems: too many parameters, and no way to see the structure the data already has. Before the Transformer arrived, three key inventions each solved one specific problem. You learn them not to use them today, but to understand what the Transformer kept, what it threw away, and why.

CNN: patterns in an image are the same everywhere

A cat is a cat whether it sits in the top-left corner of the image or the bottom-right. The convolutional neural network (CNN) builds this common sense into its structure: a small window (say, 3×3 pixels) slides across the whole image, and at every position it uses the same set of weights to look for the same pattern, such as an edge or a corner. This is called local connectivity and weight sharing. A fully connected layer needs a weight between every pixel and every output, so the parameter count explodes as images grow; a convolution window has only a few dozen weights, reused across the whole image.

An assumption built into the structure like this is called an inductive bias: if the assumption is right, the model learns with less data and fewer parameters. Gradient-Based Learning Applied to Document Recognition used a CNN to read handwritten digits, and ImageNet Classification with Deep Convolutional Neural Networks used one in 2012 to win the ImageNet image recognition competition by a wide margin, which started the current wave of deep learning.

RNN and LSTM: reading one word at a time

Text and speech are sequences of no fixed length. A recurrent neural network (RNN) reads one word at a time, squeezes what it has read so far into a "memory" vector that it passes along, and consults that memory when it reads the next word. The trouble is in training. The gradient has to travel back along this chain one step at a time, getting multiplied once at each step, so over a long chain it keeps shrinking until it is almost 0. This is called vanishing gradients, and the result is that an RNN cannot remember things from far back. LSTM (long short-term memory, Long Short-Term Memory) adds a few "gates": at each step the network itself decides which old memories to keep, which to forget, and what new content to write in. The memory now has a channel through which it can pass along mostly unchanged, so information from far back survives.

Residuals: a direct route for the gradient

In principle, the deeper a network, the stronger it is; in practice, networks that are too deep stop training at all, because by the time the gradient has traveled back from the loss through dozens of layers, it has vanished. The residual connection (Deep Residual Learning for Image Recognition) fixes this simply: each layer's output = that layer's input + the change that layer computes. In other words, each layer is only responsible for "adding a small change on top of what came in". The gradient can then travel straight through dozens or hundreds of layers along the "unchanged" line. Without it there would be no deep networks today, and no Transformer either: every sublayer of the Transformer is wrapped in exactly this kind of straight-through line.

How it connects to the Transformer

The Transformer kept residuals and normalization and threw away recurrence. It no longer reads one word at a time; instead it uses attention to let every word look directly at every other word, so it can compute in parallel and distance does not hurt it. Once you understand the gates of an LSTM, you see what attention replaced. CNNs have not disappeared either: in Multimodal, the vision encoder that looks at images is either a convolutional network or a ViT, which cuts the image into small patches and treats them as tokens.

The prerequisites for this node are Loss and backpropagation and PyTorch: train a network yourself. The project is to train an MLP, a 1D CNN and an LSTM on the same sequence classification task, compare their parameter counts, training times and accuracy, and see what each structure's built-in assumption corresponds to in the data.

Builds on
Loss and backpropagation · PyTorch: train a network yourself
Leads to
Multimodal
  • Dive into Deep Learning free

    book · about 20 hours · only ch. 7–10 — Four chapters: CNN, modern CNN (ResNet), RNN, modern RNN (LSTM). Each names the flaw of the last generation, then gives runnable PyTorch. After it you can say what each one solved, in one line.

  • Understanding LSTM Networks free

    article · 30 minutes — Four gate diagrams show why LSTM remembers distant information and a plain RNN cannot. It is the shortest path to understanding what the Transformer's attention replaced.

  • CS231n Convolutional Neural Networks for Visual Recognition — course notes: Convolutional Networks free

    course · 1 hour — Convolution, stride, padding, receptive field, parameter sharing, each with a countable diagram. You can compute any layer's output size and parameters, the base skill for vision backbones.

Hands-on project: Run one task on three architectures — On a small sequence classification dataset, train an MLP, a 1D CNN and an LSTM. Record parameter count, training time and validation accuracy. Write a paragraph on what each architecture's inductive bias corresponds to in the data.

Not picked (3)
  • He 等「Deep Residual Learning for Image Recognition」(2015) — The original residual paper, but d2l ch. 8 already explains it and gives an implementation.
  • Goodfellow 等《Deep Learning》ch. 9–10 — The content is right, but it has no code and no residuals.
  • fast.ai Practical Deep Learning for Coders — Top-down, using high-level libraries, so you can't see the architecture itself.

Self-check

  • Without nn.Module or an optimizer, using only tensor operations, I can train a two-layer MLP (multilayer perceptron, the simplest kind of fully connected network) to a reasonable validation accuracy. (Hint: nn.Module and optimizer are the model and update step PyTorch packages up for you; without them you write the forward pass, zero the gradients and update the weights yourself.)
  • I can plot the training / validation loss curves, point to the epoch where overfitting begins, and use one regularization method to close the gap between the two lines. (Hint: an epoch is one pass over the whole training set; overfitting starts where the validation loss begins to climb back up.)
  • I can give a case where accuracy is the wrong metric, and say what to use instead and why. (Hint: think of data with very few positives, such as ten spam emails out of a thousand.)
  • In three sentences, I can say what problem each of CNN, LSTM and residual connections solved. (Hint: too many parameters, can't remember far back, too deep to train.)
  • I can say how the bias–variance tradeoff relates to double descent. (Hint: the U-shaped curve covers the first half; what happens as the model keeps getting bigger?)

Hands-on projectTrain a small network from scratch and plot the training and validation loss as two curves. First make it overfit on purpose and watch the two lines split apart at some point; then add weight decay (keeping weights from growing too large) or dropout (randomly switching off some neurons during training) and watch the gap close. The output is two plots and a paragraph explaining what happens in each (attached to Loss and backpropagation).

Spot a mistake on this page?