Deep Learning with PyTorch


Deep Learning with PyTorch

Maria
Welcome in. Today we’re taking a wide-angle tour of deep learning with PyTorch: from tensors and simple neural networks to training, evaluation, and more specialized models for images, sequences, and multiple inputs or outputs. The big idea is to understand not just how to build a model, but how to tell whether it’s learning and how to improve it.

Anna
And it helps to start with what deep learning is. It’s a subset of machine learning built around networks of inputs, hidden layers, and outputs. The original inspiration was the way interconnected neurons in the brain learn, which is why these models are called neural networks. They can power tasks such as translation, medical diagnostics, chatbots, and self-driving cars.

Maria
The layers let a network build representations of data, but deep learning often needs far more examples than other machine-learning approaches—typically at least hundreds of thousands of data points. We’ll use PyTorch, a widely used, well-maintained framework with a Python-friendly style. Its central data structure is the tensor, which is much like an array or matrix.

Anna
You can create a tensor from a Python list or a NumPy array using PyTorch’s tensor functionality. Two useful checks are its shape and data type: the shape tells you how its dimensions line up, and the data type tells you what kind of values it holds. Those checks help catch mismatches before they become confusing model errors.

Maria
Tensors support the operations that neural networks use constantly. Addition and subtraction require compatible shapes—in the basic case we’re discussing, the shapes must match exactly—and multiplication can be done element by element. Matrix multiplication is different: each result combines a row from the first matrix with a column from the second, multiplying corresponding values and summing them.

Anna
Let’s build from that into a network. The input layer represents the features in a data set, the output layer represents predictions, and hidden layers sit between them. A network with no hidden layer and a single fully connected linear layer is equivalent to a linear model. It’s a useful starting point before we add complexity.

Maria
In PyTorch, the neural-network module is conventionally imported as `nn`. A linear layer needs an input dimension and an output dimension. If one input example has three features and we want two outputs, the layer must take three input features and produce two output features. The output shape follows those choices.

Anna
That linear layer has weights and biases. A weight represents how much an input feature contributes to a neuron’s calculation; a bias gives the neuron an additional baseline term. PyTorch initializes these values randomly at first, and training later adjusts them. For example, in a weather model, humidity might receive a stronger weight if it is especially useful for predicting rain.

Maria
To make a deeper network, we can put layers in sequence using `nn.Sequential`. The dimensions have to connect: the output size of one layer must equal the input size of the next. So a layer that maps ten features to eighteen can feed a layer that maps eighteen to twenty, which can feed one that maps twenty to five.

Anna
Those connections also explain parameter counts. In a fully connected layer, each output neuron has one weight for every input from the previous layer, plus one bias. If a layer has eight input values and four output neurons, that’s four times nine, or thirty-six parameters. A following layer with four inputs and two outputs adds ten, for forty-six parameters total.

Maria
PyTorch can count those parameters for us by iterating over them and summing their numbers of elements. It’s worth understanding the count because it gives us a sense of model capacity. More parameters can help a model handle more complex data, but they can also mean longer training and greater risk of overfitting; too few can limit what it learns.

Anna
A stack of linear layers alone still describes a linear relationship. Activation functions add non-linearity, which allows networks to learn more complex interactions. The output from a final linear layer, before it goes through an activation, is often called the pre-activation output. What activation we use depends partly on the prediction task.

Maria
For binary classification, sigmoid turns a number into a value between zero and one, so it can be interpreted as a probability. If a model outputs six before sigmoid, the transformed result is close to one. With a threshold of 0.5, we classify values above the threshold as class one and values below it as class zero.

Anna
For a problem with more than two classes, softmax turns a set of class scores into probabilities that sum to one. If the three class probabilities are, say, highest for the second class, the model predicts that class. In PyTorch, softmax can be applied along the last dimension, which is useful when each row represents a different example.

Maria
Now we can describe a forward pass. Input data moves through the layers in order, with each layer transforming it using the model’s weights and biases, until the final output is produced. Forward passes are used both to make predictions and during training. The final output could be a class probability or a continuous numerical estimate.

Anna
For example, suppose we have five animals, each described by six features. A network with two linear layers and a final sigmoid could produce one probability per animal for a binary task, such as mammal versus not mammal. We could turn those probabilities into labels with a threshold, but at this stage the predictions may not yet be meaningful—the parameters still need to be trained.

