Linear regression, low-level
A single neuron trained by gradient descent: the model, the cost function, the gradient, and the analytical solution.
Linear regression is the classic entry point to deep learning: a single
neuron, no activation function, trained by gradient descent. Understanding how
it works mechanically — not just model.fit() — lays the groundwork for
everything that follows (deep networks, backprop, optimizers).
The model
We look for an affine function that approximates from :
With several input variables, becomes a vector, and so does :
The cost function
We measure the error over the whole training set with the mean squared error:
where is the number of examples. Squaring penalises large errors more heavily and makes the function differentiable everywhere, unlike the absolute value.
The gradient
To minimise , we compute its derivative with respect to each parameter. For :
And for :
Gradient descent
We update the parameters in the direction opposite to the gradient, scaled by a learning rate :
We repeat until convergence. An that is too large makes training diverge; too small, and it converges, but very slowly.
Minimal implementation
import numpy as np
def train(X, y, lr=0.01, epochs=1000):
m, n = X.shape
w = np.zeros(n)
b = 0.0
for _ in range(epochs):
y_hat = X @ w + b
error = y_hat - y
dw = (2 / m) * X.T @ error
db = (2 / m) * np.sum(error)
w -= lr * dw
b -= lr * db
return w, b
The analytical solution
For this specific case, there is an exact solution, with no iteration: the normal equations.
It avoids gradient descent entirely, but becomes expensive when is large (matrix inversion is ), or impossible if is not invertible. Gradient descent, on the other hand, generalises directly to deep networks — which is why we learn it first.