Abstract flowing gradient in deep indigo and blue tones, smooth and luminous, evoking a modern digital learning atmosphere

Computer Science and programming articles. We do not sell courses.

Linear regression with gradient descent from scratch

Linear regression is often the first useful model in supervised learning because it predicts a continuous value from one or more numeric inputs. Its central idea is straightforward: fit a straight line by choosing an intercept and coefficients that make the prediction errors as small as possible. Gradient descent supplies the repeated method for finding those parameters.

Building an understanding of linear regression with gradient descent from scratch goes beyond copying an optimiser. It connects a prediction equation to a loss function, derives the gradient, translates the maths into Python, and tests whether the fitted relationship generalises. These habits remain valuable when a one-feature model grows into a larger predictive system.

What the model is really learning

In its simplest form, the model is (\hat{y}_i=b_0+b_1x_i). The intercept (b_0) gives the prediction when the input is zero, and the slope (b_1) describes how the prediction changes for each unit increase in (x). A fitted model is therefore a line of best fit, not a claim that one variable mechanically causes another.

An Australian housing example makes the variables concrete. Prices are recorded in Australian dollars, floor area in square metres, and travel distances in kilometres. A Melbourne property model might include distance to a tram stop, while a Sydney model might include rail access. Many Australian homes are sold at auction, making the final transaction price a better target than a vendor's guide price.

Several inputs extend the same equation to (\hat y=b_0+b_1x_1+\cdots+b_px_p). Each coefficient gives the expected change in predicted price for one unit of that feature while the others stay fixed. The coefficients are useful for explanation, but predictions outside the observed ranges remain risky extrapolation.

Turning predictions into a measurable objective

A residual is the signed gap between a prediction and its observation: (e_i=\hat y_i-y_i). To turn many gaps into one number, least-squares linear regression minimises the mean squared error, (J=\frac{1}{2n}\sum e_i^2). The factor (1/(2n)) keeps the value tied to the dataset size and simplifies the derivative.

Squaring prevents positive and negative residuals from cancelling. It also gives large mistakes extra influence, which is useful when an A$20,000 error matters more than an A$2,000 error. The loss is measured in squared Australian dollars, so root mean squared error is often reported to restore the target's original unit.

This estimator is designed for a continuous target. For a binary outcome such as whether a property sells above its guide price, a logistic regression guide covers the suitable sigmoid model, probability interpretation and different loss function.

Deriving the gradient update

The gradient indicates how the loss changes as each parameter moves. Start with the error (e_i=\hat y_i-y_i), differentiate the square, and apply the chain rule: the error is multiplied by the derivative of the prediction. For the simple line, this produces (\frac{\partial J}{\partial b_0}=\frac{1}{n}\sum e_i) and (\frac{\partial J}{\partial b_1}=\frac{1}{n}\sum x_ie_i).

With those derivatives known, each training example contributes to a direction of improvement. The parameters are changed using (b_0\leftarrow b_0-\alpha\frac{1}{n}\sum e_i) and (b_1\leftarrow b_1-\alpha\frac{1}{n}\sum x_ie_i). Both new values must use gradients calculated from the same old parameters; updating one and immediately using it to calculate the other would change the intended path.

A learning rate, usually written as alpha, scales each step. Too small means the optimiser crawls; too large means it overshoots. Scaling predictors helps because a feature measured in hundreds and another measured in single digits otherwise create very different gradient magnitudes.

Building the optimiser in plain Python

The following batch implementation uses only Python's standard library. Every iteration visits all observations, computes both gradients, and then applies simultaneous updates. It standardises the input area before optimisation and returns a prediction function that performs the same transformation for new values.

from math import sqrt

def fit_linear_regression(xs, ys, learning_rate=0.05, epochs=2000):
    n = len(xs)
    x_mean = sum(xs) / n
    x_std = sqrt(sum((x - x_mean) ** 2 for x in xs) / n)
    z_values = [(x - x_mean) / x_std for x in xs]

    intercept = 0.0
    slope = 0.0

    for _ in range(epochs):
        grad_intercept = 0.0
        grad_slope = 0.0

        for z, y in zip(z_values, ys):
            prediction = intercept + slope * z
            error = prediction - y
            grad_intercept += error
            grad_slope += error * z

        intercept -= learning_rate * grad_intercept / n
        slope -= learning_rate * grad_slope / n

    def predict(x):
        z = (x - x_mean) / x_std
        return intercept + slope * z

    return predict, intercept, slope


areas_m2 = [45, 52, 61, 74, 89, 103]
prices_aud_thousands = [520, 580, 650, 720, 810, 910]

predict, intercept, slope = fit_linear_regression(
    areas_m2, prices_aud_thousands
)

rmse = sqrt(
    sum(
        (predict(x) - y) ** 2
        for x, y in zip(areas_m2, prices_aud_thousands)
    ) / len(areas_m2)
)

print(f"RMSE: {rmse:.2f} thousand Australian dollars")

The sample data are illustrative rather than market quotations: area is measured in square metres and target values are thousands of Australian dollars. Because area is standardised, slope represents the change in price per standard deviation of area; intercept corresponds to the mean area. The predict function hides that internal representation.

Publishing a fitted predictor through a small API is a separate layer. The site's web development guide explains how to move from a Python function to an application while keeping the numerical model unchanged.

Controlling learning rate and convergence

The learning rate is the first parameter to test. With 0.001, a model may need thousands of iterations; with 0.1, the same model may oscillate or diverge. Plot the loss after every iteration: a steady decline followed by a plateau suggests useful convergence, while a sharp rise usually means the step is too large.

Batch gradient descent is stable but can be slow for a large dataset. Stochastic gradient descent updates after each example, and mini-batch gradient descent processes a small group at once. Those variants can move faster and add noise, yet all rely on the same gradient estimate and learning-rate controls. For (n) rows and (p) features, each batch iteration costs (O(np)).

Australian teams often encourage someone to “have a go” at a quick baseline, and a short Python script is ideal for that experiment. Keep the baseline simple, record the learning rate and scaling method, and compare the final loss with a constant-mean predictor. A reproducible run is more valuable than a promising result that nobody can repeat.

A practical validation checklist

Fit the model only on training data, then use a validation set to tune the learning rate and number of iterations. Reserve a separate test set for the final assessment. For Australian property data, a time-based split can be more realistic than a random split because recent quarters may reflect different interest rates and auction conditions than earlier ones.

Evaluate more than training error. RMSE highlights large misses, mean absolute error is easy to express in thousands of Australian dollars, and (R^2) compares the model with a mean-value baseline. Residual plots can reveal curved patterns, unequal spread or influential examples that a single score conceals.

Broader problem-solving tutorials show how to frame a modelling task, test assumptions and communicate the limits of a result. The outcome is a transparent numerical model whose coefficients, errors and assumptions can be inspected before it informs any Australian housing decision.