Maria
For three-class classification, the final layer would produce three scores per animal, and softmax would convert them into three probabilities. The output would have five rows and three columns, with each row’s probabilities summing to one. For regression, predicting something like animal weight, the final layer instead produces one continuous value per animal, with no sigmoid or softmax at the end.

Anna
To measure whether predictions are good, we use a loss function. It compares a model’s prediction with the true answer, also called the ground truth, and returns a number. A correct prediction should generally have lower loss than a poor one. Training tries to minimize that loss.

Maria
For multi-class classification, the target label might be an integer such as zero, one, or two. One-hot encoding represents that class as a vector: with three classes, class zero becomes one-zero-zero, class one becomes zero-one-zero, and class two becomes zero-zero-one. PyTorch’s functional tools can create this encoding without us writing it by hand.

Anna
A common classification loss is cross-entropy loss. It compares the model’s class scores with the correct class information and returns a single loss value for the example or batch. The model’s scores are the values before the final softmax in this setup. For regression, a common choice is mean squared error, or MSE: the average of the squared differences between predictions and true values.

Maria
How do we reduce loss? Gradients tell us how the loss changes as a parameter changes. You can picture loss as a landscape: on a steep slope, the derivative is large; near a flat point, it is small. The goal is to move parameters toward a low point. Real neural-network loss landscapes can have multiple local minima, so finding the global minimum is not always straightforward.

Anna
This is where backpropagation comes in. After a forward pass and loss calculation, we compute gradients with respect to the model’s parameters, working back through the layers. PyTorch’s backward operation calculates those gradients and stores them on the parameters. They indicate how the weights and biases should change to reduce loss.

Maria
One basic update rule subtracts the learning rate multiplied by the gradient from a parameter. The learning rate controls the size of that update. In practice, we generally use an optimizer to manage these updates. Stochastic gradient descent, or SGD, can be given all the model’s parameters and a learning rate, then used to take an update step.

Anna
Learning rate matters a lot. If it’s too small, the optimizer can make painfully slow progress. If it’s too large, it may jump back and forth across the minimum instead of settling near it. A typical range discussed for learning rates is about 0.01 to 0.0001, but the right value depends on the problem.

Maria
Momentum can help too. It uses information from previous updates so the optimizer can keep moving through a shallow spot or past a local dip instead of stopping immediately. A momentum value around 0.9 is one example. The effect of learning rate and momentum is something we monitor during training, not a guarantee that every problem will behave the same way.

Anna
Before training, we need to prepare data. A common workflow is to read tabular data, separate the feature columns from the target column, and convert them into arrays and then tensors. A tensor data set stores features alongside labels and lets us retrieve individual examples. A data loader then serves those examples in batches.

Maria
Batch size is the number of examples in each iteration, while shuffling randomizes their order. Batches make large data sets more manageable, and shuffling can help a model generalize rather than rely on a fixed ordering. One epoch means a complete pass through the training data. If five examples are loaded in batches of two, the final batch contains just one example.

Anna
A training loop repeats this process over multiple epochs. For each batch, we clear old gradients, run a forward pass, calculate loss, backpropagate to compute new gradients, and ask the optimizer to update the parameters. In regression, the targets and predictions need compatible floating-point types, and MSE is a natural loss choice.

Maria
We also have to consider how activation functions affect gradients. Sigmoid and softmax have bounded outputs, and their gradients can become very small for some inputs. When gradients shrink repeatedly as they travel backward, earlier layers may barely update. That’s the vanishing-gradient problem, one reason sigmoid and softmax are generally used at a model’s output rather than throughout hidden layers.

Anna
ReLU is a common hidden-layer activation. It returns the input for positive values and zero for negative values, so its gradient does not shrink toward zero for large positive inputs. Leaky ReLU changes the negative side: instead of returning zero, it returns a small multiple of the input. That keeps a non-zero gradient for negative inputs and can help prevent a neuron from stopping its learning altogether.

Maria
The size of initial weights also matters for stable learning. Small weights can help keep the weighted sums in a reasonable range, and different initialization methods aim to support stable signals through the network. PyTorch provides initialization tools, including uniform initialization. For ReLU-like activations, a method such as Kaiming initialization is designed to help preserve the variance of inputs and outputs.

Anna
A related technique is batch normalization. It normalizes a layer’s outputs using the batch mean and standard deviation, then learns scale and shift values. This helps control the distribution of inputs passed to the next layer and can speed up loss reduction while making training less vulnerable to unstable gradients. In a model, the batch-normalization layer needs the same feature size as the preceding layer’s output.

