TExcelTAD

Logistic Regression

Is this transaction fraud? Will this customer cancel? Is this tumour malignant? For a yes/no question you want more than a yes or no: you want a probability, so you can set a threshold that fits the cost of each kind of mistake. Logistic regression gives exactly that. Despite the name it is a classifier, the standard first model for binary problems, and the output layer of most neural-network classifiers. The Machine Learning course uses it through scikit-learn; here you derive the loss and fit it with Newton's method.

The model

Compute a linear score, then squash it into (0,1)(0, 1) with the sigmoid:

z=w⊤x+b,p(y=1∣x)=σ(z)=11+e−zz = \mathbf{w}^\top \mathbf{x} + b, \qquad p(y = 1 \mid \mathbf{x}) = \sigma(z) = \frac{1}{1 + e^{-z}}

Inverting the sigmoid shows what the linear part models: the log-odds,

log⁡p1−p=w⊤x+b.\log \frac{p}{1 - p} = \mathbf{w}^\top \mathbf{x} + b .

So a weight wjw_j means "one unit more of xjx_j multiplies the odds by ewje^{w_j}". The decision boundary p=0.5p = 0.5 is where z=0z = 0: a straight line in two dimensions, a hyperplane in general.

The loss: maximum likelihood

Treat each label as a coin flip with probability pi=σ(zi)p_i = \sigma(z_i). The likelihood of the training labels is ∏ipiyi(1−pi)1−yi\prod_i p_i^{y_i} (1 - p_i)^{1 - y_i}; maximising it is the same as minimising the log-loss (binary cross-entropy):

ℓ(w,b)=−∑i=1n[yilog⁡pi+(1−yi)log⁡(1−pi)]=∑i=1n[log⁡(1+ezi)−yizi]\ell(\mathbf{w}, b) = -\sum_{i=1}^{n} \big[ y_i \log p_i + (1 - y_i) \log(1 - p_i) \big] = \sum_{i=1}^{n} \big[ \log(1 + e^{z_i}) - y_i z_i \big]

Its gradient has the same shape as linear regression's, the error times the input:

∇wℓ=∑i=1n(pi−yi) xi=X⊤(p−y),∇w2ℓ=X⊤SX,S=diag⁡(pi(1−pi))\nabla_{\mathbf{w}} \ell = \sum_{i=1}^{n} (p_i - y_i) \, \mathbf{x}_i = X^\top (\mathbf{p} - \mathbf{y}), \qquad \nabla^2_{\mathbf{w}} \ell = X^\top S X, \quad S = \operatorname{diag}\big(p_i (1 - p_i)\big)

The Hessian is positive semidefinite, so the loss is convex: no local minima to get stuck in. There is no closed form, but Newton's method θ←θ−H−1∇\boldsymbol{\theta} \leftarrow \boldsymbol{\theta} - H^{-1} \nabla converges in a handful of steps. Derivations: Maximum Likelihood Estimation, Maximum Likelihood and Cross-Entropy, Newton's Method.

scikit-learn regularises by default. It minimises

12∥w∥2+C∑i=1n[log⁡(1+ezi)−yizi],\frac{1}{2} \lVert \mathbf{w} \rVert^2 + C \sum_{i=1}^{n} \big[ \log(1 + e^{z_i}) - y_i z_i \big],

so CC is an inverse strength: small CC, strong regularisation. Without the penalty, perfectly separable data would push the weights to infinity.

From scratch with Newton's method

On the breast-cancer data (standardised on the training part), Newton's method on scikit-learn's objective:

python · try it yourself
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

X, y = load_breast_cancer(return_X_y=True)           # y = 1 means benign
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=0, stratify=y)
sc = StandardScaler().fit(X_tr)
X_tr, X_te = sc.transform(X_tr), sc.transform(X_te)

def sigmoid(z):
    return 1 / (1 + np.exp(-z))

def objective(w, b, X, y, C):
    z = X @ w + b
    logloss = np.sum(np.logaddexp(0, z) - y * z)      # sum of -log p(y_i), computed stably
    return 0.5 * w @ w + C * logloss

