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.
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:
For house prices: (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:
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:
- Closed form (the normal equation): . Exact, but inverting a d×d matrix costs O(d³) — fine for small d.
- Gradient descent: start anywhere and repeatedly step downhill. Scales to huge datasets and is how everything in deep learning is trained.
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], 15Beyond straight lines
"Linear" means linear in the weights, not the features. Add transformed features — , , interactions , 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:
| Score z | σ(z) |
|---|---|
| −4 | 0.02 |
| 0 | 0.50 |
| 2 | 0.88 |
| 6 | 0.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 , is a line (or hyperplane) in feature space.
The loss: binary cross-entropy (log loss)
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: .
Interpreting coefficients
Each weight is the change in the log-odds per unit of the feature; is the odds ratio. A weight of 0.7 on "has previous default" means the odds of default are 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:
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.
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:
| Method | Penalty added to loss | Effect |
|---|---|---|
| Ridge (L2) | Shrinks all weights smoothly; handles correlated features | |
| Lasso (L1) | Drives some weights exactly to zero — automatic feature selection | |
| Elastic net | Both | A 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.
- 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.