Maria
For more robust training, the optimizer can be changed too. SGD’s update size depends on the learning rate. Adagrad reduces learning rates for parameters that are updated frequently, which can suit sparse data, but its learning rate can shrink too quickly. RMSprop adapts learning rates using the size of recent gradients.

Anna
Adam combines ideas from RMSprop and momentum, using information about gradient size and a weighted average of past gradients. It’s a versatile, widely used optimizer and often a reasonable default. No optimizer removes the need to monitor training, but trying different optimizers can help when learning is unstable or slow.

Maria
A model that does well on its training data may still fail on new examples, so we split data into training, validation, and test sets. Training data updates parameters. Validation data helps us choose hyperparameters such as learning rate and momentum. The test set is reserved to evaluate final performance.

Anna
We can track loss across training and validation. After each epoch, average the training loss across batches. Then switch the model to evaluation mode, disable gradient calculations, and calculate validation loss without updating weights. After validation, switch back to training mode. If training loss keeps falling while validation loss rises, that’s a classic sign of overfitting.

Maria
Accuracy offers another view, especially for classification. In a multi-class problem, choose the class with the highest predicted score or probability using an argmax operation, then compare those class indices with the true labels. A metric can accumulate results across batches, compute accuracy at the end, and be reset before the next epoch.

Anna
Overfitting means the model has learned the training examples too specifically and doesn’t generalize well. A small data set, excessive model capacity, or large weights can contribute. Possible responses include reducing model size, adding dropout, using weight decay, collecting more data, or applying data augmentation.

Maria
Dropout randomly turns off a fraction of neurons during training, so the model can’t depend too heavily on particular features. It’s commonly placed after an activation function. During evaluation dropout is disabled, so all neurons contribute to stable predictions. That’s why it’s important to put the model into the correct training or evaluation mode.

Anna
Weight decay is another form of regularization. It penalizes large weights through the optimizer, encouraging parameters to stay smaller; a small value such as 0.001 is one example. Stronger weight decay can reduce overfitting, but too much regularization can also keep the model from learning effectively.

Maria
Data augmentation expands training data by applying transformations that preserve the label. For images, that might mean rotation or scaling. But a transformation that changes what an image represents can create a misleading label—for instance, flipping a handwritten W vertically can make it resemble an M. Augmentations have to suit both the data and the task.

Anna
A practical model-building recipe begins with one training example. If the model cannot reach very low loss and high accuracy on that one example, there may be a bug or a problem with the setup. Once it can, scale up and build a model large enough to overfit the full training set. Then use validation results to reduce overfitting and improve generalization.

Maria
Keep a record of experiments and their validation results. Too little regularization leaves you with overfitting; too much can lower both training and validation performance. Once you have a useful model, tune hyperparameters such as learning rate and momentum. Grid search tries chosen values at fixed intervals; random search samples values from a range and can explore more efficiently.

Anna
Saving and reusing trained weights is another way to build on previous work. Transfer learning starts a new task with a model trained on another task—for example, using weights learned from US salary data as a starting point for European salary data. Fine-tuning continues training the reused model, often with a smaller learning rate.

Maria
You can also freeze layers you don’t want to train by setting their parameters’ gradient requirement to false. A common rule of thumb is to freeze earlier layers and fine-tune layers closer to the output. This is a way to reuse learned representations while adjusting the parts most relevant to the new task.

Anna
Now let’s shift to how we organize models in PyTorch. Object-oriented programming defines classes that create objects with attributes, which store data, and methods, which perform actions. For example, a bank-account class can initialize a balance attribute and include a deposit method that updates it.

Maria
The same idea makes custom PyTorch data sets and models flexible. A custom data-set class typically initializes its data, implements a length method to report the number of examples, and implements an item method to return a chosen example. A custom model class inherits from PyTorch’s neural-network module, defines layers in its initializer, and describes the computations in a forward method.

Anna
For a binary water-potability task, for instance, a custom data set can load a CSV file, return chemical features and a drinkable-or-not label, and feed batches through a data loader. A model can apply linear layers and activations in its forward method. For binary classification, binary cross-entropy loss is a suitable choice, and the labels must be shaped to match the model outputs.

