Hello! In our last lesson, we learned how to measure a model's performance using metrics like accuracy, precision, and recall. These are crucial for evaluating how well a model is doing, but they don't tell us how to make it better. Today, we'll dive into the core mechanism of how models actually learn from data.
This lesson will introduce two fundamental concepts: loss functions, which quantify a model's error into a single number, and gradient descent, the optimization algorithm that uses this error to systematically adjust the model's parameters and improve its performance. Understanding this process is central to machine learning, as it's the engine that drives model training.
What is a Loss Function?
In the previous lesson, we used metrics like the F1-score to evaluate our model from a business or application perspective. However, for a model to learn algorithmically, it needs a different kind of signal. It needs a loss function (or error function).
A loss function's job is to calculate a single number that represents how "wrong" a model's predictions are compared to the actual target values. The higher the number, the worse the model is doing. The goal of training is to adjust the model's internal parameters—its weights and biases—to make this loss as small as possible.
It's useful to distinguish between a loss function and a cost function. While often used interchangeably, a loss function typically calculates the error for a single training example, while a cost function is the average of the loss over the entire training dataset.
Loss Functions in Machine Learning Explained
This article from DataCamp provides a clear definition of a loss function and explains how it guides the learning process.
Please read the introduction and the first two sections, "What Is a Loss Function?" and "How Loss Functions Work". Focus on the distinction between a loss function and a cost function, and the concept of Empirical Risk Minimization (ERM), which formalizes the goal of minimizing error on the training data.
While there are many types of loss functions, they are generally chosen based on the task (e.g., regression or classification). Two of the most common are:
- Mean Squared Error (MSE): Used for regression tasks, like predicting a house price. It calculates the average of the squared differences between the predicted and actual values. Squaring the error penalizes larger mistakes more heavily.
- Cross-Entropy Loss: Used for classification tasks. It measures how different the model's predicted probabilities are from the true class labels (0s and 1s).
The key takeaway is that the loss function provides the objective that the training process aims to minimize. But how does it do that?
How Models Learn: The Intuition of Gradient Descent
Once we have a loss function, we can think of it as a landscape where the "low ground" or valleys represent a small loss and the "high ground" or hills represent a large loss. Our model's parameters (its weights) determine our position on this landscape. Our goal is to find the lowest point in this landscape.
The algorithm used to do this is called gradient descent. Imagine you are standing on a foggy hillside and want to get to the bottom. You can't see the valley, but you can feel the slope of the ground beneath your feet. The most straightforward strategy is to feel which direction is steepest downhill and take a step in that direction. You repeat this process, taking step after step, and you will eventually find your way to the bottom.

This is precisely the intuition behind gradient descent. The "slope" is given by the gradient of the loss function, and each "step" is an update to the model's weights.
The following video from StatQuest provides an exceptionally clear, step-by-step explanation of this process. It starts by optimizing a single parameter and then builds up to optimizing two, which maps directly to the multi-parameter reality of machine learning models.
Gradient Descent, Step-by-Step
This video, "Gradient Descent, Step-by-Step", visualizes the entire process in a very approachable way.
Please watch the following segments: Introduction : This sets up the problem using a simple linear regression example and defines the loss function (sum of squared residuals). Finding the Minimum : This is the core of the video. It demonstrates how to use the derivative (slope) of the loss function to take iterative steps toward the minimum. Pay close attention to the concepts of 'step size' and 'learning rate'. Optimizing Two Parameters : This extends the concept to a more realistic scenario with two parameters. It introduces the term gradient as the collection of partial derivatives.
The Gradient: Finding the Direction of Steepest Ascent
As the video explained, when we have more than one parameter, we can't just talk about "the slope." We need to know how the loss changes with respect to each parameter individually. This is done using partial derivatives. The gradient is simply a vector that collects all of these partial derivatives.
Here, is the loss function and are the model's parameters. The gradient vector points in the direction of the steepest increase in the loss. To decrease the loss, we must move in the opposite direction, which is why the algorithm is called gradient descent.
This next video from 3Blue1Brown provides a beautiful geometric intuition for what the gradient represents in higher dimensions, which is the situation we're in when dealing with models that have thousands or millions of parameters.
Gradient descent, how neural networks learn Chapter 2, Deep learning
This video from 3Blue1Brown, "Gradient descent, how neural networks learn", provides a stunning visualization of the concept.
Watch from this section to understand how the simple idea of "rolling downhill" generalizes from a 1D or 2D function to the massively high-dimensional functions that represent neural networks. Focus on the core idea that the negative gradient gives you the direction of steepest descent.
The infographic below provides a great summary of the concepts we've discussed so far, including the hill analogy, the key components, and the different types of gradient descent, which we'll touch on next.

The Mechanics of the Update Rule
Now that we have the intuition, let's look at the simple but powerful update rule that lies at the heart of gradient descent.
This article from Outcome School breaks down the mathematics and implementation of gradient descent in a clear, accessible way.
Please read the following sections: Start with the explanation of a derivative as a slope. Carefully study "The Update Rule". This section presents the core formula. Walk through the numeric example to see the rule in action. Read "The Role of Learning Rate" to understand the importance of this hyperparameter. Finally, review the Python code to see a practical implementation.
To summarize the key points from the article:
-
The Update Rule: At each step, every weight in the model is updated according to the rule:
Where:
- is the current value of the weight.
- (alpha) is the learning rate, a small number that controls the size of our step.
- is the partial derivative of the loss with respect to the weight (one component of the gradient).
-
The Learning Rate (): This is a critical hyperparameter.
- If it's too small, training will be very slow as we take tiny steps.
- If it's too large, we might overshoot the minimum and bounce around wildly, failing to converge.
- Finding a good learning rate is a key part of training a model.
-
Types of Gradient Descent:
- Batch Gradient Descent: Calculates the gradient using the entire dataset for each step. This is accurate but very slow on large datasets.
- Stochastic Gradient Descent (SGD): Calculates the gradient using just one randomly chosen example per step. This is fast but the steps are "noisy" and erratic.
- Mini-Batch Gradient Descent: The best of both worlds. It calculates the gradient using a small batch (e.g., 32, 64, 128) of examples. This is the most common approach used in practice as it balances speed and stability.
Conclusion
In this lesson, we've unpacked the fundamental mechanism of machine learning. We saw that for a model to learn, it needs a loss function to quantify its error and an optimization algorithm, gradient descent, to minimize that error.
Key Takeaways:
- A loss function measures the difference between a model's predictions and the actual values, creating a single score that the model aims to minimize.
- Gradient descent is an iterative algorithm that minimizes the loss function by repeatedly taking steps in the direction opposite to the gradient.
- The gradient is a vector of partial derivatives that points in the direction of the steepest increase in loss.
- The learning rate is a crucial hyperparameter that controls the step size in gradient descent. Choosing it correctly is vital for efficient training.
- Mini-batch gradient descent is the standard approach, offering a practical balance between the accuracy of batch GD and the speed of stochastic GD.
We now understand how a model adjusts its parameters to get "better" at a task. However, simply minimizing the loss on the training data as much as possible isn't always the best strategy. A model can become too good at fitting the training data, to the point where it fails to generalize to new, unseen data. This problem is called overfitting, and in our next lesson, we will explore what it is and discuss common techniques used to prevent it.