Linear & Logistic Regression

The two foundational models — linear regression with mean squared error and the normal equation, logistic regression with the sigmoid and cross-entropy, decision boundaries, softmax for multiple classes, feature scaling, regularisation (L1/L2), and interpreting coefficients.

Intermediate 4 min readLesson 3 of 14

Linear and logistic regression are simple, fast, interpretable — and still widely used in production. They also introduce every concept deep learning builds on: a parameterised model, a loss function, and optimisation. A neural network is, in a sense, many logistic regressions stacked together.

Linear regression

Predict a number as a weighted sum of features plus a bias:

y^=w1x1+w2x2+⋯+wdxd+b=w⊤x+b\hat{y} = w_1 x_1 + w_2 x_2 + \cdots + w_d x_d + b = \mathbf{w}^\top \mathbf{x} + b

For house prices: y^=0.42⋅area+8.1⋅bedrooms−0.6⋅age+12\hat{y} = 0.42 \cdot \text{area} + 8.1 \cdot \text{bedrooms} - 0.6 \cdot \text{age} + 12 (in lakhs). Each weight says how much the prediction changes per unit of its feature, holding others fixed.

The loss: mean squared error

Training finds the weights that minimise the average squared difference between predictions and true values:

MSE=1n∑i=1n(y^i−yi)2\text{MSE} = \frac{1}{n} \sum_{i=1}^{n} (\hat{y}_i - y_i)^2

Squaring makes all errors positive and punishes large errors heavily (which also makes MSE sensitive to outliers — MAE or Huber loss are more robust).

Solving it

Two ways:

  1. Closed form (the normal equation): w=(X⊤X)−1X⊤y\mathbf{w} = (X^\top X)^{-1} X^\top \mathbf{y}. Exact, but inverting a d×d matrix costs O(d³) — fine for small d.
  2. Gradient descent: start anywhere and repeatedly step downhill. Scales to huge datasets and is how everything in deep learning is trained.
Python
import numpy as np

rng = np.random.default_rng(0)
X = rng.uniform(50, 250, size=(200, 1))                 # area in m²
y = 0.45 * X[:, 0] + 15 + rng.normal(0, 8, 200)         # true relation + noise

# Gradient descent from scratch
Xs = (X - X.mean()) / X.std()                           # scale features
w, b, lr = 0.0, 0.0, 0.1
for epoch in range(500):
    pred = Xs[:, 0] * w + b
    err = pred - y
    w -= lr * 2 * (err * Xs[:, 0]).mean()               # ∂MSE/∂w
    b -= lr * 2 * err.mean()                            # ∂MSE/∂b
print(f"w={w:.2f}, b={b:.2f}, mse={(err**2).mean():.1f}")

# Same with scikit-learn
from sklearn.linear_model import LinearRegression
model = LinearRegression().fit(X, y)
print(model.coef_, model.intercept_)                    # ≈ [0.45], 15

Beyond straight lines

"Linear" means linear in the weights, not the features. Add transformed features — x2x^2, log⁡x\log x, interactions x1x2x_1 x_2, one-hot encoded categories — and a linear model can fit curves (polynomial regression). Too many features invites overfitting, which brings us to regularisation.

Logistic regression: classification

To predict a probability of a class (spam? fraud? will churn?), squash the linear score into (0, 1) with the sigmoid:

σ(z)=11+e−z,P(y=1∣x)=σ(w⊤x+b)\sigma(z) = \frac{1}{1 + e^{-z}}, \qquad P(y = 1 \mid \mathbf{x}) = \sigma(\mathbf{w}^\top \mathbf{x} + b)
Score zσ(z)
−40.02
00.50
20.88
60.998

Predict class 1 if the probability exceeds a threshold (0.5 by default — tune it to trade precision against recall; see Model evaluation). The decision boundary, where w⊤x+b=0\mathbf{w}^\top \mathbf{x} + b = 0, is a line (or hyperplane) in feature space.

The loss: binary cross-entropy (log loss)

L=−1n∑i[yilog⁡p^i+(1−yi)log⁡(1−p^i)]L = -\frac{1}{n} \sum_{i} \left[ y_i \log \hat{p}_i + (1 - y_i) \log(1 - \hat{p}_i) \right]

If the true label is 1 and the model says 0.99, the loss is tiny; if it says 0.01, the loss is huge (−log 0.01 ≈ 4.6). MSE is a poor fit here: combined with the sigmoid it creates a non-convex loss with flat regions. Cross-entropy is convex for logistic regression, so gradient descent finds the global optimum. Its gradient is beautifully simple: (p^−y) x(\hat{p} - y)\,\mathbf{x}.

Interpreting coefficients

Each weight is the change in the log-odds per unit of the feature; ewe^{w} is the odds ratio. A weight of 0.7 on "has previous default" means the odds of default are e0.7≈2×e^{0.7} \approx 2\times higher. This interpretability is why logistic regression remains popular in credit scoring and medicine.

Multiple classes: softmax

For K classes, compute one score per class and convert scores to a probability distribution with softmax:

P(y=k∣x)=ezk∑j=1KezjP(y = k \mid \mathbf{x}) = \frac{e^{z_k}}{\sum_{j=1}^{K} e^{z_j}}

Trained with categorical cross-entropy. Softmax plus cross-entropy is exactly the final layer of most neural network classifiers — and of LLMs choosing the next token from a vocabulary.

Python
from sklearn.linear_model import LogisticRegression
from sklearn.datasets import load_iris

X, y = load_iris(return_X_y=True)                # 3 species
clf = LogisticRegression(max_iter=500).fit(X, y) # multinomial (softmax) by default
print(clf.predict_proba(X[:1]))                  # e.g. [[0.98, 0.02, 0.00]]

Feature scaling

Gradient descent converges much faster when features have similar scales (area in thousands, bedrooms in single digits would make the loss surface a long narrow valley). Standardise features (subtract mean, divide by standard deviation). Fit the scaler on training data only and apply it to validation/test data, or you leak information.

Regularisation

Penalise large weights to reduce overfitting:

MethodPenalty added to lossEffect
Ridge (L2)λ∑wj2\lambda \sum w_j^2Shrinks all weights smoothly; handles correlated features
Lasso (L1)λ∑∣wj∣\lambda \sum \lvert w_j \rvertDrives some weights exactly to zero — automatic feature selection
Elastic netBothA mix

λ (alpha in scikit-learn; C = 1/λ for LogisticRegression) is a hyperparameter chosen by cross-validation. The same L2 idea appears in neural networks as weight decay.

Assumptions and limits

  • Assumes a roughly linear relationship (after feature engineering) — can't discover complex interactions on its own; trees and neural networks can.
  • Sensitive to outliers (linear regression) and to highly correlated features (unstable coefficients — multicollinearity).
  • Strong baselines: always try a regularised linear/logistic model first. If a complex model barely beats it, the complexity may not be worth it.
Key takeaways
  • Linear regression predicts a weighted sum of features, trained by minimising mean squared error (closed form or gradient descent).
  • Logistic regression passes the linear score through a sigmoid to get a probability, trained with cross-entropy.
  • Softmax + cross-entropy generalises to many classes — the output layer of most neural classifiers and LLMs.
  • Coefficients are interpretable (log-odds and odds ratios for logistic regression).
  • Scale features using training statistics only; regularise with L2 (ridge) or L1 (lasso, sparse weights).
  • Always use them as strong, interpretable baselines.