Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 18

Linear Regression with Gradient Descent: From Scratch

This lesson is built with resources from youtube.com, kdnuggets.com and 1 more site.

Hello! Welcome to the third lesson in our module on the Fundamentals of Model Training.

In the last lesson, we focused on the critical importance of splitting our data into training, validation, and test sets. This ensures we can build models that generalize well and allows us to get an unbiased measure of their performance.

Now that we have our datasets ready, it's time to dive into the core process of training itself. Today, we'll address the learning outcome: Implement linear regression using gradient descent from scratch to understand the training process.

We're building this "from scratch" not because you'll do it this way in your day-to-day work as an AI Engineer (you'll use libraries like PyTorch for that), but because it demystifies what happens inside the .fit() or .train() methods. Understanding this fundamental process of optimization is key to diagnosing issues, tuning models, and grasping how even the most advanced neural networks "learn."

1. The Goal: Finding the Best Line

Linear regression is about finding the best-fitting straight line through a set of data points. For a simple case with one input feature , you might remember the equation of a line from school:

In machine learning, we use slightly different notation and terminology. We write the predicted value, (pronounced "y-hat"), as a function of our input features .

  • is the weight (or coefficient), corresponding to the slope . If we have multiple features, becomes a vector of weights, one for each feature.
  • is the bias, corresponding to the y-intercept.
  • and are the model's parameters. These are the values the model needs to "learn" from the data.

The entire "training" process is about finding the optimal values for and that make our model's predictions () as close as possible to the actual target values ().


2. How "Good" Is Our Line? The Loss Function

To find the "best" line, we first need a way to quantify how "bad" our current line is. We do this with a loss function (also called a cost function or error function). For regression, the most common loss function is the Mean Squared Error (MSE).

The MSE is calculated as follows:

  1. For each data point, calculate the difference between the actual value () and the predicted value (). This difference is the error or residual.
  2. Square each of these errors. This makes all errors positive and penalizes larger errors more heavily.
  3. Calculate the average of these squared errors.

Our goal is to find the values of and that minimize this MSE. The lower the MSE, the better our line fits the data.

The following video provides a great visual introduction to these concepts.

Gradient Descent From Scratch In Python

The video 'Gradient Descent From Scratch In Python' from Dataquest starts by explaining the linear regression equation and introduces the Mean Squared Error (MSE) as a way to measure the model's performance. This will help you visualize the relationship between parameters, predictions, and loss.

Watch the video from 01:51 to 11:27. Focus on: The linear regression equation: y_hat = W1*X1 + b. The concept of the Mean Squared Error (MSE) as a loss function. The visualization of how the loss changes as the weight parameter changes, forming a U-shaped curve.


3. Finding the Minimum Loss: Gradient Descent

So, how do we find the values of and that give us the minimum loss? We can't just try every possible combination; that would be infinitely complex. Instead, we use an optimization algorithm called Gradient Descent.

Imagine you are on a foggy mountain and want to get to the lowest point in the valley. You can only see the ground right beneath your feet. A good strategy would be to feel which direction is the steepest downhill and take a small step in that direction. You repeat this process, and eventually, you'll find yourself at the bottom.

Path of Converging Gradient Descent on a Cost Surface
This visualization shows the path of gradient descent. It iteratively takes steps "downhill" on the loss surface to find the point with the minimum loss, which corresponds to the optimal weights for the model.

This is exactly what gradient descent does:

  1. Gradient: In calculus, the gradient is a vector of partial derivatives. It points in the direction of the steepest ascent of a function. For our model, it tells us how the loss will change if we slightly increase the weight or the bias .
  2. Descent: Since we want to minimize the loss, we move in the opposite direction of the gradient.
  3. Learning Rate (): We need to control the size of the step we take. This is a hyperparameter called the learning rate.

The update rules for our parameters are:

Here, and are the partial derivatives of the loss function with respect to the weight and bias .

Choosing the right learning rate is crucial.

  • If it's too small, training will be very slow.
  • If it's too large, we might "overshoot" the minimum and our loss might actually increase. The algorithm can diverge instead of converging.
Path of Diverging Gradient Descent
If the learning rate is too high, the algorithm can overshoot the minimum on each step, leading to a diverging path where the loss gets worse over time.

4. The Math: Deriving the Gradients

To implement the update rules, we need the formulas for the partial derivatives. Let's derive them.

Implementing Linear Regression with Gradient Descent ...

This article, 'Implementing Linear Regression with Gradient Descent From Scratch', provides a clear, mathematical derivation of the gradients for both the weights and the bias. Understanding where these formulas come from is the final piece of theory we need before coding.

Read the section 'Deriving Gradient Descent'. It walks you through applying the chain rule to find the partial derivatives of the MSE loss function with respect to the weights (w) and bias (b). Don't worry about memorizing the derivation, but focus on understanding how the final equations are reached.

To summarize the key results from the derivation:

The partial derivative of the loss with respect to the weight is:

And the partial derivative with respect to the bias is:

(Note: The factor of 2 is sometimes dropped, as its effect can be absorbed into the learning rate. We'll keep it for correctness but you may see implementations without it.)

With these formulas, we have everything we need to write the code.


5. Implementation: The Training Loop

Now we'll translate these concepts into a Python implementation. As a software engineer, you'll recognize this as an iterative algorithm. We'll structure it as a Python class, which is a clean way to organize our model.

The training process, which happens inside the .fit() method, follows a loop. Each full pass over the entire training dataset is called an epoch.

Here's the algorithm for one epoch of gradient descent:

  1. Forward Pass: Calculate the model's predictions () for all training samples using the current weights and bias.
  2. Calculate Gradients: Use the predictions and the true labels to compute the gradients and using the formulas we just derived.
  3. Update Parameters: Update and using the gradients and the learning rate.

We repeat this process for a set number of epochs.

Linear Regression from Scratch with NumPy

The article 'Linear Regression from Scratch with NumPy' provides a great, concise implementation inside a Python class. Pay special attention to how it uses NumPy's vectorized operations.

Read the sections from 'Initialize Linear Regression Class' to the end. Focus on how the mathematical concepts are translated into NumPy code: The __init__ method sets up hyperparameters. The fit method contains the main training loop. Notice the use of np.dot(X, self.weights) for a fast, vectorized forward pass. See how the gradient calculations dw and db are implemented efficiently with NumPy.

Let's bring it all together into a final, working example. Below is a complete implementation of a LinearRegression class.

import numpy as np

class LinearRegression:
    """
    Linear Regression model implemented from scratch using Gradient Descent.
    """
    def __init__(self, learning_rate=0.01, n_iters=1000):
        self.lr = learning_rate
        self.n_iters = n_iters
        self.weights = None
        self.bias = None

    def fit(self, X, y):
        """
        Train the model using gradient descent.
        X: training features (n_samples, n_features)
        y: training labels (n_samples,)
        """
        n_samples, n_features = X.shape
        
        # 1. Initialize parameters
        self.weights = np.zeros(n_features)
        self.bias = 0
        
        # Gradient Descent loop
        for _ in range(self.n_iters):
            # 2. Forward Pass: Make predictions
            y_predicted = np.dot(X, self.weights) + self.bias
            
            # 3. Backward Pass: Compute gradients
            # Note: The (y_predicted - y) is the negative of (y - y_hat) from the formula,
            # which cancels out the negative sign in the derivative.
            dw = (1 / n_samples) * np.dot(X.T, (y_predicted - y))
            db = (1 / n_samples) * np.sum(y_predicted - y)
            
            # 4. Update parameters
            self.weights -= self.lr * dw
            self.bias -= self.lr * db
            
    def predict(self, X):
        """
        Make predictions on new data.
        """
        return np.dot(X, self.weights) + self.bias

# --- Example Usage ---
if __name__ == '__main__':
    from sklearn.model_selection import train_test_split
    from sklearn.datasets import make_regression
    import matplotlib.pyplot as plt

    # Generate a sample dataset
    X, y = make_regression(n_samples=100, n_features=1, noise=20, random_state=42)
    
    # In the previous lesson, we learned to split into train, val, and test.
    # For simplicity here, we'll just use a train/test split.
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=123)

    # Instantiate and train our model
    regressor = LinearRegression(learning_rate=0.01, n_iters=1000)
    regressor.fit(X_train, y_train)
    
    # Make predictions on the test set
    predictions = regressor.predict(X_test)

    # Calculate the final loss (MSE) on the test set
    def mse(y_true, y_predicted):
        return np.mean((y_true - y_predicted)**2)

    mse_value = mse(y_test, predictions)
    print(f"Mean Squared Error on test set: {mse_value:.2f}")

    # Visualize the results
    y_pred_line = regressor.predict(X)
    plt.figure(figsize=(8, 6))
    plt.scatter(X_train, y_train, color='blue', label='Training data')
    plt.scatter(X_test, y_test, color='green', label='Test data')
    plt.plot(X, y_pred_line, color='red', linewidth=2, label='Prediction line')
    plt.title("Linear Regression from Scratch")
    plt.xlabel("Feature")
    plt.ylabel("Target")
    plt.legend()
    plt.show()
Test your understanding!

In the fit method of the code above, what would happen to the training process if you set the learning_rate to a very large value, like 5.0? What if you set it to a very small value, like 1e-9?

Show answer
  • Large learning_rate (e.g., 5.0): The algorithm would likely diverge. The parameter updates would be so large that they would consistently overshoot the minimum of the loss function. The loss would likely explode to Infinity or NaN (Not a Number) after a few iterations as the weights and biases grow to extreme values.

  • Small learning_rate (e.g., 1e-9): The algorithm would learn extremely slowly. The parameter updates would be minuscule, and it would take a vast number of iterations (n_iters) to converge to a good solution. After 1000 iterations, the model would likely still be very close to its initial state and perform poorly.


Conclusion

Congratulations! You have now implemented the entire training process for a machine learning model from the ground up. You've turned abstract mathematical concepts into working code.

Key Takeaways:

  • Parameters (): These are the learnable values that define your model.
  • Loss Function (MSE): This function quantifies how well your model is performing on the training data.
  • Gradient Descent: This is the iterative optimization algorithm used to find the parameters that minimize the loss function.
  • Training Loop: The core of model training consists of a loop with three steps: a forward pass to make predictions, a backward pass to compute gradients, and a parameter update step.
  • Learning Rate (): A critical hyperparameter that controls the step size of gradient descent.

This fundamental loop—predict, calculate loss, compute gradients, update weights—is the engine that powers not just linear regression, but also the massive neural networks used in modern AI. The only difference is that the models and their loss functions are far more complex.

Next up:
We've successfully trained a model on our training data. But how do we know if it has learned a general pattern or just memorized the training set? In the next lesson, we will explore overfitting and underfitting and learn how to use our validation set to diagnose these critical issues.