def fit_logistic_newton(X, y, C=1.0, iters=8):
    """Newton's method on 1/2 ||w||^2 + C * sum log-loss (scikit-learn's objective)."""
    Xb = np.column_stack([X, np.ones(len(y))])        # last column: intercept (not penalised)
    theta = np.zeros(Xb.shape[1])
    reg = np.eye(Xb.shape[1]); reg[-1, -1] = 0
    for it in range(iters):
        p = sigmoid(Xb @ theta)
        grad = reg @ theta + C * Xb.T @ (p - y)
        H = reg + C * (Xb.T * (p * (1 - p))) @ Xb
        theta -= np.linalg.solve(H, grad)
        print(f"  iteration {it + 1}  objective {objective(theta[:-1], theta[-1], X, y, C):.4f}")
    return theta[:-1], theta[-1]

w, b = fit_logistic_newton(X_tr, y_tr)
sk = LogisticRegression(C=1.0, tol=1e-8, max_iter=10000).fit(X_tr, y_tr)
print("same weights as sklearn:", np.allclose(w, sk.coef_[0], atol=1e-3), np.isclose(b, sk.intercept_[0], atol=1e-3))
p = sigmoid(X_te @ w + b)
print("first 4 test probabilities of 'benign':", p[:4].round(3), " labels:", y_te[:4])
print("test accuracy ours", round(np.mean((p >= 0.5) == y_te), 3), " sklearn", round(sk.score(X_te, y_te), 3))
  iteration 1  objective 102.0719
  iteration 2  objective 60.8549
  iteration 3  objective 41.3773
  iteration 4  objective 31.3043
  iteration 5  objective 27.7621
  iteration 6  objective 27.0896
  iteration 7  objective 27.0592
  iteration 8  objective 27.0592
same weights as sklearn: True True
first 4 test probabilities of 'benign': [0.996 0.    0.    1.   ]  labels: [1 0 0 1]
test accuracy ours 0.958  sklearn 0.958

Newton's method reaches the minimum (objective 27.0592) in seven iterations, each solving one 31×3131 \times 31 linear system, and the weights agree with scikit-learn's L-BFGS solver (run here with a tight tolerance so the comparison is fair). np.logaddexp(0, z) computes log⁡(1+ez)\log(1 + e^z) without overflow for large zz. Test accuracy on the 143 held-out tumours is 0.958. Most probabilities are close to 0 or 1: this data is nearly separable.

Nonlinear boundaries

The boundary of logistic regression is a hyperplane in feature space. Add polynomial features and it becomes a curve in the original space. In the lab, pick logistic regression on the moons and the circles data: the straight boundary cannot follow either shape. Lower CC to see the boundary tilt and soften as the weights shrink.

−2−1012−2−1012feature x₁feature x₂logistic on moonsC = 1z = 0.14 + 0.69x₁ − 2.39x₂class Aclass Bdecision boundaryTraining accuracy66/8082.5 %Test accuracy173/20086.5 %Test set: 200 new points

The same moons in code, with polynomial features of increasing degree and two strengths of regularisation, scored on a held-out half:

python · try it yourself
import numpy as np
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import log_loss

X, y = make_moons(n_samples=400, noise=0.25, random_state=0)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.5, random_state=0)
for degree in [1, 3, 9]:
    for C in [1.0, 1000.0]:
        m = make_pipeline(PolynomialFeatures(degree), StandardScaler(), LogisticRegression(C=C, max_iter=5000))
        m.fit(X_tr, y_tr)
        print(f"degree {degree}  C {C:6.0f}  train acc {m.score(X_tr, y_tr):.3f}  test acc {m.score(X_te, y_te):.3f}"
              f"  test log-loss {log_loss(y_te, m.predict_proba(X_te)):.3f}")
