Linear regression fits a weighted sum of the inputs to a number. Logistic regression squashes that same weighted sum through a sigmoid and reads it as a probability. Both are small enough to derive on paper, and almost everything later in deep learning (losses, gradients, maximum likelihood, decision boundaries) shows up here first in a form you can fully check. I treat them as the model to beat before reaching for anything bigger.

Draw the straight line that misses the dots by as little as possible. Image: Justinkunimune, CC0, via Wikimedia Commons.

Mental Model

  • A linear model is a dot product . Fitting means choosing so the predictions are close to the targets.
  • Least squares has a closed form, and geometrically it is an orthogonal projection of the target vector onto the column space of the data matrix.
  • Squared error is not an arbitrary choice: it is exactly what maximum likelihood gives under Gaussian noise.
  • Logistic regression is linear in the log-odds. Its decision boundary is a hyperplane, and its loss (cross-entropy) is convex.
  • Both models give clean gradients of the form (prediction minus target) times input.

1. Least Squares and the Normal Equations

Stack examples into a matrix (with a column of ones for the bias) and the targets into . The loss is the residual sum of squares:

Setting the gradient to zero gives the normal equations:

The Hessian is , which is positive semidefinite, so any stationary point is a global minimum. If the columns of are linearly dependent (or ), is singular and the minimizer is not unique. In practice you solve with a QR or SVD routine (np.linalg.lstsq) instead of forming the inverse, because squares the condition number of .

Worked example

Four points: and . With the normal equations are Solving gives , , so the line is . The residuals are and the RSS is . The code below reproduces this.

2. The Geometric View

The vector lives in the column space of , a -dimensional subspace of . Least squares picks the point in that subspace closest to , which is the orthogonal projection:

is the hat matrix. The residual is orthogonal to every column of , which is just the normal equations rewritten as . In the example above, comes out as zero up to rounding, and when the model has a bias column the residuals also sum to zero.

Intuition

Think of the data as one arrow in -dimensional space and the features as arrows spanning a flat sheet. The fit is the shadow of the target arrow on that sheet. Adding a feature enlarges the sheet, so the shadow can only get closer, which is why training error never rises when you add features.

3. Maximum Likelihood Under Gaussian Noise

Assume with independent. The likelihood of the data is a product of Gaussians, so the log-likelihood is

Only the second term depends on , and it is a negative constant times the RSS. Maximizing the likelihood therefore equals minimizing squared error. The same derivation tells you what goes wrong when the noise is not Gaussian: heavy-tailed noise makes squared error chase outliers, and a Laplace noise model would lead to absolute error instead. Adding a Gaussian prior on turns the MAP estimate into ridge regression, which is picked up in Generalization and Regularization.

4. Logistic Regression

For binary labels , model the probability of class 1 as

Equivalently, the log-odds are linear: . Each label is a Bernoulli draw, so the negative log-likelihood is the binary cross-entropy:

The sigmoid has the convenient derivative . Chain rule on makes the factors cancel, leaving

That is the same “error times input” shape as linear regression, with in place of . The loss is convex (the Hessian is with ), but there is no closed-form solution, so you use gradient descent or Newton’s method (iteratively reweighted least squares). If the classes are perfectly separable, the weights grow without bound, since pushing up always lowers the loss. A small L2 penalty fixes that.

The multi-class version replaces the sigmoid with softmax and the loss with categorical cross-entropy, the same pair used at the output of nearly every classifier network (see Foundation Models L02: ML Basics).

5. The Decision Boundary

Predicting class 1 when is the same as predicting it when . The boundary is the hyperplane , and is its normal vector. The distance of a point from the boundary is , so is a signed, scaled distance and turns it into a confidence. A threshold other than 0.5 just shifts the boundary parallel to itself, which matters when the costs of errors differ (see Evaluation Metrics).

The boundary is linear in the features you give it. Add , and so on and the boundary becomes a conic in the original space while the model stays linear in its parameters.

6. Running It

import numpy as np
 
# --- least squares: four points, line y = w0 + w1 x ---
x = np.array([1.0, 2, 3, 4]); y = np.array([2.1, 2.9, 4.2, 4.8])
X = np.c_[np.ones(4), x]
w = np.linalg.solve(X.T @ X, X.T @ y)
r = y - X @ w
print("w =", w, " RSS =", round(r @ r, 3), " X^T r =", np.round(X.T @ r, 10))
 
# --- logistic regression by gradient descent on two Gaussian blobs ---
rng = np.random.default_rng(0)
Xd = np.r_[rng.normal(-1, 1, (200, 2)), rng.normal(1, 1, (200, 2))]
yd = np.r_[np.zeros(200), np.ones(200)]
A = np.c_[np.ones(400), Xd]
sigmoid = lambda z: 1 / (1 + np.exp(-z))
w = np.zeros(3)
for _ in range(2000):
    p = sigmoid(A @ w)
    g = A.T @ (p - yd) / len(yd)          # gradient of mean cross-entropy
    w -= 0.5 * g
p = sigmoid(A @ w)
loss = -np.mean(yd * np.log(p) + (1 - yd) * np.log(1 - p))
print("w =", w.round(3), " loss =", round(loss, 3), " acc =", np.mean((p > 0.5) == yd))

Running this prints w = [1.15 0.94], RSS = 0.082 for the line fit. For the classifier it prints w = [0.09 1.877 1.775], a loss of 0.204 and an accuracy of 0.9. The boundary is , nearly the anti-diagonal that separates the two blobs, tilted a hair by the bias. The blobs overlap (their centers are standard deviations apart), so 90% training accuracy is close to what any classifier can reach on this data.

Common mistake

Do not read logistic regression coefficients as effects on probability. A one-unit increase in adds to the log-odds, i.e. multiplies the odds by . The change in probability depends on where you start.