Maria
Evaluation uses a similar pattern: switch the model to evaluation mode, turn off gradient calculations, run predictions over test batches, and convert probabilities to labels with a threshold such as 0.5. Accuracy is one metric, but it does not tell the whole story. For classification, precision measures how many positive predictions were correct, while recall measures how many actual positive examples were found.

Anna
For a multi-class task, precision and recall can be calculated separately for each class or averaged. Micro averaging pools true positives, false positives, and false negatives across classes. Macro averaging calculates each class’s score and gives all classes equal weight. Weighted averaging also calculates class-by-class scores, but gives more influence to classes with more examples.

Maria
So the average you choose reflects what you care about. Macro averaging is useful when small classes matter just as much as large ones. Weighted averaging reflects class sizes, while micro averaging combines the counts globally. You can also inspect scores class by class to see where a model struggles rather than relying on one summary number.

Anna
Images call for a different model design. A digital image is made of pixels: grayscale pixels represent shades from black to white, often with values from zero to 255, while color pixels typically have red, green, and blue values. Image data sets can be organized into folders by class, loaded with an image-folder utility, converted to tensors, and resized so all images have consistent dimensions.

Maria
Image tensors commonly have dimensions for batch size, color channels, height, and width. To display a color image, you may need to remove a batch dimension and rearrange the channels to the last dimension. Image transformations can resize images, while random rotations, horizontal flips, or contrast changes can augment the training set.

Anna
But why not just use linear layers on images? A 256-by-256 grayscale image already has more than 65,000 input values. Connecting that to a layer with 1,000 neurons would require over 65 million parameters. A color image would require even more, and a linear layer doesn’t naturally recognize that a pattern can appear in different locations.

Maria
Convolutional layers address both issues. They use small filters that slide over an image, applying the same learned operation at different locations. Each operation produces a value in a feature map, and different filters produce different feature maps. In PyTorch, a two-dimensional convolution specifies input and output channels and a kernel size, such as a three-by-three filter.

Anna
At each location, convolution takes an image patch and a filter, multiplies corresponding values, and sums them to make one feature-map value. Zero padding adds zeros around the input; this can help preserve spatial dimensions and give border pixels more equal treatment. Max pooling then takes the maximum value in a window, often reducing the height and width of feature maps.

Maria
A convolutional image classifier often has a feature extractor made from convolution, activation, and pooling layers, followed by a classifier. After the feature extractor, the maps are flattened into a vector. For example, a convolution can increase the number of feature maps, while pooling halves the spatial dimensions. The final linear layer produces one score per target class.

Anna
For a seven-cloud-type classifier, that’s a multi-class task, so cross-entropy loss is appropriate. Training data can use carefully chosen augmentations, but evaluation images should use consistent transformations such as converting to tensors and resizing, not random augmentation. Otherwise, the test image could be altered unpredictably during evaluation.

Maria
And image augmentations need to preserve meaning. A rotation may show a cloud formation from another angle, and a horizontal flip can simulate another view of the sky. A contrast adjustment can represent different lighting. But other tasks may need different choices: changing a lemon’s color too much could make its label confusing, for example.

Anna
Let’s move from images to sequential data, where order matters. Time series such as electricity use, weather, or sales are sequential; so are words in a sentence and samples in an audio signal. If we randomly split time-series data, the model could effectively see future information while being tested. Splitting by time avoids that lookahead bias.

Maria
For electricity-consumption forecasting, imagine measurements every fifteen minutes and a prediction based on the previous twenty-four hours. That input sequence contains 96 measurements, and the next measurement is the target. A sequence-building function moves through the training data, collecting each window of 96 values and the value immediately after it.

Anna
Those input sequences and targets can be converted into tensors, stored in a tensor data set, and passed to a data loader. The same next-step idea appears elsewhere: a language model predicts the next word, while speech recognition processes audio and produces text. The important point is that the sequence’s order carries information.

Maria
A feedforward network passes data in one direction. A recurrent neural network, or RNN, also feeds information from one time step into the next through a hidden state. At the first time step, the hidden state is often initialized to zero. Later outputs depend on the current input and the previous hidden state, allowing the network to retain information about earlier inputs.

Anna
We can stack recurrent layers just as we stack other layers. The architecture depends on what we want to input and output. Sequence-to-sequence models produce an output at every time step, as in real-time speech recognition. Sequence-to-vector models read a whole sequence and use the final output, as in text classification or the electricity forecast we’re discussing.