degree 1  C      1  train acc 0.880  test acc 0.885  test log-loss 0.320
degree 1  C   1000  train acc 0.875  test acc 0.875  test log-loss 0.323
degree 3  C      1  train acc 0.900  test acc 0.905  test log-loss 0.255
degree 3  C   1000  train acc 0.940  test acc 0.915  test log-loss 0.239
degree 9  C      1  train acc 0.935  test acc 0.905  test log-loss 0.234
degree 9  C   1000  train acc 0.935  test acc 0.920  test log-loss 0.277

Curved boundaries help (test accuracy 0.875 to 0.92). Accuracy alone hides a difference that the log-loss shows: degree 9 with almost no regularisation (C=1000C = 1000) has the best accuracy but a worse log-loss than with C=1C = 1, because its probabilities are overconfident. When probabilities matter, judge a classifier by log-loss (or calibration), not only by accuracy. The noise in the moons caps accuracy around 0.9 whatever the model.

Hyperparameters

Hyperparameter Meaning
C inverse regularisation strength (default 1.0); tune on a log grid
penalty "l2" (default), "l1" (feature selection, with solver="liblinear" or "saga"), "elasticnet", None
class_weight "balanced" reweights rare classes
solver, max_iter, tol numerical settings; raise max_iter if you see a convergence warning

Strengths, weaknesses, when to use it

Logistic regression trains fast, has a convex loss (one answer), outputs reasonably calibrated probabilities, and its coefficients read as odds ratios. It is limited to linear boundaries unless you engineer features, it needs scaled inputs for the penalty to be fair, and correlated features make individual coefficients unstable, as in linear regression. Use it as the first model and baseline for every classification problem, for scorecards and other settings where you must explain the model, and when you need probabilities rather than just labels.

Pitfalls

  • Treating 0.5 as the only threshold. If missing a positive costs ten times a false alarm, a lower threshold is better; the probability lets you choose.
  • Ignoring the default penalty. LogisticRegression() is ridge-penalised with C=1C = 1; coefficients are shrunk.
  • Calling exp on raw scores. eze^{z} overflows for z>709z > 709; use logaddexp or scipy.special.expit.

Practice

  1. A credit model has w=0.7w = 0.7 for "number of late payments" (unscaled). What happens to the odds of default with two more late payments?
Answer

The log-odds rise by 2⋅0.7=1.42 \cdot 0.7 = 1.4, so the odds are multiplied by e1.4≈4.06e^{1.4} \approx 4.06. The probability itself changes by an amount that depends on where it started.

  1. Show that σ′(z)=σ(z)(1−σ(z))\sigma'(z) = \sigma(z)(1 - \sigma(z)) and explain where it appears in the Hessian.
Answer

σ(z)=(1+e−z)−1\sigma(z) = (1 + e^{-z})^{-1}, so σ′(z)=e−z(1+e−z)−2=σ(z)⋅e−z1+e−z=σ(z)(1−σ(z))\sigma'(z) = e^{-z}(1 + e^{-z})^{-2} = \sigma(z) \cdot \frac{e^{-z}}{1 + e^{-z}} = \sigma(z)(1 - \sigma(z)). Differentiating the gradient ∑(pi−yi)xi\sum (p_i - y_i)\mathbf{x}_i once more gives ∑pi(1−pi)xixi⊤\sum p_i(1 - p_i) \mathbf{x}_i \mathbf{x}_i^\top, the diagonal matrix SS in X⊤SXX^\top S X.

Test yourself

What does logistic regression model as a linear function of the features?

  1. the probability pp
  2. the log-odds log⁡p1−p\log \frac{p}{1-p}
  3. the class label
  4. the squared error

In scikit-learn's LogisticRegression, making C smaller…

  1. weakens the regularisation
  2. strengthens the regularisation
  3. changes the solver
  4. raises the decision threshold

Why is the log-loss of logistic regression easy to minimise reliably?

  1. It has a closed-form minimum
  2. It is convex, so any local minimum is the global one
  3. It is linear
  4. It has no gradient

Two models have the same test accuracy, but one has a much larger test log-loss. What does that tell you?

  1. Nothing; accuracy is what counts
  2. Its probabilities are worse, typically overconfident on the examples it gets wrong
  3. It is underfitting
  4. It was trained on less data