Deep Learning with PyTorch
Transcript
Initialize What's up everybody? Today's videos is a collection, of course videos coming from our deep learning with PyTorch skill track. It covers everything you need to know about working with PyTorch, from building deep learning models in PyTorch using multi-modal output and import, as well as dealing with issues like overfitting, vanishing gradients, and a lot more. If you enjoyed this video, make sure to like and subscribe to the channel and if you're interested in going beyond watching videos but actually practicing in the browser, check out the link in the description below. Hi I'm Yasmin, a senior Data Science content developer at Datacamp, and I'll be your instructor for this course on Deep Learning with PyTorch. Deep learning is everywhere. It powers many recent and exciting innovations, from language translation to self-driving cars medical diagnostics, and chat bots.
Deep learning is a subset of machine learning, where the fundamental model structure is a network of inputs, hidden layers, and outputs, as shown. A network can have one or many hidden layers. The original intuition behind deep learning was to create models inspired by how the human brain learns through interconnected cells, called neurons. This is why we continue to call deep learning models neural networks. These layered model structures require far more data compared to other machine learning
models in order to derive patterns. We are usually talking about at least hundreds of thousands of data points. While there are several frameworks and packages out there for implementing deep learning algorithms, we'll focus on PyTorch, one of the most popular and well maintained frameworks. PyTorch was originally developed by meta AI as part of Facebook's AI research lab, before it moved under the Linux Foundation.
It is designed to be intuitive and user friendly, sharing many similarities with the Python library. NumPy we can import the PyTorch module by calling import torch. The fundamental data structure in PyTorch is a tensor which is similar to an array or matrix. It can support many mathematical operations and forms a building block for our neural networks. Tensors can be created from Python lists or NumPy arrays. Using the torch tensor class, this class converts the data into a compatible format.
For deep learning, we can call tensor dot shape to display the shape of our newly created tensor and tensor dot d type to display its data type. Here, a 64 bit integer checking the shape and data type ensures tensors align correctly with our module and task, and can help us in case of debugging. PyTorch tensors can be added or subtracted provided that their shapes are compatible. Two tensors are compatible if they have the same shape, meaning their dimensions align exactly. When shapes are incompatible, we get an error. We can also perform element wise multiplication, which involves multiplying each corresponding element from two arrays of the same shape, and many other operations, including matrix multiplication. Matrix multiplication is a way of combining two matrices to make
a new one. Each value in the new matrix comes from multiplying a row from the first matrix with a column from the second matrix, and summing the results behind the scenes. Deep learning models perform countless operations like addition and multiplication to process data and learn patterns. Let's build our first neural network using PyTorch tensors.
A neural network consists of input, hidden and output layers. The input layer contains the data set features. The output layer contains the predictions and hidden layers lie in between. While a network can have any number of hidden layers, we'll begin by building a network with no hidden layers where the output layer is a linear layer. Here, every input neuron connects to every output neuron, referred to as a fully connected network. This network is equivalent to a linear model and helps
us understand the fundamentals before adding complexity. We'll use the torch and end module to build our networks. It makes neural network code more concise and flexible, and is conventionally imported as an n. When designing a neural network. The input and output layer dimensions are predefined. The number of neurons in the input layer is the number of features in our data set, and the number of neurons in the output layer is the number of classes we want to predict. Say we create an input tensor of shape one by three. We can think of this as one row with three features or neurons. Next we pass this input tensor to a linear layer, which applies a linear function to make predictions, and then dot linear takes two arguments in features. Is the number of features in our input three and out
features is the desired size of the output tensor. In this case two. Correctly specifying n features ensures our linear layer can receive the input tensor. Lastly, we pass input tensor to linear layer to generate an output. Notice that the output has two features on neurons due to the out features specified in our linear layer. When input tensor is passed to linear layer, a linear operation is performed to include weights and biases. Each linear layer has a set of associated weights and biases. These are the key quantities that define a neuron. The weights reflect the importance of different features. The bias is an additional term that is independent of the weights, providing the neuron with a baseline output.
At first, the linear layer assigns random weights and biases. These are tuned later. Let's imagine our fully connected network in action. Say we have a weather data set with three features temperature, humidity, and wind. We want to predict whether it will rain or be cloudy. The humidity feature will have a more significant weight compared to the other features, as it's a strong predictor of rain and clouds.
The weather data is for a tropical region with a high probability of rain, so a bias is added to account for this baseline information. With this information, our model makes a prediction. So far we've used one input layer and one linear layer. Now we'll add more layers to help the network learn complex patterns. We'll stack three linear layers using encode sequential. A PyTorch container for stacking layers in sequence. This network takes input, passes it to each linear layer in sequence,
and returns output. In this case, the layers within known sequential are hidden layers. Here, the first argument in the first layer represents the number of input features and features, and the last argument in the final layer represents the number of output classes and classes, both defined by the data set. We can add as many hidden layers as we like, as long as the input dimension of each layer matches the output dimension of the previous one. In our three layer example, the first layer takes ten features and outputs 18. The second layer takes 18 and outputs 20. Finally, the third layer takes 20 and outputs five. A layer is fully connected when each neuron links to all neurons in the previous layer, as shown in red in the figure, each neuron in a linear layer performs a linear operation using all
neurons from the previous layer. Therefore, a single neuron has N plus one learnable parameters, with n being the output dimension of the previous layer plus one for the bias. Increasing the number of hidden layers increases the total number of parameters in the model. Also known as model capacity. Higher capacity models can handle more complex datasets, but may take longer to train. An effective way to assess a model's capacity is by calculating its total number of parameters. Let's break it down with a two layer network. The first layer has four neurons. Each neuron has eight weights and one bias, which results in 36 parameters. A second layer has two neurons. Each neuron has four weights and one bias, for a total of ten parameters, adding them together. This model has 46 learnable
parameters in total. We can also calculate this in PyTorch using the dot new ML method. This method returns the number of elements in a tensor by looping through the model's parameters and summing the number of elements. We can confirm that the total is also 46. Understanding parameter count helps us balance model complexity and efficiency. Too many parameters can lead to long training times or overfitting, while too few might limit learning capacity. Welcome back! So far we have seen neural networks made only of linear layers. We can add non-linearity to our models using activation functions. We'll discuss two activation functions sigmoid for binary classification and softmax for multi-class classification. This non-linearity allows networks
to learn more complex interactions between inputs and targets than only linear relationships will call the output of the last linear layer. The pre activation output, which will pass to activation functions to obtain the transformed output. The sigmoid activation function is widely used for binary classification problems. Let's say we are trying to classify an animal as a mammal or not. We have three pieces of information. The number of limbs, whether it lays eggs and whether it has hair.
The latter two binary variables one if yes and zero if no. Passing the input to a model with two linear layers returns a single output, the number six. This number is not yet interpretable, so we pass the number six through the sigmoid function, transforming it into a range representing probability between 0 and 1. We are now ready to perform a binary classification. If the output is closer to one or greater than 0.5, we label it as class one mammal. If it were less than 0.5, the prediction
would be zero. Not a mammal. Let's implement sigmoid in PyTorch here. And then dot sigmoid takes a one dimensional input tensor of values six and returns an output of the same size. Meaning it is also one dimensional. The output is now bounded between 0 and 1. Typically not sigmoid is added as the last step in non-sequential, automatically transforming the output of the final linear layer. Interestingly, a neural network with only linear layers and a sigmoid activation behaves like a logistic regression, but adding more layers and activations unlocks the true power of deep learning, which we'll see later. We use softmax, another popular activation function for multiclass classification involving more than
two class labels. Let's say we have three classes, but zero mammal one and reptile two. In this network, softmax takes a three dimensional pre activation output and generates an output of the same shape one by three. The output is a probability distribution because each element is between 0 and 1, and the values sum to one.
Here the prediction is for the second class mammals, which has the highest probability of 0.842. In PyTorch, we use KNN softmax. Dim equals negative one. Indicates that softmax is applied to input tensors. Last dimension. Similar to sigmoid, softmax can be the last layer in n and sequential. We've explored tensors, small networks, and activation functions. Now let's dive into generating predictions. This process is called running a forward pass through a network. When input data flows through a
neural network in the forward direction to produce outputs or predictions, it passes through each network layer. Calculations transform the data into new representations at every layer, which are passed to the next layer until the final output is produced. The purpose of the forward pass is to pass input data through the network and produce predictions or outputs based on the model's learned parameters, also known as weights and biases.
This process is essential for both training and making new predictions. The final output can be binary classifications, multi-class classifications, or numerical predictions. Regressions will look at an example for each. Say we have input data of five animals with six features, or neurons per data point. We create a small network with two linear layers and one sigmoid activation function in sequence. The first layer takes six features as input outputs four, and the second layer processes
this into a final probability. The output of our binary classification is a single probability between 0 and 1. For each of our five animals. Recall that we commonly use a threshold of 0.5 to turn these probabilities into class labels, such as one mammal or zero not mammal. This output will not be meaningful until we use backpropagation to update layer weights and biases. More on that later.
The model would be similar if we wanted to run multiclass classification. Say we are predicting three classes mammal bird or reptile. We specify our model has three classes. Setting this value as the last linear layer's output dimension. We use softmax instead of sigmoid with dim equals negative one to indicate the five animals have the same last dimension as the last linear layer's output. Using the same input as before, the output shape is five by three. When we print the output, each row
represents probabilities for three classes which sum to one. The predicted label for each row is assigned to the class with the highest probability. In our example, the first and second rows are mammals. The third is a reptile, and so on. The last model will look at is regression. Predicting continuous numerical values. We'll now use the same data to predict the animal weights based on their properties. This time there is no activation function at the end, and the last linear layer's last dimension returns an output with one feature. Output dimensions are five by one five continuous values, one for each row. We've generated predictions by running a forward pass. The next step is to see how good our predictions are compared to the
actual values. The loss function. Another component of neural networks tells us how good our model is at making predictions during training. It takes a model prediction, y hat and true label or ground truth y as inputs and outputs. A float. Let's use our multi-class classification model that predicts whether an animal is a mammal zero, bird one, or reptile two.
Our dataset contains animal characteristics. This example is a bear. Therefore, the class is zero mammal. If our model predicts that the class equals zero, it is correct and the loss value will be low and incorrect prediction would make the loss value high. Our goal is to minimize loss. Loss is calculated using a loss function f, which takes the ground truth y and the prediction y hat as inputs and outputs. A numerical loss value. In our animal example, possible values for our true class of y are integers zero, 1 or 2.
Y hat is the raw prediction. Before applying the softmax function, it is a tensor with the same dimensions as the number of classes n if n is three. The softmax output is a tensor of shape one by three. We use one hot encoding to convert an integer y into a tensor of zeros and ones, so we can compare. To evaluate model performance. For example, if y equals zero with three classes, the encoded form is 100.
We can import tortuga and n functional as f to avoid manual one. Hot encoding. In the first example, ground truth is zero. The first class we have three classes. So the function outputs a three element tensor with one at the first position and zeros otherwise. If y equals one, the second class, the output tensor has one in the second position and zeros otherwise. Lastly, if y equals to the third class, the output tensor has one at the last position and zeros otherwise. With the encoding
complete, we can pass it along with our predictions y hat to a loss function. Here y hat is stored as the tensor scores. The most commonly used loss function for classification is cross entropy loss. We start by defining our loss function as criterion. We then pass it the dot double method of the scores tensor and the one hot target tensor. This ensures tensors are in the correct format for the loss function. The output is the computed loss value. In summary, the loss function takes the scores
tensor as input, which is the model prediction before the final softmax function and the one hot encoded ground truth label. It outputs a single float. The loss of that sample. Recall that our goal is to minimize this loss. In the next video, we'll see how to do that with backpropagation. Excellent job handling those loss functions. Let's now see how we can minimize loss. We know a model predicts poorly when loss is high. We can use derivatives or gradients to minimize this loss. Imagine the
loss function as a valley. The derivative represents the slope, how steeply the curve rises or falls. Steep slopes shown by red arrows indicate high derivatives and large steps. Gentle slopes represented by green arrows have smaller derivatives and smaller steps on the valley floor shown by the blue arrow. The slope is flat and the derivative is zero. This point is the loss functions minimum, which we aim to reach. Convex functions have one global minimum non convex functions such as loss
functions have multiple local minima where the value is lower than nearby points, but not the lowest overall. When minimizing loss functions, we aim to locate the global minimum when x is approximately one. During training we run a forward pass on the features and compute loss by comparing predictions to the target value. Recall that layer weights and biases are randomly initialized when a model is created. We update them during training using a backward pass or backpropagation and deep learning derivatives are known as gradients. We compute the loss function gradients and use them to update the model parameters, including weights and biases with backpropagation. Repeating until the layers
are tuned during backpropagation, if we consider a network of three linear layers, we can calculate local loss gradient with respect to each layer's parameters. We first calculate loss gradients with respect to L2 parameters to L2 and L1, and repeat until we reach the first layer. Let's see this with PyTorch.
After running a forward pass, we define a loss function here cross-entropy loss and use it to compare predictions with target values. Using dot backward, we calculate gradients based on this loss, which are stored in the dot grad attributes of each layer's weights and biases. Each layer in the model can be indexed starting from zero to access its weights, biases, and gradients to manually update model parameters. We access each layer gradient, multiply it by the learning rate, and subtract
this product from the weights. Learning rate is another tunable parameter. We'll discuss this and the training loop later in the course. We use a mechanism called gradient descent to find the global minimum of loss functions. PyTorch simplifies this with optimizers like stochastic gradient descent and SGD. We use opt in to instantiate SGD. Dot parameters. Returns an iterable of all model parameters, which we pass to the optimizer. We use a standard learning rate layer. Here the optimizer automatically calculates gradients and updates model parameters with dot step magic. It's time to train our neural network. Efficient data handling is key to training deep learning models. Our animal classification data is in a CSV file and can be loaded using PD dot. Read CSV. I use hair, feathers, eggs milk
predator legs and tail as features to predict an animal's type. The animal name column isn't needed since names don't determine classification. Note the type column has three categories bird zero, mammal one, and reptile two. Will use dot eye lock to select all columns except the first animal name and last type. Giving us our input features.
These are converted into a numpy array x for easier handling with PyTorch. Similarly, we can extract the last column type and store it as an array of our target values, which represent the class labels for each animal. We'll call this y. We'll use tensor dataset to prepare data for PyTorch models. We first import Torch and tensor dataset from torch. Dot utilized dot data. This allows us to store our features x and target labels y as tensors, making them easy to manage. We convert x and y
into tensors using PyTorch tensor method and pass them to tensor data set. To access an individual sample, we use square bracket indexing. Dataset zero returns a tuple containing the input features and label, which we unpack into input sample and label sample. Once we've created our dataset using tensor data set, we can pass it to data loader to efficiently manage data loading during training. We start by importing data loader from torch. Dot utilized data. Next we define two key parameters. Batch size determines how many samples are included in each iteration. Since deep learning models require large data sets, batching helps process multiple samples at once. Making training more efficient. Shuffle randomizes the data order at each epoch, helping
improve model generalization. One epoch is a full pass through the training data loader, and generalization means the model performs well on unseen data rather than just memorizing the training set. We then create a data loader instance with these parameters, making it easy to iterate through our data set in batches. Let's iterate through data loader. Each element in the data loader is a tuple, which we unpack as batch inputs and batch labels. Since our data set contains five animals and we set a batch size of two, the first iteration randomly selects two animals and their corresponding labels. On the second iteration, two more samples are randomly selected with their labels. Finally, the last remaining sample is returned. Since our dataset has an odd number of samples, the last batch contains just one item
in real world. Deep learning datasets are much larger, with batch sizes of typically 32 or more. For better computational efficiency, we now have the core components to train a PyTorch deep learning model. Once we create a model, choose a loss function, define a dataset, and set an optimizer. We're ready to train. This involves looping through the dataset. Calculating the loss, computing gradients and updating model parameters. This process, called the training loop repeats multiple times. The training loop allows for greater flexibility and control, giving us the option to customize different elements will work with the data set of data scientist salaries. To see this in action, features are categorical and the target is salary in US dollars already normalized. Since the target is a continuous value,
this is a regression problem. For regression, we'll use a linear layer as the final output instead of softmax or sigmoid. Additionally, we'll apply a regression specific loss function as cross-entropy is only used for classification tasks. We can use mean squared error MSE loss for regression problems. The MSE loss is the mean of the squared difference between predictions and ground truth. As shown in this Python implementation
in PyTorch, we use the encore MSE loss function as a criterion. Note that both predictions and targets must be float tensors. Let's put everything together. Now we have two numpy arrays features and target containing our data and labels. We start by passing these to tensor data set to organize our features and targets into the right data types. Floats. This casting is required and float is the data type used by the parameters of our model. We can now load our dataset into the data loader class
to enable batching. Here we use a small batch size of four, but selection of batch size is customizable depending on the use case. We create our model next. This dataset has four input features and one target output. We won't need one hot encoding as this is a regression problem. Finally we create the MSE loss criterion and the optimizer as 0.001. Learning rate is a good default learning rate for most deep learning problems. We can now loop through the data set multiple times. Looping through the entire dataset once is called an epoch, and we train over multiple epochs indicated by num epochs. For each epoch, we loop through the data loader. Each iteration of the data loader provides a batch of samples, which we saw earlier. Before the forward pass, we set the gradients
to zero using optimizer dot zero grad. Because the optimizer stores gradients from previous steps by default. We get features and targets from each sample of the data loader. We use the features for the forward pass of the model, and we use the target for the loss calculation. Finally we use the optimizer to update the parameters of the model. We've seen how activation functions introduce non-linearity to help neural networks learn complex patterns. And we've learned about gradients and their
role within the training loop. Some activation functions can shrink gradients too much making training inefficient. So far we've worked with two activation functions sigmoid and softmax, which are typically used in a model's final layer. We'll begin by understanding some of the limitations of the sigmoid function. The sigmoid outputs are bounded between 0 and 1, meaning that for any input, the output will always fall in this range. Sigmoid could be used at any point in a network. However, the gradients of the sigmoid shown in orange are very small for large and small values of x. This phenomenon is called saturation
during backpropagation. This becomes problematic because each gradient depends on the previous one. When gradients are extremely small, they fail to update the weights effectively. This issue is known as the vanishing gradients problem, and it can make training deep networks very difficult. The softmax function, which also produces bounded outputs between 0 and 1, suffers from saturation in a similar way. Therefore, both of these activation functions are not ideal for hidden layers and are
best used in the last layer only. Will discover two widely used activation functions designed for use between linear layers or in hidden layers. Here is the rectified linear unit or ReLU. ReLU outputs the maximum value between its input and zero, as shown in the graph. For positive inputs, the output equals the input for negative inputs. The output is zero.
This function has no upper bound, and its gradients do not approach zero for large values of x, which helps overcome the vanishing gradients problem. In PyTorch, ReLU can be used through the torch node module. It's a reliable default activation function for many deep learning tasks. The leaky ReLU is a variation of the value function for positive inputs. It behaves exactly like value for negative inputs. It multiplies the input by a small coefficient defaulted to 0.01. In PyTorch, this ensures
the gradients for negative inputs remain non-zero, preventing neurons from completely stopping learning, which can happen with standard ReLU. In PyTorch, the leaky ReLU function is implemented using the torch start and end module. The negative slope parameter controls the coefficient applied to negative inputs. Learning rate has come up a few times. The time has come for us to dig deeper. Training a neural network means solving an optimization problem by minimizing the loss function and adjusting model parameters. To do this, we use an algorithm called stochastic gradient descent or SGD, implemented in PyTorch. Recall this is the optimizer we used to find the global minimum of loss functions. The optimizer takes the model's parameters along with two key arguments. Learning rate, which controls the step
size of updates, and momentum, which adds inertia to help the optimizer move smoothly and avoid getting stuck. Understanding their impact helps us optimize efficiency. Let's try to find the minimum of a U-shaped function. We start at x equals negative two and run the SGD optimizer for ten steps. After these steps we observe that the optimizer is close to the minimum. We can also note that as we approach the minimum, the step size gradually decreases. This happens because the step size is the gradient multiplied by the learning rate. Since the function is less steep near zero, the gradient and thus the step size gets smaller. However, if we use the same algorithm for a learning rate ten times smaller, we realize that we are still far from the minimum of the function. After ten steps,
the optimizer will take much longer to find the function's minimum. If we use a high value for the learning rate, we observe that the optimizer cannot find the minimum and bounces back and forth on both sides of the function. Recall that loss functions are non-convex. One of the challenges when trying to find the minimum of a non-convex function is getting stuck in a local minimum. Let's run our optimizer for 100 steps with no momentum on this non-convex function. We see that the optimizer gets stuck in this first step of the function, which is not its global minimum. However, when using a momentum of 0.9, we can find the minimum of the function. This parameter provides momentum to the optimizer, enabling it
to overcome local dips as shown here. The momentum keeps the step size large when previous steps were also large. Even if the current gradient is small. In summary, two key optimizer parameters impact training learning rate and momentum. The learning rate controls the step size and typical values range from 0.01 to 0.0001. If it's too high, the optimizer may not find the minimum if it's too low. Training slows down momentum helps the optimizer then move past the local minimum. Without it, the optimizer may get stuck here. Typical values range from 0.85 to 0.99.
We've explored how neural networks learn by updating weights during training. This final chapter, we'll look at techniques to evaluate and improve model performance efficiency. Before we get started, please note the topics here are more advanced and we'll cover them at a high level. Data normalization scales input features for stability. Similarly, the weights of a linear layer are also initialized. the small values. This is known as layer initialization. Let's create a small linear layer
and check its weight range. We observe that the weights are between -0.125 and positive 0.125. Why is this important? The output of a neuron in a linear layer is a weighted sum of inputs from the previous layer, keeping both the input data and layer weights small ensures stable outputs. Preventing extreme values that could slow. Training
layers can be initialized in different ways, and it remains an active area of research. PyTorch provides an easy way to initialize layer weights with the next init module. For example, here we initialize a linear layer with a uniform distribution. As you can see, the weights values now range from 0 to 1. In practice, engineers are rarely training a model from randomly initialized weights. Instead, they rely on a concept called transfer learning. Transfer learning takes a model that was
trained on a first task and reuses it for a second task. For example, we trained a model on US data scientist salaries. We now have new data of salaries in Europe. Instead of training a model using randomly initialized weights, we can load weights from the first model and use them as a starting point to train on this new dataset. Saving and loading weights can be done using the torch dot save and the torch dot load functions. These functions work on any type of PyTorch objects. Sometimes the second task is similar to the first task, and we want to perform a specific type of transfer learning called fine tuning. In this case, we load weights from a previously trained model, but train the model with a smaller learning rate. We can even train part of a network if we decide some of the network layers do not need
to be trained and choose to freeze them. A rule of thumb is to freeze early layers of the network and fine tune layers closer to the output layer. This can be achieved by setting each parameters requires grad attribute to false. Here we use the model's named parameters method, which returns the name and the parameter itself we set requires grad on the first layer's weight to false. We've done a lot of training. Now let's evaluate our models. In machine learning, data is split into training,
validation, and test sets. Training data adjusts the model's parameters such as weights and biases. Validation data. June's hyper parameters like learning rate and momentum and the test set evaluates the model's final performance. We'll track two key metrics loss and accuracy during training and validation. Let's begin with loss. Training loss is calculated by summing the loss across all batches in the training data loader. At the end of each epoch, we compute the mean training loss by dividing the total loss by the number of batches.
We begin by setting training loss to zero. We iterate through the train loader, run a forward pass, and compute the loss. As usual, the model computes gradients and updates weights using backpropagation. We add each loss value to the total using dot item, which extracts the numerical value from a tensor. Since one epoch is a full pass through the training data loader, we compute the mean loss by dividing training loss by the number of batches in the train loader. After each training epoch,
we run a validation loop. First, we set the model to evaluation mode using dot eval. As some layers behave differently during training and validation to improve efficiency, we use Torch no grad, which disables gradient calculations. Since we don't update weights during validation, we then iterate through the validation data loader, run the forward pass, and compute the loss, summing it across batches. At the end of the epoch, we calculate the mean validation loss. Finally, we switch the model back to training mode with dot train preparing it for the next training epoch. Keeping track of training and validation loss helps us detect overfitting. When the model overfits training loss keeps decreasing, but validation loss starts to rise. This means the model is learning
the training data too well and won't perform well on new data. Loss tells us how well a model is learning, but it doesn't always reflect how accurately it makes predictions. To measure that we track accuracy using torch metrics. For multi-class classification tasks, we create an accuracy metric with torch metrics. Accuracy. As the model processes each batch, we update this metric using its predictions and the actual labels.
Since the model outputs probabilities for multiple classes, we use argmax dim equals negative one. To select the class with the highest probability. This converts one hot encoded predictions into class indices before passing them to the metric. At the end of each epoch, we calculate the overall accuracy using dot compute. Finally, we reset the metric with dot reset to clear its state before the next epoch. This process is the same for both training and validation. Previously, we learned how to
detect overfitting by looking at the training and validation losses. In this video, we'll discover a few ways we can fight overfitting. Recall that overfitting happens when the model does not generalize to unseen data. If we do not train the model correctly, it will start to memorize the training data, which leads to good performance on the training set, but poor performance on the validation set. Several factors can lead to overfitting a small dataset, a model with too much capacity or large values of weights.
To counter overfitting, we can reduce the model size or add a new type of layer called dropout. We can also use weight decay to force the parameters to remain small. We can get more data or use data augmentation. Let's explore these strategies. A common way to fight overfitting is to add dropout layers to our neural network. Dropout is a regularization technique which randomly deactivates a fraction of neurons during training. Preventing the model from becoming too dependent on specific
features. Dropout layers are typically added after activation functions. The p argument determines the probability of a neuron being set to zero. In this example, 50% of the neurons are dropped. Dropout behaves differently during training and evaluation. During training. It randomly deactivates neurons while during evaluation it is disabled, ensuring all neurons are active for stable predictions. To switch between these modes, we use model, train and model dot eval.
The next strategy to reduce overfitting, we will discover is weight decay. Another form of regularization in PyTorch, weight decay is added to the optimizer using the weight decay parameter. Typically set to a small value, for example 0.001. This parameter adds a penalty to the loss function, encouraging smaller weights and helping the model generalize better. During backpropagation, this penalty is subtracted from the gradient, preventing excessive weight growth. The higher we set the weight decay, the stronger the regularization. Making overfitting less likely. Collecting more data can be expensive, but researchers have found a way to expand datasets artificially using data augmentation. Data augmentation is commonly applied to
image data, which can be rotated and scaled so that different views of the same face become available as new data points. While we won't discuss how to augment data here, it remains a valuable method for combating overfitting when additional data isn't available. In our final video we'll bring everything together and learn a recipe for tackling any deep learning problem. First, we create a model that can overfit the training set. This will ensure that the problem is solvable. We also set a performance baseline to aim for with the validation set. We then need to reduce overfitting to increase performance on the validation set. Finally, we can slightly adjust the different hyperparameters to ensure we achieve the best possible performance. It's useful
to start with a single data point before overfitting the entire training set. This ensures the problem is solvable and helps catch potential bugs. We modify the training loop to repeatedly train on a single example, rather than iterating through the entire data loader. When the model is set up properly, it should quickly reach near zero loss and 100% accuracy on that data point.
Once this step is successful, we scale up to the entire training set. At this stage, we use an existing model architecture. Large enough to overfit while keeping hyperparameters like the learning rate at their defaults. Now we need to create a model that generalizes well to maximize the validation accuracy. We know a few strategies to reduce overfitting, such as including dropout layers, data augmentation, weight decay, or reducing the model capacity. We need to keep track of the different
parameters and the corresponding validation accuracy for each set of experiments. Reducing overfitting often comes at a cost, as applying regularization can significantly impact model performance. The original model overfits the training set, achieving high accuracy but failing to generalize well to new data. In contrast with too much regularization, the updated model shows a drop in training and validation accuracy, limiting its ability to learn effectively.
This highlights the importance of balancing overfitting reduction strategies while closely monitoring key metrics to find the best performing model. Once was satisfied with performance, the final step is fine tuning hyperparameters. This is often done on optimizer settings like learning rate or momentum, grid search tests parameters, and fixed intervals. For example, momentum values from 0.85 to 0.99 and learning rates from ten to the power of -2 to 10, to the power of negative six.
Random search takes a different approach. Instead of testing set values it randomly selects them within a given range. The MP dot random dot uniform function, for example, picks a number between 2 and 6, allowing us to explore a wider variety of learning rates. Random search is often more efficient, as it avoids unnecessary tests and increases the chance of finding optimal settings.

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