Maria
A vector-to-sequence model starts with one input and produces a sequence, which can be useful for generating text. An encoder-decoder model processes an input sequence before starting its output sequence, as in machine translation. That differs from sequence-to-sequence generation, where outputs can be produced while inputs are still arriving.

Anna
A plain RNN cell can struggle with long-term memory: information from the beginning of a long sequence may fade by the time the end is processed. Long short-term memory cells, or LSTMs, address this using both a short-term hidden state and a long-term cell state. Their gates help decide what to forget, what to store, and what to output.

Maria
A gated recurrent unit, or GRU, is a simpler alternative that combines those memories into one hidden state and uses a different, simpler gating structure. In PyTorch, the basic pattern is similar for RNN, LSTM, and GRU layers: initialize the recurrent layer, pass in the sequence and initial state, and use the outputs you need. For a sequence-to-vector task, that’s often the final output.

Anna
There isn’t one recurrent architecture that wins for every problem. Plain RNNs are important to understand but are less commonly used because of their short-term-memory limitation. LSTMs and GRUs are often the practical choices; GRUs are less complex and require less computation, while relative performance depends on the use case. Trying both and comparing results is sensible.

Maria
For sequence forecasting, we use a regression loss such as MSE. Recurrent layers expect input shaped as batch size, sequence length, and number of features. If each sequence contains one feature and the data loader returns only batch size by sequence length, we add that feature dimension before passing the data to the model.

Anna
Predictions and targets also need matching shapes for the loss. If the model outputs a batch-by-one tensor but labels are a batch-sized vector, squeeze the extra dimension from the outputs. The training loop otherwise follows the same rhythm: clear gradients, run the model, calculate loss, backpropagate, and update parameters.

Maria
A third design challenge is data with multiple sources. Multi-input models can combine two images of the same object, different kinds of data such as an image and text, or two examples that need to be compared. In each case, separate parts of the model can process each input before their representations are combined.

Anna
For example, with handwritten-character images, one model could receive both the character image and a one-hot vector representing its alphabet. The image and alphabet are processed separately, their representations are concatenated, and a classifier predicts the character class. PyTorch’s concatenation operation combines tensors along a chosen dimension, provided their shapes are compatible.

Maria
A custom data set for that task can return a triplet: the transformed image, the alphabet vector, and the character label. The model has one subnetwork for the image, another for the alphabet vector, and a classifier for their combined representation. In the training loop, both inputs go into the model, along with the target label for the loss.

Anna
Multi-output models produce more than one prediction from the same input. They’re useful for multi-task learning, such as predicting a car’s make and model, or multi-label classification, where one image might contain both a beach and people. Extra outputs can also be added at intermediate points in very deep networks to encourage useful learning in earlier layers.

Maria
With the character data, a model can use one image to predict both the character and its alphabet. A shared image-processing network creates a representation, and two separate classifiers produce scores for the two tasks. The targets are class indices: one for the character and one for the alphabet.

Anna
Each output needs its own loss and evaluation metric. The alphabet task has 30 classes, while character recognition has 964, so their accuracies may differ. At first, we can add the two losses together, telling the model that both tasks matter equally. But we can also weight them when one task is more important.

Maria
For instance, if character recognition is twice as important as alphabet recognition, we can multiply the character loss by two before combining them. Alternatively, assign weights that sum to one. The key caution is that loss magnitudes matter: if one loss is much larger than another, it can dominate the combined objective and make the model effectively ignore the smaller one.

Anna
Imagine combining MSE for house prices with cross-entropy for a house-quality category. MSE values could be in the tens of thousands, while cross-entropy is often in the single digits. Simply adding them could overwhelm the quality task. Scaling losses to bring them into a similar range can make their weights more meaningful.

Maria
So the toolkit we’ve built is broad: tensors and layers, activations and losses, backpropagation and optimizers, data loading and evaluation, then specialized approaches for stability, images, sequences, and multiple inputs or outputs. The unifying routine is to define the task, prepare the data, choose an architecture and loss, train carefully, and evaluate on data the model hasn’t used to update its parameters.

Anna
And keep balancing learning with generalization. Watch training and validation metrics, make regularization choices that fit the task, and tune hyperparameters rather than assuming one setting is best. Once you’re comfortable with these foundations, transformers and self-supervised learning are natural next areas to explore. Most importantly, practice by building and testing models on real problems.

Ask anything
We've read this whole study set, so questions about it get the best answers.