Deep Learning with PyTorch
Deep Learning with PyTorch: Study Notes
1. Deep Learning and Neural Networks
Deep learning is a subset of machine learning that uses neural networks with one or more hidden layers to learn patterns from data. Neural networks are made of interconnected computational units called neurons, arranged in layers:
Input layer: receives the features of each example.
Hidden layers: transform the input into progressively useful representations.
Output layer: produces a prediction, such as a class or a numerical value.
A neural network may contain no hidden layers or many hidden layers. Deeper networks can represent more complex relationships, but they usually require substantial amounts of data—often hundreds of thousands of examples or more—to learn reliable patterns.
Deep learning is used in tasks such as translation, medical diagnosis, image recognition, chatbots, and self-driving systems. PyTorch is a popular framework for implementing these models. Its interface is designed to be familiar to Python users, and it uses tensors as its core data structure.
2. PyTorch Tensors
A tensor is PyTorch’s fundamental data structure. It generalizes scalars, vectors, matrices, and higher-dimensional arrays, and supports the operations used to build and train neural networks.
Tensors can be created from Python lists or NumPy arrays. Two useful properties are:
Shape: the size of the tensor along each dimension.
Data type: the type of values it stores, such as integers or floating-point numbers.
Checking shape and data type helps ensure that tensors are compatible with a model and its operations. For example, model parameters are commonly floating-point values, so input data may need to be converted to a floating-point type.
Tensor operations
Addition and subtraction are defined element by element when the tensors have compatible shapes.
Element-wise multiplication multiplies corresponding elements.
Matrix multiplication combines rows of one matrix with columns of another. Each output value is the sum of the pairwise products of one row and one column.
Shape compatibility matters. Operations between tensors with incompatible dimensions generally produce an error, unless the operation explicitly supports broadcasting.
Neural networks perform many such operations. Each layer transforms its input using mathematical operations and learnable parameters.
3. Linear Layers and Network Capacity
A linear layer, also called a fully connected layer, connects every output neuron to every input neuron. Each output neuron applies a weighted sum to the inputs and adds a bias:
Here, x is the input, W contains weights, and b contains biases. The result z is often called a pre-activation output when it will next be passed through an activation function.
Weights determine how strongly each input feature affects a neuron.
Biases provide an additional baseline term independent of the input features.
PyTorch initializes weights and biases when a layer is created. Training adjusts them to improve predictions.
Dimensions between layers
The input dimension of a linear layer must match the number of features it receives. Its output dimension is the number of neurons it produces. In a sequence of layers, the output dimension of each layer must match the input dimension of the next.
For example, a network can transform data through dimensions 10→18→20→5. It accepts ten input features and produces five output values.
Parameter count
A neuron connected to n inputs has n weights and one bias, for a total of n+1 learnable parameters. A layer with m output neurons therefore has:
parameters.
For example, a first layer with four neurons receiving eight inputs has 4(8+1)=36 parameters. A second layer with two neurons receiving four inputs has 2(4+1)=10. Together, the network has 46 parameters.
A model’s number of learnable parameters is one measure of its capacity:
More parameters allow the model to represent more complex patterns, but can increase training time and overfitting risk.
Too few parameters may make the model unable to learn the task adequately.
Parameter counts can be obtained by summing the number of elements in the model’s parameter tensors.
4. Activation Functions
A network containing only linear layers remains equivalent to a single linear transformation, regardless of how many linear layers are stacked. Activation functions introduce nonlinearity, enabling networks to learn relationships more complex than linear ones.
Sigmoid
The sigmoid function maps any real-valued input to a value between zero and one:
It is commonly used in the final layer of a binary classification model, where the result is interpreted as the probability of class 1. A threshold of 0.5 can convert that probability into a class prediction:
Output at least 0.5: predict class 1.
Output below 0.5: predict class 0.
A network with linear layers and a sigmoid output behaves like logistic regression. Hidden layers and nonlinear activations allow more expressive models.
Softmax
For a problem with more than two classes, softmax transforms a vector of scores into a probability distribution. Each output lies between zero and one, and the outputs sum to one. The predicted class is the one with the largest probability.
Softmax is commonly applied over the dimension containing the class scores. If the output has one score per class, the output shape remains the same as the score shape.
ReLU and leaky ReLU
Sigmoid and softmax can have very small gradients for some inputs, so they are usually reserved for output layers rather than hidden layers.
Rectified linear unit (ReLU) is defined as:
For positive inputs, ReLU returns the input; for negative inputs, it returns zero. It is widely used in hidden layers because its gradient does not shrink toward zero for large positive inputs.
A limitation of ReLU is that a neuron receiving consistently negative inputs can produce zero and stop learning through that activation. This is sometimes called the dying ReLU problem.
Leaky ReLU addresses this by retaining a small slope for negative inputs. A common form is:
where α is a small coefficient, often 0.01. The nonzero negative-side slope allows gradients to continue flowing through the neuron.
5. Forward Passes and Model Outputs
A forward pass sends input data through a network’s layers to produce predictions. Each layer transforms its input and passes the result onward. A forward pass is used both during training and when making predictions on new data.
Output layers depend on the task:
Binary classification
The final linear layer produces one score per example.
A sigmoid activation converts the score to a probability.
A threshold, commonly 0.5, turns the probability into a class label.
For a batch of five examples, a binary model may produce five probabilities.
Multiclass classification
The final linear layer produces one score per class.
Softmax can convert the scores to probabilities.
The predicted class is the index with the highest probability.
For five examples and three classes, the output has shape 5×3. Each row contains the class probabilities for one example.
Regression
Regression predicts continuous numerical values. Its final layer usually has one output per target and no sigmoid or softmax activation. For five examples with one target value each, the output has shape 5×1.
A forward pass alone does not make predictions meaningful. During training, the model’s weights and biases must be adjusted using a loss function and an optimization procedure.
6. Loss Functions and Targets
A loss function measures the difference between model predictions and the ground-truth targets. It takes predictions and targets and returns a numerical value. Training aims to minimize this value.
Classification targets and cross-entropy
For multiclass classification, targets are often represented as integer class indices. A one-hot representation instead uses a vector with a 1 at the true class position and 0s elsewhere. For three classes, class zero can be represented as [1,0,0].
In PyTorch, cross-entropy classification loss is typically computed from the model’s raw class scores, also called logits, and integer class labels. Softmax is incorporated into the loss calculation internally. Conceptually, the loss rewards assigning high probability to the correct class and penalizes incorrect predictions.
A correct, confident prediction generally produces low loss; an incorrect prediction produces higher loss. Cross-entropy loss is used for multiclass classification. Binary classification commonly uses binary cross-entropy, with predicted probabilities and binary targets.
Regression loss: mean squared error
For regression, mean squared error (MSE) is the average squared difference between predictions and targets:
Squaring the differences has two effects:
Positive and negative errors cannot cancel each other.
Larger errors are penalized more strongly than smaller ones.
Predictions and targets used in regression loss calculations should have compatible shapes and floating-point types.
7. Gradients, Backpropagation, and Optimization
A model minimizes loss by adjusting its parameters. Gradients describe how the loss changes as each parameter changes. They indicate both the direction and size of the parameter adjustment that is likely to reduce the loss.
A useful mental model is a loss curve:
A steep slope has a large gradient.
A gentle slope has a smaller gradient.
At a minimum, the slope is zero.
Real neural-network loss surfaces are usually non-convex, meaning they may contain multiple local minima. A local minimum is lower than nearby points but may not be the lowest point overall.
Backpropagation
A typical training update follows these steps:
Run a forward pass to produce predictions.
Compute the loss by comparing predictions with targets.
Run backpropagation to calculate gradients of the loss with respect to model parameters.
Use an optimizer to update those parameters.
Backpropagation applies the chain rule through the network, calculating how each layer’s weights and biases contributed to the loss. Gradients are stored with the corresponding parameters.
Gradient descent and SGD
An optimizer uses gradients to update parameters. Stochastic gradient descent (SGD) updates parameters using a learning rate and the gradients calculated for a batch of data. In simplified form, a parameter update is:
where θ is a parameter, η is the learning rate, and ∇θL is the loss gradient with respect to that parameter.
A positive gradient indicates that increasing the parameter would increase the loss locally, so gradient descent moves it in the negative direction. The size of the update depends on the gradient and learning rate.
In PyTorch, an optimizer is given the model’s parameters. A typical update cycle clears old gradients, computes new gradients through backpropagation, and applies an optimizer step.
8. Learning Rate and Momentum
The learning rate controls the size of parameter updates.
If it is too small, training can make very slow progress.
If it is too large, updates may overshoot a minimum and cause the loss to oscillate or diverge.
Suitable values depend on the model and data; values such as 0.01 through 0.0001 are common starting points, but are not universal.
Momentum uses information from previous updates to smooth optimization. It can preserve movement in a consistent direction even when the current gradient is small, helping an optimizer move through shallow regions and past some local minima. Momentum values are often chosen in a range such as 0.85 to 0.99.
Both parameters are hyperparameters: they are selected by the practitioner rather than learned directly as model weights.
Common optimizers
SGD: uses the learning rate to scale gradient-based updates. It is simple and computationally efficient.
Adagrad: reduces learning rates for parameters that have been updated frequently. It can work well with sparse data, where some features occur infrequently, but its learning rates can shrink too quickly.
RMSprop: adapts the learning rate for each parameter using recent gradient magnitudes, addressing overly aggressive learning-rate decay.
Adam: combines adaptive learning rates with momentum-like averages of past gradients. It is a versatile, commonly used default optimizer.
9. Datasets, Batches, and Training Loops
Training requires more than a model and an optimizer. It also requires organized data, a loss function, and a loop that repeatedly processes examples.
Datasets and data loaders
A dataset stores features and target labels and provides access to individual examples. A tensor dataset can pair feature tensors with target tensors. A sample is typically returned as a tuple containing its input and target.
A data loader iterates over a dataset in batches:
Batch size is the number of examples processed in one iteration.
Shuffling randomizes example order, usually at the beginning of each epoch.
An epoch is one complete pass through the training dataset.
Batching allows multiple examples to be processed efficiently. If the dataset size is not divisible by the batch size, the final batch may contain fewer examples unless incomplete batches are explicitly dropped.
Building a standard training loop
A basic training loop performs the following operations for each batch:
Clear gradients from the previous update.
Run a forward pass on the batch inputs.
Compute loss from the predictions and targets.
Backpropagate the loss to calculate gradients.
Apply an optimizer step to update parameters.
The loop repeats for multiple epochs. Clearing gradients is necessary because many PyTorch operations accumulate gradients by default.
Preparing tabular data
For a tabular classification task, columns containing meaningful predictors become features, while the target column supplies class labels. Irrelevant identifiers, such as an animal’s name when predicting its type, can be excluded. Feature and target arrays can then be converted to tensors and organized into a dataset and data loader.
For regression, feature values and targets generally need to be floating-point tensors. Classification targets are generally represented as class indices for multiclass cross-entropy.
10. Object-Oriented PyTorch Datasets and Models
Object-oriented programming (OOP) organizes programs around objects that combine data, called attributes, with functions, called methods. A class describes how its objects are created and behave.
An initializer method sets an object’s attributes when it is created. For example, a bank-account object could store its balance as an attribute and provide a deposit method that updates it.
Custom datasets
A custom PyTorch dataset is commonly built by defining a class based on PyTorch’s dataset base class. It needs three main components:
An initializer that loads or stores the data and any required transformations.
A length method that returns the number of samples.
An item-access method that returns the features and target for a requested index.
A water-quality dataset, for example, could return chemical features and a binary label indicating whether a sample is potable. The dataset can then be passed to a data loader for batching and shuffling.
Custom model classes
Small models can be built with sequential containers, but custom classes provide more flexibility. A model class based on PyTorch’s neural-network module generally includes:
An initializer that defines the model’s layers.
A forward method that specifies how input data flows through those layers.
The forward method might pass an input through a linear layer, an activation, and further layers before returning the output.
11. Evaluating Models
Model performance should be measured on data that was not used to fit the model’s parameters.
Training, validation, and test sets
Training set: used to learn weights and biases.
Validation set: used to compare model configurations and tune hyperparameters.
Test set: used for a final evaluation after model development.
The test set should not be used repeatedly to choose model settings, because doing so can indirectly tailor the model to the test data.
Training and validation loss
Training loss is calculated over batches during training. The mean loss for an epoch is commonly the total loss across batches divided by the number of batches.
For validation:
Put the model in evaluation mode.
Disable gradient calculations because no parameter updates are needed.
Run a forward pass on validation batches and accumulate the loss.
Calculate the mean validation loss.
Return the model to training mode before the next training epoch.
Some layers behave differently during training and evaluation, so switching modes is important.
Accuracy
Accuracy is the fraction of predictions that are correct. For multiclass outputs, the predicted class is the index of the largest score or probability. Accuracy metrics accumulate correct predictions and targets across batches, compute the final value, and are reset before a new evaluation period.
Accuracy alone may not describe performance adequately, especially when classes are imbalanced or different kinds of mistakes have different consequences.
Precision and recall
For a class treated as the positive class:
Precision is the fraction of positive predictions that are correct.
Recall is the fraction of actual positive examples that are correctly identified.
For multiclass problems, precision and recall can be calculated separately for each class or aggregated.
Micro average: combines true positives, false positives, and false negatives across classes before calculating the metric. It reflects the overall distribution of examples.
Macro average: calculates a score for each class and averages them equally. Small classes count as much as large classes.
Weighted average: averages the class scores while weighting each class by its number of examples.
Macro averaging is useful when performance on each class matters equally. Weighted averaging accounts for class size while retaining per-class calculations. Micro averaging provides a global summary and is influenced by the overall number of examples in each class.
12. Overfitting and Regularization
Overfitting occurs when a model learns the training data too specifically and fails to generalize to unseen examples. A common warning sign is that training loss continues to fall while validation loss begins to rise.
Overfitting risk increases with factors such as:
A small dataset.
A model with excessive capacity.
Large parameter values or overly flexible decision boundaries.
Dropout
Dropout is a regularization technique that randomly sets some neuron outputs to zero during training. This discourages the network from depending too heavily on particular neurons or features. Dropout is often placed after an activation function.
During evaluation, dropout is disabled so the full network is used to make stable predictions. The model’s training and evaluation modes control this behavior.
Weight decay
Weight decay adds a penalty that encourages smaller parameter values. It is configured through the optimizer and is typically assigned a small coefficient. Stronger weight decay imposes stronger regularization, although too much can prevent the model from learning effectively.
More data and data augmentation
More training data can improve generalization. When collecting additional data is difficult, data augmentation can create modified versions of existing examples. For images, common transformations include rotation, horizontal flipping, scaling, and contrast changes.
Augmentations must preserve the correct label. A transformation that changes the apparent class—for example, turning a handwritten character into another character—introduces mislabeled examples and can harm learning.
13. A Practical Model-Development Workflow
A robust approach to a new deep learning problem is:
Check that the task is learnable. Train on a single example. A suitable model should be able to drive its loss near zero and achieve near-perfect accuracy on that example. Failure may reveal a data, shape, label, or model bug.
Establish a baseline. Train a model large enough to fit the training set. This helps confirm that the model and data pipeline can solve the task.
Measure generalization. Track validation performance as well as training performance.
Reduce overfitting. Try dropout, weight decay, augmentation, more data, or reduced model capacity.
Tune hyperparameters. Compare settings such as learning rate, momentum, model size, and regularization strength.
Choose a model using validation results. Use the test set for the final performance estimate.
Regularization requires balance. Too little can lead to strong training performance but weak validation performance; too much can reduce performance on both training and validation data.
Hyperparameter search
Grid search tests specified combinations of values, such as a set of learning rates and momentum values.
Random search samples values from specified ranges. It can explore a wider variety of configurations without testing every possible combination in a grid.
14. Weight Initialization and Gradient Stability
Neural networks can encounter vanishing gradients, where gradients become so small that earlier layers receive little effective learning signal, or exploding gradients, where gradients become excessively large and updates destabilize training.
A contributing factor is how weights are initialized. Appropriate initialization aims to maintain useful signal and gradient scales as they pass through layers. In particular, initialization methods are chosen with regard to the activation function. He initialization is commonly used with ReLU-like activations.
Small, appropriately scaled initial weights can help keep layer outputs stable. PyTorch provides initialization utilities for setting weights according to distributions such as uniform distributions.
Activation functions and gradient stability
Sigmoid and softmax are bounded, but their gradients can become very small in saturated regions. Repeatedly multiplying small gradients during backpropagation can cause the vanishing-gradient problem. They are therefore most often used in output layers.
ReLU-like activations help maintain gradients for positive inputs, though standard ReLU can produce inactive neurons for negative inputs. Leaky ReLU and exponential linear unit (ELU) retain nonzero behavior for negative inputs and can help alleviate this limitation. ELU also has outputs that are often centered closer to zero.
Batch normalization
Batch normalization normalizes a layer’s outputs using the batch mean and standard deviation, then learns scale and shift parameters. This helps control the distribution of inputs passed to subsequent layers and can make training faster and less sensitive to gradient instability.
For a one-dimensional batch-normalization layer, the number of features must match the preceding layer’s output size. It is usually placed after a linear or convolutional operation and before the activation function.
15. Transfer Learning and Fine-Tuning
Transfer learning reuses a model trained on one task as a starting point for another task. Instead of beginning with random weights, the new model begins with parameters that have already learned useful patterns.
For example, a model trained on salary data from one region may provide a starting point for a related task involving another region. Models and their weights can be saved and loaded for reuse.
Fine-tuning is a form of transfer learning in which a pretrained model is further trained on the new task, often with a smaller learning rate. Layers that do not need to change can be frozen by disabling gradient updates for their parameters. A common strategy is to freeze early layers and fine-tune later layers, although the best choice depends on how similar the tasks are.
16. Image Data and Convolutional Neural Networks
Image representation
A digital image is made of pixels, each of which stores color information.
A grayscale pixel can be represented by an intensity value, often ranging from 0 for black to 255 for white.
A color image commonly represents each pixel with red, green, and blue intensities.
A color image is often represented as a tensor with dimensions for channels, height, and width. Batches add another dimension, producing a common format of batch size, channels, height, and width.
Image data can be loaded from directories organized by class. A transformation pipeline can convert images to tensors and resize them to a consistent height and width. Consistent image dimensions make batching and model processing practical.
Why ordinary linear layers are inefficient for images
A 256×256 grayscale image has more than 65,000 input values. Connecting those inputs to 1,000 neurons would require more than 65 million weights, before counting biases. Color images have three channels and can require roughly three times as many input connections.
Linear layers also do not naturally preserve spatial structure. A pattern learned at one position in an image may not be recognized if it appears elsewhere.
Convolutional layers
A convolutional layer uses small grids called filters or kernels. A filter slides across an input image or feature map, applying the same learned operation at each position. The result is a feature map that responds to patterns detected by the filter.
The operation at one position can be viewed as an element-wise multiplication between the input patch and filter, followed by a sum. Multiple filters produce multiple feature maps. The layer’s output is then typically passed through an activation function.
Convolutional layers often use far fewer parameters than fully connected layers and recognize patterns wherever they occur in the image.
Padding and pooling
Zero padding adds a border of zeros around the input. Padding can preserve spatial dimensions and ensures border pixels are processed comparably to interior pixels. Without padding, the spatial size generally decreases as filters move over the input.
Max pooling applies a window to a feature map and retains the largest value in each window. A non-overlapping 2×2 window typically halves the height and width. Pooling reduces spatial dimensions and computational demands while retaining strong detected features.
CNN structure
A convolutional neural network often contains two broad parts:
A feature extractor, made from repeated convolution, activation, and pooling operations.
A classifier, which uses the extracted features to predict classes.
Before a classifier’s linear layer, the feature maps are flattened into a vector. The classifier’s input size must equal the number of values in that flattened representation.
For example, an image beginning with shape 3×64×64 may pass through a convolution producing 32 feature maps, a pooling operation, another convolution producing 64 maps, and another pooling operation. If each pooling operation halves the spatial dimensions, the final feature maps have shape 64×16×16 before flattening.
17. Image Augmentation and Classification Metrics
Image augmentation can include random rotation, horizontal flipping, and contrast adjustment. These transformations can expose a model to different orientations and lighting conditions, improving robustness and reducing overfitting. The transformation must make sense for the task and preserve the class label.
For image classification with multiple classes, cross-entropy loss is appropriate. Evaluation data should generally use deterministic preprocessing—such as resizing and tensor conversion—rather than random training augmentations, so the model is evaluated on a consistent version of each example.
Per-class metrics can reveal performance differences hidden by an overall score. For example, a model may recognize clear-sky images well but struggle with a visually similar cloud class. Mapping class names to their indices allows the corresponding per-class scores to be interpreted correctly.
18. Sequential Data and Time-Based Splits
Sequential data has an order that carries meaning. Examples include:
Time series such as electricity use, weather, sales, or stock prices.
Text, where word order affects meaning.
Audio, where sample order determines the sound.
For sequential forecasting, randomly splitting data can introduce lookahead bias: the model may train on observations from a period later than the examples it is tested on. A more realistic approach is to train on earlier data and test on later data.
Creating sequences
A sequence model often trains on fixed-length windows. If electricity measurements are recorded every fifteen minutes, the previous twenty-four hours contain 24×4=96 measurements.
Each training example can consist of:
An input sequence containing the previous 96 observations.
A target containing the next observation.
A sequence-generation procedure slides a window along the time series, pairing each window with the value immediately following it. The resulting arrays can be converted into tensors and placed in a dataset and data loader.
This next-step prediction setup is conceptually similar to predicting the next word in language modeling.
19. Recurrent Neural Networks
A recurrent neural network (RNN) is designed to process ordered sequences. Unlike a purely feedforward network, it passes a hidden state from one time step to the next.
At time step t, a recurrent cell receives:
The current input xt.
The previous hidden state ht.
It produces an output and a new hidden state. The hidden state acts as a compact memory of information from earlier steps. The initial hidden state is commonly set to zero.
An RNN can be understood as the same recurrent cell applied repeatedly across time. This is called unrolling the network. The output at a given step can depend on previous inputs through the hidden state. Multiple recurrent layers can also be stacked to form a deeper recurrent network.
Sequence input-output patterns
Sequence-to-sequence: receives a sequence and uses outputs at every time step. One application is real-time speech recognition.
Sequence-to-vector: receives a sequence and uses the final output to produce one prediction. It can classify a text or forecast a value from a history of observations.
Vector-to-sequence: receives a single input and produces a sequence, as in some text-generation setups.
Encoder-decoder: processes an entire input sequence before generating an output sequence. Translation is a common example because the source sentence usually needs to be understood before its translation is produced.
Tensor shapes
A recurrent layer commonly expects inputs in the form:
If each time step contains one feature, the feature dimension still needs to be present. It may need to be added to the input tensor. A model’s output may have a shape such as batch size by one, while scalar regression targets may have shape batch size. The shapes should be made compatible before calculating loss, for example by removing an unnecessary singleton dimension from the output.
20. LSTM and GRU Cells
Plain RNNs can struggle to preserve information over long sequences. As a sequence is processed, information from its beginning may fade from the hidden state. This is a short-term memory limitation.
Long short-term memory
A long short-term memory (LSTM) cell maintains two states:
Hidden state: often treated as short-term memory and used to produce the current output.
Cell state: a longer-term memory pathway.
LSTMs use gates to regulate information:
The forget gate controls what information is removed from the cell state.
The input gate controls what new information is written to it.
The output gate controls what information contributes to the current output.
These mechanisms help LSTMs retain or discard information across longer sequences. In PyTorch, an LSTM has an input, hidden state, and cell state; the initial states are commonly initialized to zeros.
Gated recurrent unit
A gated recurrent unit (GRU) is a simpler gated recurrent architecture. It combines long- and short-term information into a single hidden state and does not use a separate output gate. It is often less computationally complex than an LSTM.
There is no universally best choice between LSTM and GRU. Performance depends on the task and data. Comparing both is often useful.
Regression for sequence forecasting
Electricity consumption forecasting is a regression task. It can use MSE loss and a final linear output. The recurrent layer processes the input sequence; a model can take the last recurrent output and map it to the predicted next value. During evaluation, a mean squared error metric can summarize forecast error over test batches.
21. Multi-Input Models
A multi-input model combines information from more than one input source. Examples include:
Two images of the same object used to identify it.
An image and text used together to answer a question.
Two images compared to determine whether they show the same person.
Two augmented versions of an example used in self-supervised representation learning.
The inputs may be processed by separate subnetworks. Their learned representations are then concatenated and passed to a final classifier or predictor.
Example: image and alphabet information
For handwritten-character recognition, a model can receive:
An image of the character.
A vector describing the alphabet to which it belongs.
The image can be processed by convolutional layers, while the alphabet vector passes through a separate layer. The resulting representations are concatenated, then passed to a classifier that predicts the character class.
A custom dataset can return a tuple of inputs and a target. For example, it may load an image, convert it to grayscale, apply a transformation, and return the transformed image, alphabet representation, and character label.
When concatenating tensors, their dimensions must agree in all dimensions except the one along which concatenation occurs.
22. Multi-Output Models and Loss Weighting
A multi-output model produces more than one prediction from the same input. Applications include:
Predicting a car’s make and model from its image.
Assigning multiple labels to an image.
Producing auxiliary predictions at intermediate stages of a deep model.
For handwritten-character recognition, a model can predict both the character and its alphabet from the image. A shared feature extractor processes the image, and separate classifier heads produce the two outputs.
Combining losses
Each output has its own target and loss. To train the shared model, the losses must be combined into a single objective for the optimizer. A simple approach is:
This treats both tasks as equally important. If one task is more important, its loss can receive a larger weight:
The weights communicate the relative importance of each task. They may also be chosen to sum to one for readability; the relative weighting is what matters for optimization.
Loss magnitudes must be considered. If one loss is much larger than another, it may dominate the combined objective, causing the model to give little attention to the smaller loss. For example, MSE for prices measured on a large numerical scale can be thousands of times larger than cross-entropy for a classification task. The losses may need to be normalized or scaled before combining them.
Each output should also be evaluated with an appropriate metric. A task with fewer possible classes may naturally achieve higher accuracy than a harder task with many classes. Solving related tasks together can nevertheless improve the shared representation, because learning one task may provide useful information for another.
23. Core Principles to Retain
Tensors, layers, and parameter shapes must be compatible throughout a model.
Linear layers learn weighted combinations; nonlinear activations allow deeper networks to model complex relationships.
The output layer and loss function must match the task: sigmoid or binary cross-entropy for binary classification, cross-entropy for multiclass classification, and linear outputs with MSE for regression.
Training consists of forward passes, loss computation, backpropagation, and optimizer updates over batches and epochs.
Learning rate and momentum influence how efficiently and stably an optimizer moves through the loss landscape.
Training performance alone is not enough: validation performance reveals whether a model generalizes.
Regularization, data augmentation, suitable initialization, and batch normalization can improve training stability or reduce overfitting.
Convolutional networks exploit image structure; recurrent networks model ordered sequences; multi-input and multi-output architectures combine or predict multiple sources of information.
Model design should be tested systematically, beginning with simple checks and selecting configurations based on validation results.

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