Module contents
Lesson 6 of 24Core 110 min

Logistic and softmax regression

Build logistic regression as a probabilistic model of P(Y = 1 | x), derive logistic loss as Bernoulli negative log-likelihood and prove convexity. Train from scratch with gradient descent and Newton (IRLS, whose general GLM framework appears in m05), survey scalable solvers, study separable data and extend to multiple classes with softmax, the output layer of neural classifiers.

After this lesson you can

  • Derive logistic regression negative log-likelihood, its gradient Xᵀ(p - y) and Hessian XᵀWX.
  • Implement gradient descent and Newton (IRLS), comparing convergence and cost per iteration.
  • Choose between lbfgs, newton-cg, liblinear, sag and saga based on size, sparsity and penalty.
  • Explain why the MLE does not exist for linearly separable data and what regularization and gradient descent do in that case.
  • Generalize to K classes with softmax and reason about parameter identifiability.
  • Recognize logistic regression as a GLM and choose Poisson or Tweedie losses for predictive counts and costs.

Before you start

Motivation: probabilities, not labels

A bank does not just want to know whether a customer “will default”: it wants P(impago∣x)\Pr(\text{impago} \given \vb{x}), because the decision depends on that probability multiplied by the loss. Lending 10,000 euros with an 800-euro margin pays off if the default probability (with total loss) is below 800/10 800≈0.074800/10\,800 \approx 0.074, and the threshold changes with each amount. The same applies when deciding which transactions to block for fraud or which security alerts an analyst with time for a hundred a day reviews first: rank by probability, set a threshold according to the cost of each error (as you will in the lesson on cost-sensitive thresholds), and require that 0.3 really means “three out of ten.”

Linear regression on 0/1 labels is unsuitable: predictions leave [0,1][0, 1] as soon as x\vb{x} moves far enough, and a point far away on the correct side moves the line as much as a misclassified one. Logistic regression fixes both with a minimal idea: model the log odds, not the probability, linearly, and fit by Bernoulli maximum likelihood. The result is a convex model with closed-form gradient and Hessian, interpretable coefficients, and a probability as output. It has underpinned credit scoring for decades and, with KK classes, forms the final layer of classification networks and language models.

This lesson builds it all: the model and its interpretation, the loss and its convexity, two algorithms from scratch (gradient descent and Newton, here called IRLS), solvers used at scale, the pathological case of separable data, the multiclass softmax extension and, finally, GLMs from a prediction perspective: which loss to choose when the response is a count or a cost.

The model: linear log odds

For probability p∈(0,1)p \in (0, 1), the odds are p/(1−p)p/(1 - p) (0.8 gives odds of 4 to 1), and the logit function is their logarithm, logit⁡(p)=log⁡p1−p\operatorname{logit}(p) = \log\frac{p}{1 - p}, which ranges over all of R\R. Its inverse is the sigmoid (logistic function),

σ(z)=11+e−z=ez1+ez,logit⁡(σ(z))=z.\sigmoid(z) = \frac{1}{1 + e^{-z}} = \frac{e^z}{1 + e^z}, \qquad \operatorname{logit}(\sigmoid(z)) = z.

Three properties are used constantly: σ(−z)=1−σ(z)\sigmoid(-z) = 1 - \sigmoid(z); σ′(z)=σ(z)(1−σ(z))\sigmoid'(z) = \sigmoid(z)\big(1 - \sigmoid(z)\big), with maximum 1/41/4 at z=0z = 0; and log⁡σ(z)=−log⁡(1+e−z)\log\sigmoid(z) = -\log(1 + e^{-z}).

Geometrically, the model is a smooth step-shaped surface over the space of x\vb{x}. The boundary P(Y=1∣x)=0.5\Pr(Y = 1 \given \vb{x}) = 0.5 is the hyperplane w⊤x+b=0\vb{w}\T\vb{x} + b = 0; w\vb{w} points toward increasing probability, and its norm determines the steepness of the step: along w/∥w∥\vb{w}/\norm{\vb{w}}, the probability is σ(∥w∥ t+cte)\sigmoid(\norm{\vb{w}}\,t + \text{cte}), with maximum slope ∥w∥/4\norm{\vb{w}}/4 right at the boundary. The signed distance from x\vb{x} to the boundary is (w⊤x+b)/∥w∥(\vb{w}\T\vb{x} + b)/\norm{\vb{w}}: the logit is that distance multiplied by ∥w∥\norm{\vb{w}}.

InteractiveThe sigmoid above the plane
  • y=1y = 1
  • y=0y = 0
  • boundary p=0.5p = 0.5
  • ∣yi−pi∣\abs{y_i - p_i}
Mean loss along the ray s⋅(w,b)s\cdot(\vb{w}, b): s=1s = 1 is the current position
Data
Parameters
0.80
-0.60
0.40
Mean loss R^(w,b)\hat{R}(\vb{w}, b)0.6162
Possible minimum0.2237
Correct at threshold 0.527 / 40
∥w∥\norm{\vb{w}} and maximum slope ∥w∥/4\norm{\vb{w}}/41.00 and 0.25
Forty points from two classes, at height y∈{0,1}y \in \{0, 1\}, generated by an explicit model: equally probable classes and x∣y=k∼N(μk,I)\vb{x} \given y = k \sim \Normal(\vb{\mu}_k, \mat{I}) with μ1=(1,0.5)\vb{\mu}_1 = (1, 0.5) and μ0=(−1,−0.5)\vb{\mu}_0 = (-1, -0.5). Move w1w_1, w2w_2 and bb: the direction of w\vb{w} rotates the surface, its norm steepens it, and bb shifts it. Each vertical segment measures ∣yi−pi∣\abs{y_i - p_i}. The curve below is the loss along the ray s⋅(w,b)s\cdot(\vb{w}, b): press “Maximum likelihood” and check that its minimum is at s=1s = 1. Does the fit resemble the true posterior? Then switch to separable data and find a boundary separating every point: where is the curve's minimum now?

The data model in the figure is not arbitrary. If the two classes are Gaussian with the same covariance Σ\mat{\Sigma}, Bayes’ rule gives exactly a logistic function:

log⁡P(Y=1∣x)P(Y=0∣x)=log⁡π1 N(x;μ1,Σ)π0 N(x;μ0,Σ)=(μ1−μ0)⊤Σ−1x−12(μ1⊤Σ−1μ1−μ0⊤Σ−1μ0)+log⁡π1π0,\log\frac{\Pr(Y = 1 \given \vb{x})}{\Pr(Y = 0 \given \vb{x})} = \log\frac{\pi_1\,\Normal(\vb{x}; \vb{\mu}_1, \mat{\Sigma})}{\pi_0\,\Normal(\vb{x}; \vb{\mu}_0, \mat{\Sigma})} = (\vb{\mu}_1 - \vb{\mu}_0)\T\mat{\Sigma}\inv\vb{x} - \tfrac{1}{2}\big(\vb{\mu}_1\T\mat{\Sigma}\inv\vb{\mu}_1 - \vb{\mu}_0\T\mat{\Sigma}\inv\vb{\mu}_0\big) + \log\frac{\pi_1}{\pi_0},

because the quadratic terms x⊤Σ−1x\vb{x}\T\mat{\Sigma}\inv\vb{x} cancel. With the figure’s values, w=(2,1)\vb{w} = (2, 1) and b=0b = 0 (the “True posterior” button). The maximum likelihood fit to those 40 points points in a similar direction but has twice the norm, ∥w^∥=4.52\norm{\hat{\vb{w}}} = 4.52 versus 5≈2.24\sqrt{5} \approx 2.24: with so little data the estimator varies greatly, and in small samples the logistic MLE tends to exaggerate coefficients (Firth’s 1993 correction exists specifically to reduce that bias). The calculation generalizes: if both conditional densities belong to the same exponential family, p(x∣y=k)=h(x)exp⁡(ηk⊤T(x)−A(ηk))p(\vb{x} \given y = k) = h(\vb{x})\exp\big(\vb{\eta}_k\T T(\vb{x}) - A(\vb{\eta}_k)\big), the log odds are (η1−η0)⊤T(x)(\vb{\eta}_1 - \vb{\eta}_0)\T T(\vb{x}) plus a constant: linear in sufficient statistic T(x)T(\vb{x}), and in x\vb{x} when the nonlinear components of TT have the same natural parameter in both classes (like the xx⊤\vb{x}\vb{x}\T term for two Gaussians with equal covariance). The logistic function is shared by many generative models, and logistic regression fits it directly without modeling p(x∣y)p(\vb{x} \given y). This contrast between generative and discriminative models is the topic of lesson 11.

Coefficients as odds ratios

If variable xjx_j increases by one unit while the others stay fixed, log odds increase by wjw_j, so odds are multiplied by ewje^{w_j} regardless of the starting point. This is the usual interpretation in epidemiology and credit risk: a coefficient of 0.70.7 on a binary variable (smoker, customer with previous defaults) means odds are multiplied by e0.7≈2.01e^{0.7} \approx 2.01. Watch two things. First, odds are multiplied, not probability: moving from p=0.5p = 0.5 (odds 1) to odds 2 gives p=0.67p = 0.67, but starting at p=0.01p = 0.01 and doubling the odds gives p≈0.0198p \approx 0.0198. Second, “holding the others fixed” is a strong condition: if two variables are highly correlated, each coefficient measures an effect that almost never occurs in the data. The lab shows an extreme case.

Bernoulli likelihood and logistic loss

From here on we absorb the intercept: xi\vb{x}_i has a 1 as its first coordinate and w\vb{w} has bb as its first component (the design matrix X∈Rn×(d+1)\mat{X} \in \R^{n \times (d+1)} has a column of ones). When there is a penalty, bb is not penalized.

Each label is Bernoulli with probability pi=σ(zi)p_i = \sigmoid(z_i), zi=w⊤xiz_i = \vb{w}\T\vb{x}_i, and its probability mass is piyi(1−pi)1−yip_i^{y_i}(1 - p_i)^{1 - y_i}. For independent observations the negative log-likelihood is

L(w)=−∑i=1n[yilog⁡pi+(1−yi)log⁡(1−pi)]=∑i=1n[log⁡(1+ezi)−yizi].\Loss(\vb{w}) = -\sum_{i=1}^n \Big[y_i\log p_i + (1 - y_i)\log(1 - p_i)\Big] = \sum_{i=1}^n \Big[\log\big(1 + e^{z_i}\big) - y_i z_i\Big].

The second form follows from log⁡pi=zi−log⁡(1+ezi)\log p_i = z_i - \log(1 + e^{z_i}) and log⁡(1−pi)=−log⁡(1+ezi)\log(1 - p_i) = -\log(1 + e^{z_i}). This is logistic loss as Bernoulli negative log-likelihood, and its minimizer is the maximum likelihood estimator. It has three names depending on who is speaking:

  • Binary cross-entropy. The first bracket is the cross-entropy H⁡(qi,pi)\Ent(q_i, p_i) between the empirical distribution qi=(1−yi,yi)q_i = (1 - y_i, y_i) and the model’s. Minimizing it minimizes ∑iKL⁡(qi ∥ pi)\sum_i\KL(q_i \,\|\, p_i), because the entropy of qiq_i does not depend on w\vb{w}.
  • Logistic loss on the margin. With labels si=2yi−1∈{−1,+1}s_i = 2y_i - 1 \in \{-1, +1\}, each term is log⁡(1+e−sizi)\log(1 + e^{-s_i z_i}): a decreasing function of margin mi=sizim_i = s_i z_i familiar from classification losses. For very negative margins it grows like −mi-m_i, linearly rather than quadratically: a gross error matters, but does not dominate as in least squares.
  • Log-loss. The name in sklearn.metrics.log_loss, which uses it as a metric (mean rather than sum).

Why can fitted pip_i values be interpreted as probabilities? Because logistic loss is a proper scoring rule: at a point where P(Y=1∣x)=η\Pr(Y = 1 \given \vb{x}) = \eta, conditional risk ηlog⁡(1+e−f)+(1−η)log⁡(1+ef)\eta\log(1 + e^{-f}) + (1 - \eta)\log(1 + e^{f}) is minimized exactly at f=logit⁡(η)f = \operatorname{logit}(\eta) (you proved this in lesson 1: it is the functional elicited by the loss). With a sufficiently flexible model and enough data, the output converges to the true probability. A misspecified linear model need not do so; measuring how far off it is is the subject of calibration.

Gradient and Hessian

The derivative of each term with respect to its logit is simple:  ⁣d ⁣dz[log⁡(1+ez)−yz]=σ(z)−y\frac{\dd}{\dd z}\big[\log(1 + e^z) - yz\big] = \sigmoid(z) - y. By the chain rule:

L(w)=∑iℓi(zi),zi=w⊤xi\Loss(\vb{w}) = \sum_i \ell_i(z_i), \qquad z_i = \vb{w}\T\vb{x}_i
The loss depends on w only through the logits.
1/8

The gradient has the same form as in least squares, X⊤(y^−y)\mat{X}\T(\hat{\vb{y}} - \vb{y}): prediction minus label, projected onto the columns. This is no coincidence: it always happens when using the canonical link of an exponential family, and it happens again with softmax and Poisson. The Hessian, however, is no longer constant: each example has weight pi(1−pi)p_i(1 - p_i), large when the model is uncertain (pi≈0.5p_i \approx 0.5) and nearly zero when it is confident.

The first guided exercise proves this. Notice “at most”: strict convexity gives uniqueness, not existence. The function e−te^{-t} is strictly convex on R\R and has no minimum. We will see that exactly this happens to logistic loss when the data are separable.

Two quantitative consequences matter for optimization. Since p(1−p)≤1/4p(1 - p) \le 1/4, the Hessian of mean loss R^=L/n\hat{R} = \Loss/n is bounded by 14nX⊤X\frac{1}{4n}\mat{X}\T\mat{X}, so its gradient is Lipschitz with constant

L=λmax⁡(X⊤X)4n,L = \frac{\lambda_{\max}(\mat{X}\T\mat{X})}{4n},

and gradient descent with step 1/L1/L has the guarantee for smooth convex functions, R^(wt)−R^⋆≤L∥w0−w⋆∥2/(2t)\hat{R}(\vb{w}_t) - \hat{R}^\star \le L\norm{\vb{w}_0 - \vb{w}^\star}^2/(2t). But the loss is not strongly convex throughout Rd+1\R^{d+1}: far from the origin the pip_i saturate, W→0\mat{W} \to \mat{0}, and curvature tends to zero. If X\mat{X} has full rank, every bounded set has positive minimum curvature (the Hessian is continuous and positive definite), so near the optimum, if it exists, with μ\mu the Hessian’s smallest eigenvalue there, gradient descent converges linearly, with a factor of order 1−μ/L1 - \mu/L per iteration.

There is also a directly interpretable optimality condition. At the optimum, X⊤(p−y)=0\mat{X}\T(\vb{p} - \vb{y}) = \vb{0}. The component for the column of ones says ∑ipi=∑iyi\sum_i p_i = \sum_i y_i: with an intercept, mean fitted probability exactly matches the positive-class frequency in training. The others say residuals pi−yip_i - y_i are orthogonal to each feature.

Computing loss without overflow

The formula −ylog⁡σ(z)−(1−y)log⁡(1−σ(z))-y\log\sigmoid(z) - (1 - y)\log(1 - \sigmoid(z)) is correct on paper and disastrous in floating point. In float64, σ(z)\sigmoid(z) rounds to 1 once z≳37z \gtrsim 37, so log⁡(1−σ(z))=log⁡0=−∞\log(1 - \sigmoid(z)) = \log 0 = -\infty; and for z≲−709.8z \lesssim -709.8, e−ze^{-z} overflows, 1/(1+e−z)1/(1 + e^{-z}) is exactly 0 and log⁡σ(z)=−∞\log\sigmoid(z) = -\infty when the correct value is ≈z\approx z. The stable form is on the right of the definition: log⁡(1+ez)−yz\log(1 + e^z) - yz, computing log⁡(1+ez)\log(1 + e^z) as np.logaddexp(0, z), which uses the stable reformulation max⁡(z,0)+log⁡(1+e−∣z∣)\max(z, 0) + \log(1 + e^{-\abs{z}}).

[ ]Logistic loss without overflowBrowser
import numpy as np

z = np.array([-800.0, -40.0, 0.0, 40.0, 800.0])
with np.errstate(over="ignore", divide="ignore"):
    sig = 1 / (1 + np.exp(-z))
    ingenuo_1 = -np.log(sig)          # pérdida si y = 1
    ingenuo_0 = -np.log(1 - sig)      # pérdida si y = 0
estable_1 = np.logaddexp(0, z) - z    # log(1 + e^z) - y z con y = 1
estable_0 = np.logaddexp(0, z)        # con y = 0

print(f"{'z':>7} {'sigma(z)':>10} {'ingenua y=1':>12} {'estable y=1':>12} {'ingenua y=0':>12} {'estable y=0':>12}")
for fila in zip(z, sig, ingenuo_1, estable_1, ingenuo_0, estable_0):
    print(f"{fila[0]:7.0f} {fila[1]:10.3g} {fila[2]:12.6g} {fila[3]:12.6g} {fila[4]:12.6g} {fila[5]:12.6g}")

At z=40z = 40 with y=0y = 0 the naive formula gives infinity when the correct value is 4040, and at z=−800z = -800 with y=1y = 1 it gives infinity where it should give 800800. One such example turns the mean loss into inf and the gradient into nan. These are not exotic cases: they appear when a model becomes very confident, which is exactly what happens with separable data.

Optimization from scratch: gradient descent and Newton

Gradient descent

The iteration is wt+1=wt−η X⊤(pt−y)/n\vb{w}_{t+1} = \vb{w}_t - \eta\,\mat{X}\T(\vb{p}_t - \vb{y})/n. Each step costs two matrix-vector products, O(nd)\bigO(nd) operations (or O(nnz⁡(X))\bigO(\operatorname{nnz}(\mat{X})) if X\mat{X} is sparse), and memory is that of the data. The cost is the number of steps: near the optimum, error decreases by a factor ≈1−μ/L\approx 1 - \mu/L per iteration. The ratio L/μL/\mu is an effective condition number (at least as large as that of the Hessian at the optimum, because LL bounds curvature everywhere) and worsens with differently scaled or highly correlated variables. This is why we standardize.

Newton is iteratively reweighted least squares

Newton’s method uses the Hessian: wt+1=wt−(X⊤WtX)−1X⊤(pt−y)\vb{w}_{t+1} = \vb{w}_t - (\mat{X}\T\mat{W}_t\mat{X})\inv\mat{X}\T(\vb{p}_t - \vb{y}). Rearranging,

wt+1=(X⊤WtX)−1X⊤Wt zt,zt=Xwt+Wt−1(y−pt).\vb{w}_{t+1} = (\mat{X}\T\mat{W}_t\mat{X})\inv\mat{X}\T\mat{W}_t\,\vb{z}_t, \qquad \vb{z}_t = \mat{X}\vb{w}_t + \mat{W}_t\inv(\vb{y} - \vb{p}_t).

Check by multiplying: X⊤Wtzt=X⊤WtXwt+X⊤(y−pt)\mat{X}\T\mat{W}_t\vb{z}_t = \mat{X}\T\mat{W}_t\mat{X}\vb{w}_t + \mat{X}\T(\vb{y} - \vb{p}_t). Each Newton step is a weighted least-squares regression of a working response zt\vb{z}_t (the current logit plus a linearized correction) with weights pi(1−pi)p_i(1 - p_i). This is why it is called IRLS (iteratively reweighted least squares). In a general GLM, the analogous step uses expected Fisher information (Fisher scoring); with the canonical link, expected and observed information coincide and IRLS is exactly Newton.

Cost per iterationMemoryConvergence
GradientO(nd)\bigO(nd)O(d)\bigO(d) beyond the datalinear near the optimum, factor ≈1−μ/L\approx 1 - \mu/L
Newton / IRLSO(nd2+d3)\bigO(nd^2 + d^3)O(d2)\bigO(d^2)quadratic near the optimum
SGD (one example)O(d)\bigO(d)O(d)\bigO(d)sublinear, limited by gradient noise

Quadratic convergence is local: it requires a positive definite, Lipschitz Hessian near the optimum, and logistic regression satisfies both if an optimum exists and X\mat{X} has full rank. Far from the optimum there is no guarantee: if initial logits are large, Wt≈0\mat{W}_t \approx \mat{0}, the Hessian is nearly singular and the step may shoot off. Practical implementations damp the step with a line search or trust region. From w0=0\vb{w}_0 = \vb{0}, where all pi=0.5p_i = 0.5 and weights are maximal, pure Newton often works well.

InteractiveNewton versus gradient descent
  • gradient descent
  • Newton
  • SGD (per epoch)
  • gradient descent, η=1/L\eta = 1/L
  • Newton (IRLS) with line search
  • SGD, one sample per step
  • optimum θ^\hat\theta (hollow circle); draggable θ0\theta_0
k = 20,000
Iteration kk20,000
f−f⋆f - f^\star: gradient descent7.5e−12
f−f⋆f - f^\star: Newton< 1e−14
f−f⋆f - f^\star: SGD (epochs)1.4e−1
Iterations to 10−610^{-6} (gradient and Newton)9,381 and 4
Hessian κ\kappa at the optimum978
Contours of mean loss f(b,w)f(b, w) for one-variable logistic regression, σ(b+wx)\sigma(b + wx), in parameter space. Data come from an explicit model: n=50n = 50, xi=5+1.3 εix_i = 5 + 1.3\,\varepsilon_i with εi∼N(0,1)\varepsilon_i \sim \Normal(0, 1) and yi∼Bern⁡(σ(−7.5+1.5xi))y_i \sim \Bern(\sigma(-7.5 + 1.5x_i)). Play the iterations (the right axis is logarithmic, up to k=20 000k = 20\,000): gradient descent with step 1/L1/L (blue) struggles along the elongated valley, Newton (magenta) arrives in a few steps, and SGD (yellow, one sample per step, plotted once per epoch of nn steps) barely moves. At right, f−f⋆f - f^\star on a logarithmic scale: Newton's curve falls almost vertically at the end, the signature of quadratic convergence. Standardize xx: what happens to contours, κ\kappa, gradient descent and SGD? Drag the starting point far away and turn off Newton's line search.

With uncentered xx (xˉ≈5\bar{x} \approx 5), the design matrix columns 1\vb{1} and x\vb{x} are almost parallel: increasing bb while reducing ww barely changes predictions. The Hessian at the optimum has a condition number near a thousand and the valley is narrow and long. Gradient descent takes over nine thousand iterations to get below 10−610^{-6}, while Newton, which corrects the geometry by multiplying by the inverse Hessian, takes four. SGD suffers similarly and its step, which starts here at η0=1/max⁡i(∥xi∥2/4)\eta_0 = 1/\max_i(\norm{\vb{x}_i}^2/4) to keep any example from destabilizing it and decreases as 1/t1/t, is smaller still: in twenty thousand epochs it barely leaves the starting point. After standardization, the condition number falls to 2, the valley becomes nearly round and gradient descent needs 17 iterations; SGD approaches quickly and then oscillates forward at the rate allowed by the noise of using one example at a time. Newton does not change: it is invariant to linear reparameterizations, unlike gradient descent (in exact arithmetic standardization changes nothing for Newton; in floating point it helps condition the Hessian when solving the system).

Lab: logistic regression from scratch

The scikit-learn breast_cancer dataset has 569 tumors with 30 measurements of cell nuclei and label 1 for benign. We start with the ten means (“mean radius,” “mean texture,” and so on), standardized. First, loss, gradient and Hessian, checking that the analytical gradient agrees with centered finite differences.

[ ]Loss, gradient and Hessian with numerical checkBrowser
import numpy as np
from scipy.special import expit            # sigmoide estable
from sklearn.datasets import load_breast_cancer

datos = load_breast_cancer()
nombres = list(datos.feature_names[:10])   # las diez medias
X = datos.data[:, :10]
y = datos.target.astype(float)              # 1 = benigno
X = (X - X.mean(axis=0)) / X.std(axis=0)
A = np.column_stack([np.ones(len(y)), X])   # columna de unos para b
n, p = A.shape

def perdida(w, A, y):
    z = A @ w
    return np.mean(np.logaddexp(0, z) - y * z)

def gradiente(w, A, y):
    return A.T @ (expit(A @ w) - y) / len(y)

def hessiana(w, A, y):
    q = expit(A @ w)
    return (A * (q * (1 - q))[:, None]).T @ A / len(y)

rng = np.random.default_rng(0)
w = rng.normal(scale=0.5, size=p)
h = 1e-6
g_fd = np.array([(perdida(w + h * e, A, y) - perdida(w - h * e, A, y)) / (2 * h) for e in np.eye(p)])
g = gradiente(w, A, y)
print(f"gradiente: error relativo frente a diferencias finitas = {np.linalg.norm(g - g_fd) / np.linalg.norm(g):.1e}")

H = hessiana(w, A, y)
H_fd = np.array([(gradiente(w + h * e, A, y) - gradiente(w - h * e, A, y)) / (2 * h) for e in np.eye(p)])
print(f"hessiana:  error relativo frente a diferencias finitas = {np.linalg.norm(H - H_fd) / np.linalg.norm(H):.1e}")
print(f"autovalor mínimo de la hessiana en ese punto: {np.linalg.eigvalsh(H)[0]:.2e} (> 0)")

Now the two algorithms: IRLS from w=0\vb{w} = \vb{0} until the gradient is on the order of rounding error, and gradient descent with step 1/L1/L for ten thousand iterations, measuring the remaining gap.

[ ]Gradient descent versus IRLS on breast_cancerBrowser
from sklearn.linear_model import LogisticRegression

w = np.zeros(p)
print(" it   pérdida media        ‖gradiente‖")
for it in range(1, 30):
    w = w - np.linalg.solve(hessiana(w, A, y), gradiente(w, A, y))
    ng = np.linalg.norm(gradiente(w, A, y))
    print(f"{it:3d}   {perdida(w, A, y):.15f}   {ng:.2e}")
    if ng < 1e-12:
        break
w_irls, f_opt = w, perdida(w, A, y)

L = np.linalg.eigvalsh(A.T @ A / n)[-1] / 4
mu = np.linalg.eigvalsh(hessiana(w_irls, A, y))[0]
print(f"\nL = {L:.3f}   curvatura mínima en el óptimo mu = {mu:.2e}   L/mu = {L / mu:.2e}")

w = np.zeros(p)
for t in range(1, 10001):
    w = w - gradiente(w, A, y) / L
    if t in (10, 100, 1000, 10000):
        print(f"gradiente, t = {t:5d}: f - f* = {perdida(w, A, y) - f_opt:.2e}   max|w - w*| = {np.abs(w - w_irls).max():.2f}")

for solver in ["lbfgs", "newton-cholesky"]:
    m = LogisticRegression(C=np.inf, solver=solver, tol=1e-10, max_iter=10_000).fit(X, y)
    w_sk = np.r_[m.intercept_, m.coef_.ravel()]
    print(f"scikit-learn {solver:15s}: {int(m.n_iter_[0]):3d} iteraciones, max|w - w_IRLS| = {np.abs(w_sk - w_irls).max():.1e}")

q = expit(A @ w_irls)
print(f"\nsuma de p_i = {q.sum():.6f}   suma de y_i = {y.sum():.0f}")
print("coeficientes:", {k: round(v, 2) for k, v in zip(["b"] + nombres, w_irls)})
print("correlaciones entre radio, perímetro y área:\n", np.corrcoef(datos.data[:, [0, 2, 3]].T).round(4))

The results deserve a careful look.

  • IRLS converges in 9 iterations, with quadratic convergence visible in the last three: gradient norm goes from 4.2×10−54.2\times 10^{-5} to 8.6×10−88.6\times 10^{-8} and then 3.5×10−133.5\times 10^{-13}, that is, ∥gk+1∥≈48 ∥gk∥2\norm{\vb{g}_{k+1}} \approx 48\,\norm{\vb{g}_k}^2. The number of correct digits doubles each step.
  • Gradient descent remains far off after ten thousand iterations: f−f⋆=2.4×10−3f - f^\star = 2.4\times 10^{-3} and one coefficient differs from its optimum by nearly 10 units. The middle line explains why: L/μ≈2.4×105L/\mu \approx 2.4\times 10^{5}, so the local contraction factor is 1−4×10−61 - 4\times 10^{-6} per step. It would need on the order of millions of iterations.
  • Three columns are responsible. Mean radius, perimeter and area have correlations from 0.9870.987 to 0.9980.998 (perimeter is nearly proportional to radius and area to its square). The Hessian is nearly singular along the direction changing all three without changing predictions.
  • Therefore coefficients cannot be read as importances. Radius has coefficient +7.22+7.22 and area −13.99-13.99, opposite signs although both measure the same thing, and both huge compared with the rest. The model uses a combination of the three; individual coefficients are poorly determined (their variance is large, as inference for generalized linear models quantifies) and change greatly with any perturbation of the data.
  • scikit-learn agrees: with newton-cholesky, within 1.5×10−131.5\times 10^{-13} in 9 iterations (it is Newton, like ours); with lbfgs, within 4.5×10−54.5\times 10^{-5} in 87 iterations because its stopping criterion is looser. And the sum of pip_i is exactly the number of benign cases, 357, as the optimality condition predicts.

C=np.inf requests “no penalty” since scikit-learn 1.8; the old form, penalty=None, is deprecated and will disappear in 1.10.

Solvers at scale

With n=569n = 569 and d=11d = 11 the algorithm hardly matters. With n=107n = 10^7 rows or d=105d = 10^5 sparse variables, it does. LogisticRegression offers six logistic regression solvers, each with a different trade-off among cost per iteration, iteration count, memory and penalty type.

  • lbfgs (the default since version 0.22). L-BFGS (Liu and Nocedal, 1989) approximates the inverse Hessian using the last mm pairs of iterate and gradient differences (10 in SciPy), so each iteration costs one gradient, O(nnz⁡(X))\bigO(\operatorname{nnz}(\mat{X})), plus O(md)\bigO(md), and stores no d×dd \times d matrix. It converges in a few dozen iterations on well-conditioned problems. It requires a differentiable loss: L2 or no penalty.
  • newton-cg: inexact Newton. It solves Hs=−g\mat{H}\vb{s} = -\vb{g} by conjugate gradients using only Hessian-vector products, X⊤(W(Xv))\mat{X}\T\big(\mat{W}(\mat{X}\vb{v})\big), each costing O(nnz⁡(X))\bigO(\operatorname{nnz}(\mat{X})). Few outer iterations, without forming H\mat{H}. L2 or no penalty.
  • newton-cholesky: exact Newton. It forms X⊤WX\mat{X}\T\mat{W}\mat{X} (O(nd2)\bigO(nd^2)) and factorizes it (O(d3)\bigO(d^3)). This is what you implemented. Ideal with n≫dn \gg d; memory is prohibitive for large dd because it stores a dense d×dd \times d matrix.
  • liblinear: the C++ library LIBLINEAR (Fan et al., 2008), designed for large sparse linear problems. For logistic regression with L2 it uses trust-region Newton; for L1, coordinate descent (the idea of lasso coordinate descent, adapted to logistic loss). Two peculiarities: it only performs binary classification (for multiple classes wrap it in OneVsRestClassifier) and penalizes the intercept, treating it as another variable with value intercept_scaling.
  • sag and saga: incremental methods. SAG (Schmidt, Le Roux and Bach) stores the last gradient computed for each example and steps using their mean; in a linear model one scalar per example suffices. Each step costs O(d)\bigO(d) (or the size of a sparse row), like SGD, but converges linearly on strongly convex problems, like full gradient descent. SAGA (Defazio, Bach and Lacoste-Julien, 2014) is a variant supporting a proximal operator and therefore L1 and elastic net; it also converges without strong convexity. Both converge fast only if features have similar scales: standardize first.
solverpenalties (l1_ratio)multinomial multiclassdominant costwhen
lbfgsL2 or noneyesone gradient per iterationdefault, moderate dense and sparse data
newton-cgL2 or noneyesHessian-vector productslarge dd, high accuracy
newton-choleskyL2 or noneyesnd2+d3nd^2 + d^3n≫dn \gg d, one-hot categorical variables with rare levels
liblinearL1 or L2no (binary only)trust-region Newton or coordinatessmall or sparse data, binary L1
sagL2 or noneyesO(d)\bigO(d) per examplevery large nn, scaled features
sagaL1, L2, elastic net or noneyesO(d)\bigO(d) per examplevery large nn, sparse data, L1 or elastic net

The table summarizes the one in the LogisticRegression documentation. The lab measures all six on growing dense datasets and a sparse matrix with L2 and L1. The objective compared is the one minimized by scikit-learn, C∑iℓi+12∥w∥22C\sum_i \ell_i + \frac{1}{2}\norm{\vb{w}}_2^2 (or +∥w∥1+\norm{\vb{w}}_1 with L1), excluding the intercept from the penalty; the “obj” column is relative distance to the best value found. For sag and saga, iterations are epochs: complete passes through the data.

[ ]Solver comparison: dense dataBrowser
import time, warnings
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.exceptions import ConvergenceWarning
warnings.simplefilter("ignore", ConvergenceWarning)

def objetivo(m, X, y, C, l1):
    w = m.coef_.ravel()
    z = X @ w + m.intercept_[0]
    perdida = np.sum(np.logaddexp(0, z) - y * z)
    return C * perdida + (np.abs(w).sum() if l1 else 0.5 * w @ w)

def banco(X, y, C, solvers, l1=False):
    filas = []
    for s in solvers:
        m = LogisticRegression(C=C, l1_ratio=1.0 if l1 else 0.0, solver=s, max_iter=1000, tol=1e-4)
        t0 = time.perf_counter()
        m.fit(X, y)
        filas.append((s, time.perf_counter() - t0, int(np.max(m.n_iter_)), objetivo(m, X, y, C, l1), np.mean(m.coef_ == 0)))
    mejor = min(f[3] for f in filas)
    for s, dt, it, obj, ceros in filas:
        print(f"  {s:16s} {1000 * dt:8.1f} ms   iter {it:4d}   obj {(obj - mejor) / mejor:8.1e}   coef. nulos {ceros:.2f}")

for n in [1000, 10000]:
    X, y = make_classification(n_samples=n, n_features=50, n_informative=10, random_state=0)
    X = (X - X.mean(axis=0)) / X.std(axis=0)
    print(f"denso, n = {n}, d = 50, L2 con C = 1")
    banco(X, y, 1.0, ["lbfgs", "newton-cg", "newton-cholesky", "liblinear", "sag", "saga"])
[ ]Solver comparison: sparse data with L2 and L1Browser
import scipy.sparse as sp

rng = np.random.default_rng(0)
n, d = 4000, 4000
X = sp.random(n, d, density=0.005, format="csr", random_state=1, data_rvs=lambda k: np.ones(k))
w_real = np.zeros(d)
w_real[rng.choice(d, 100, replace=False)] = rng.normal(0, 2, 100)
z = X @ w_real
y = (rng.uniform(size=n) < 1 / (1 + np.exp(-(z - z.mean())))).astype(int)
print(f"disperso: n = {n}, d = {d}, {X.nnz / n:.0f} no nulos por fila ({100 * X.nnz / (n * d):.1f} %), 100 coeficientes reales no nulos")
print("L2 con C = 0.3")
banco(X, y, 0.3, ["lbfgs", "newton-cg", "liblinear", "sag", "saga"])
print("L1 con C = 0.3")
banco(X, y, 0.3, ["liblinear", "saga"], l1=True)
print(f"memoria que necesitaría newton-cholesky para la hessiana: {d * d * 8 / 2**20:.0f} MiB (frente a {X.data.nbytes / 2**20:.2f} MiB de datos)")

The times shown are from the browser (Python compiled to WebAssembly, without BLAS and single-threaded), so trends matter rather than milliseconds. The patterns that hold:

  • Second-order methods need very few iterations (4 or 5 for newton-cg, newton-cholesky and liblinear), but each is expensive. lbfgs, with somewhat more cheap iterations, is fastest or close to it on dense data: this is why it is the default.
  • newton-cholesky pays its nd2nd^2 cost: at n=10 000n = 10\,000 it is several times slower than lbfgs despite needing half as many iterations, because forming X⊤WX\mat{X}\T\mat{W}\mat{X} without BLAS is expensive. With BLAS that product is much more efficient and the difference shrinks.
  • sag and saga need between 19 and 40 epochs and at these sizes do not beat lbfgs; on dense data, sag is the slowest of all. Their advantage is asymptotic: for a strongly convex problem they need on the order of (n+Lmax⁡/μ)log⁡(1/ε)(n + L_{\max}/\mu)\log(1/\eps) single-example gradients (with Lmax⁡L_{\max} the worst-example smoothness constant), versus n (L/μ)log⁡(1/ε)n\,(L/\mu)\log(1/\eps) for full gradient descent. In epochs, 1+Lmax⁡/(nμ)1 + L_{\max}/(n\mu) versus L/μL/\mu: larger nn means fewer epochs, and epoch count stops depending on conditioning when n≳Lmax⁡/μn \gtrsim L_{\max}/\mu. With n=1000n = 1000 or 10 00010\,000 and a well-conditioned problem, this regime does not arrive.
  • All reach the same optimum, apart from relative differences from 10−1010^{-10} to 10−310^{-3} reflecting different stopping criteria with the same tol, not method quality. If the last digits matter, lower tol and compare.
  • With L1 only liblinear and saga remain, and both give the same sparse model (about 90% of coefficients exactly zero). liblinear is much faster at this size; saga scales to millions of rows and alone supports elastic net and multinomial with L1. newton-cholesky is not even a reasonable choice here: its Hessian would occupy 122 MiB versus 0.6 MiB of data.

Separable data: when the maximum does not exist

If a line (hyperplane) perfectly separates the two classes, unpenalized logistic regression has no solution. The reason fits in one line: if siwˉ⊤xi>0s_i\bar{\vb{w}}\T\vb{x}_i > 0 for every ii, loss along the ray twˉt\bar{\vb{w}} is ∑ilog⁡(1+e−t siwˉ⊤xi)\sum_i\log(1 + e^{-t\,s_i\bar{\vb{w}}\T\vb{x}_i}), which tends to 0 as t→∞t \to \infty; and loss is strictly positive at every finite w\vb{w}. This is what you saw in the first figure’s ray curve with separable data.

You will prove this in a guided exercise. The full result is due to Albert and Anderson (1984): the MLE exists (and, with full-rank X\mat{X}, is unique) if and only if the data overlap, meaning there is neither complete nor quasi-complete separation, where a hyperplane leaves each class in a closed half-space with some points exactly on it. In practice this is the case of separable data and logistic MLE divergence, and it is much more frequent than it seems: with dd on the order of nn, generic data are often separable (in Rd\R^d, n≤d+1n \le d + 1 points in general position are separable with any labeling, and by Cover’s 1965 theorem, with random labels the probability is still 1/21/2 when n=2(d+1)n = 2(d + 1)); a categorical level whose examples all belong to the same class produces quasi-complete separation.

What does gradient descent do then? It never stops, but it does something very specific. Soudry, Hoffer, Nacson, Gunasekar and Srebro (2018) described it for the homogeneous model (without a separate intercept, or with it as another coordinate): with separable data, any starting point and step η<2β−1σmax⁡−2(X)\eta < 2\beta\inv\sigma_{\max}^{-2}(\mat{X}), where β\beta is the smoothness constant of one-example loss (1/41/4 for logistic loss) and the loss is summed rather than averaged, the iterates satisfy

w(t)=w^ln⁡t+ρ(t),w^=arg min⁡w∥w∥2  s.a.  siw⊤xi≥1 ∀i,\vb{w}(t) = \hat{\vb{w}}\ln t + \vb{\rho}(t), \qquad \hat{\vb{w}} = \argmin_{\vb{w}} \norm{\vb{w}}^2 \ \text{ s.a. } \ s_i\vb{w}\T\vb{x}_i \ge 1 \ \forall i,

with bounded ρ(t)\vb{\rho}(t). The vector w^\hat{\vb{w}} solves the maximum-margin SVM (hard margin), whose geometric margin is γ=1/∥w^∥\gamma = 1/\norm{\hat{\vb{w}}}. Three consequences: the norm grows like ∥w^∥ln⁡t\norm{\hat{\vb{w}}}\ln t without bound; the loss tends to zero as 1/t1/t; and the direction converges to maximum margin, but very slowly: ∥w(t)/∥w(t)∥−w^/∥w^∥∥=O(1/ln⁡t)\big\lVert\vb{w}(t)/\norm{\vb{w}(t)} - \hat{\vb{w}}/\norm{\hat{\vb{w}}}\big\rVert = \bigO(1/\ln t) for almost all datasets (their Theorem 5; in degenerate cases, O(ln⁡ln⁡t/ln⁡t)\bigO(\ln\ln t/\ln t)). Nobody asked gradient descent to maximize the margin: this is an implicit bias of the algorithm, and the authors stress that it is specific to gradient descent; other optimizers, such as Adam, have different biases.

InteractiveSeparable data: the norm of w goes to infinity
  • unpenalized
  • ‖ŵ‖ ln t
  • class +1+1
  • class −1-1
  • boundary of wt\vb{w}_t
  • maximum margin w^\hat{\vb{w}} and its margins
t = 100,000
0.0020
Iteration tt100,000
∥wt∥\norm{\vb{w}_t}14.13
Angle between wt\vb{w}_t and w^\hat{\vb{w}}2.54°
Mean loss2.7e−5
Margin of wt\vb{w}_t and maximum γ\gamma0.567 and 0.591
Δ∥w∥/Δln⁡t\Delta\norm{\vb{w}}/\Delta\ln t and ∥w^∥=1/γ\norm{\hat{\vb{w}}} = 1/\gamma1.56 and 1.69
Without a penalty loss approaches 0 without reaching it: ∥wt∥\norm{\vb{w}_t} grows like ∥w^∥ln⁡t\norm{\hat{\vb{w}}}\ln t and direction approaches w^\hat{\vb{w}} with error O(1/ln⁡t)O(1/\ln t).
Twenty points separable by a line through the origin, and gradient descent on mean logistic loss without an intercept, with step 1/L1/L from w=0\vb{w} = \vb{0}. Time advances logarithmically to t=105t = 10^5. Top right, ∥wt∥\norm{\vb{w}_t} versus tt: with a logarithmic axis, the curve approaches a line with slope ∥w^∥\norm{\hat{\vb{w}}}, parallel to the dashed ∥w^∥ln⁡t\norm{\hat{\vb{w}}}\ln t (their separation remains bounded by the theorem's ρ(t)\vb{\rho}(t) term). Below, the angle to the maximum-margin direction, drawn in gray with both margins: it falls, but each decade of iterations gains less. Compare measured slope with 1/γ1/\gamma in the readouts. Enable L2 penalty: what happens to the norm? And to the angle with w^\hat{\vb{w}} as you raise λ\lambda?

Penalization changes the problem. With λ2∥w∥2\frac{\lambda}{2}\norm{\vb{w}}^2 the homogeneous model’s objective is strongly convex and coercive, so it has a unique finite minimizer for any dataset (with an unpenalized intercept, examples of both classes suffice): separable or not, the norm stabilizes (the green curve flattens in the figure). That minimizer does not point exactly toward maximum margin, but Rosset, Zhu and Hastie (NIPS 2003) showed that as λ→0\lambda \to 0, the normalized solution of logistic regression penalized by the ℓp\ell_p norm converges to the maximum-margin separator measured in the ℓp\ell_p norm: the maximum-margin SVM with L2 and, with L1, the maximum ℓ1\ell_1 margin separator, which tends to be sparse. Regularization and unregularized gradient descent end up in the same place by different paths: one explicit, the other implicit.

In the lab

First, the figure’s twenty points: the maximum-margin vector w^\hat{\vb{w}} using a constrained optimizer, and twenty thousand iterations of the same gradient descent.

[ ]Separable data: gradient descent and maximum marginBrowser
import numpy as np
from scipy.optimize import minimize

Xs = np.array([[2.09, 2.25], [-0.7, -0.07], [-2.58, -1.41], [-0.87, -0.84], [-0.5, 0.61], [1.5, 2.4], [-1.3, -1.92],
               [2.26, 2.22], [-1.6, -1.8], [0.89, 0.33], [-1.36, -1.03], [0.93, -0.54], [1.37, 1.52], [0.79, 1.18],
               [0.76, -0.74], [1.43, 2.71], [-2.31, 0.19], [-1.17, -0.52], [1.39, 2.05], [1.84, 1.65]])
s = np.array([1, -1, -1, -1, -1, 1, -1, 1, -1, 1, -1, 1, 1, 1, 1, 1, -1, -1, 1, 1])
Z = s[:, None] * Xs                         # filas s_i x_i: margen de w en el ejemplo i = (Z w)_i
n = len(s)

# SVM de margen duro homogéneo: min ||w||^2  s.a.  Z w >= 1
res = minimize(lambda w: w @ w, x0=np.ones(2), jac=lambda w: 2 * w, method="SLSQP",
               constraints=[{"type": "ineq", "fun": lambda w: Z @ w - 1, "jac": lambda w: Z}], options={"ftol": 1e-15})
w_hat = res.x
print(f"w_hat = {np.round(w_hat, 4)}   ||w_hat|| = {np.linalg.norm(w_hat):.4f}   margen gamma = {1 / np.linalg.norm(w_hat):.4f}")
print("vectores soporte (margen 1):", np.where(np.abs(Z @ w_hat - 1) < 1e-6)[0])

L = np.linalg.eigvalsh(Xs.T @ Xs / n)[-1] / 4
w = np.zeros(2)
angulo = lambda u, v: np.degrees(np.arccos(np.clip(u @ v / np.linalg.norm(u) / np.linalg.norm(v), -1, 1)))
normas = {}
print("\n      t    ||w_t||   ||w_t||/ln t   ángulo con w_hat   margen de w_t   pérdida media")
for t in range(1, 20001):
    m = Z @ w
    w = w + (Z.T @ np.exp(-np.logaddexp(0, m))) / n / L     # exp(-logaddexp(0, m)) = sigma(-m)
    if t in (1, 10, 100, 1000, 10000, 20000):
        nw = np.linalg.norm(w)
        normas[t] = nw
        print(f"{t:7d}   {nw:7.3f}   {nw / np.log(t) if t > 1 else np.nan:10.3f}   {angulo(w, w_hat):12.2f}°   {(Z @ w).min() / nw:12.4f}   {np.mean(np.logaddexp(0, -Z @ w)):.2e}")
print(f"\npendiente medida entre t = 10^4 y 2·10^4: {(normas[20000] - normas[10000]) / np.log(2):.3f}   (||w_hat|| = {np.linalg.norm(w_hat):.3f})")

The maximum margin is γ=0.591\gamma = 0.591, with ∥w^∥=1.692\norm{\hat{\vb{w}}} = 1.692 and two support vectors. Gradient descent starts 47° from w^\hat{\vb{w}} (its first step is the mean of sixis_i\vb{x}_i, pointing toward each class’s mass rather than the gap between them) and the angle drops to about 14° at t=100t = 100, 6.6° at t=1000t = 1000 and 3.8° at t=104t = 10^4: each decade gained costs ten times as many iterations, the signature of O(1/ln⁡t)\bigO(1/\ln t). The measured slope of ∥wt∥\norm{\vb{w}_t} against ln⁡t\ln t approaches ∥w^∥\norm{\hat{\vb{w}}} from below, and the classifier’s margin rises toward γ\gamma while mean loss is already on the order of 10−410^{-4}. Had you stopped as soon as the loss “stopped falling,” you would have kept a classifier with a substantially worse margin.

Now a real case. Remember that the previous lab used only ten breast_cancer variables? With all thirty, the data are separable. A linear feasibility problem certifies this: find (w,b)(\vb{w}, b) with si(w⊤xi+b)≥1s_i(\vb{w}\T\vb{x}_i + b) \ge 1 for every ii.

[ ]breast_cancer with all 30 features: separableBrowser
from scipy.optimize import linprog
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
import warnings
from sklearn.exceptions import ConvergenceWarning

X30, y30 = load_breast_cancer(return_X_y=True)
X30 = (X30 - X30.mean(axis=0)) / X30.std(axis=0)
s30 = 2 * y30 - 1
A30 = np.column_stack([X30, np.ones(len(y30))])
lp = linprog(np.zeros(A30.shape[1]), A_ub=-(s30[:, None] * A30), b_ub=-np.ones(len(y30)),
             bounds=[(None, None)] * A30.shape[1], method="highs")
print("¿existe (w, b) con s_i (w·x_i + b) >= 1 para todo i?", lp.status == 0)

with warnings.catch_warnings():
    warnings.simplefilter("ignore", ConvergenceWarning)
    for max_iter in [100, 1000, 10000]:
        m = LogisticRegression(C=np.inf, max_iter=max_iter).fit(X30, y30)
        z = m.decision_function(X30)
        pr = m.predict_proba(X30)[:, 1]
        print(f"sin penalizar, max_iter = {max_iter:5d}: {int(m.n_iter_[0]):5d} iteraciones   ||w|| = {np.linalg.norm(m.coef_):9.1f}"
              f"   pérdida media = {np.mean(np.logaddexp(0, -s30 * z)):.1e}   p fuera de [0.01, 0.99]: {np.mean((pr < 0.01) | (pr > 0.99)):.0%}   exactitud: {m.score(X30, y30):.3f}")
for C in [1.0, 100.0]:
    m = LogisticRegression(C=C, max_iter=10000).fit(X30, y30)
    pr = m.predict_proba(X30)[:, 1]
    print(f"L2 con C = {C:5.0f}: {int(m.n_iter_[0]):3d} iteraciones   ||w|| = {np.linalg.norm(m.coef_):6.2f}"
          f"   p fuera de [0.01, 0.99]: {np.mean((pr < 0.01) | (pr > 0.99)):.0%}")

The unpenalized answer is determined by the optimizer, not the data. With max_iter=100, lbfgs stops at the limit with ∥w∥=68.5\norm{\vb{w}} = 68.5; with more room it stops by its own criterion at iteration 305, with ∥w∥=440.7\norm{\vb{w}} = 440.7, mean loss 1.5×10−21.5\times 10^{-2} and accuracy 0.9930.993: it has not even found one of the separators just certified by the linear problem. Neither model is “the” MLE, which does not exist, and their probabilities are extreme (95% outside [0.01,0.99][0.01, 0.99]). With the default penalty (C=1C = 1), the problem has a unique solution, with ∥w∥=3.84\norm{\vb{w}} = 3.84, reached in 19 iterations and independent of max_iter. This is why scikit-learn regularizes by default.

Multiple classes: softmax regression

With KK classes, y∈{1,…,K}y \in \{1, \dots, K\}, each class gets its own linear function, zk=wk⊤x+bkz_k = \vb{w}_k\T\vb{x} + b_k (the logits), which are converted to probabilities by softmax.

With K=2K = 2 this is ordinary logistic regression: softmax⁡(z)1=1/(1+e−(z1−z2))=σ((w1−w2)⊤x+b1−b2)\softmax(\vb{z})_1 = 1/(1 + e^{-(z_1 - z_2)}) = \sigmoid\big((\vb{w}_1 - \vb{w}_2)\T\vb{x} + b_1 - b_2\big). This reveals the model’s central feature: only differences matter. Add the same vector c\vb{c} to every wk\vb{w}_k and the same constant c0c_0 to every bkb_k, and each logit increases by c⊤x+c0\vb{c}\T\vb{x} + c_0; the factor ec⊤x+c0e^{\vb{c}\T\vb{x} + c_0} cancels from numerator and denominator. The K(d+1)K(d + 1) parameters determine only (K−1)(d+1)(K - 1)(d + 1) identifiable quantities. This is softmax’s lack of identifiability.

InteractiveSoftmax decision regions
  • class 1 and w1\vb{w}_1
  • class 2 and w2\vb{w}_2
  • class 3 and w3\vb{w}_3
  • vector común c\vb{c}
Classes
1.00
Intercepts
-0.10
0.18
-0.08
p1(x)p_1(\vb{x})0.598
p2(x)p_2(\vb{x})0.285
p3(x)p_3(\vb{x})0.116
Mean cross-entropy0.0218
Correct36 / 36
c\vb{c}(1.10, −0.70)
∑kwk\sum_k \vb{w}_k(3.30, −2.10)
w1−w2\vb{w}_1 - \vb{w}_2(3.31, −1.52)
All wk\vb{w}_k have the common vector c\vb{c}, added, but probabilities, loss and regions are the same as with c=0\vb{c} = \vb{0} (press “Remove c” or drag the handle): only differences matter wk−wj\vb{w}_k - \vb{w}_j.
Three or four groups of points (Gaussians with standard deviation 0.6, twelve per class) and draggable softmax regression weight vectors wk\vb{w}_k. Each point in the plane mixes class colors weighted by their probabilities: pure colors indicate certainty and mixed colors uncertainty. Initially, weights are fitted with a small L2 penalty plus a common vector c\vb{c} (the gray handle), added to every wk\vb{w}_k. Press “Remove c” or drag the handle: arrows move together, but does anything that matters change? Increase the logit scale to see regions sharpen, and move one wk\vb{w}_k toward another: what happens to that class's region?

The boundary between classes kk and jj is the hyperplane (wk−wj)⊤x+(bk−bj)=0(\vb{w}_k - \vb{w}_j)\T\vb{x} + (b_k - b_j) = 0, so the c\vb{c} handle does not move it. There are two common ways to fix a representative:

  • Reference class. Fix wK=0\vb{w}_K = \vb{0} and bK=0b_K = 0: the other coefficients are log odds against class KK, log⁡P(Y=k∣x)P(Y=K∣x)=wk⊤x+bk\log\frac{\Pr(Y = k \given \vb{x})}{\Pr(Y = K \given \vb{x})} = \vb{w}_k\T\vb{x} + b_k. This is the parameterization of classical statistics (and statsmodels).
  • Penalty. With λ2∑k∥wk∥2\frac{\lambda}{2}\sum_k\norm{\vb{w}_k}^2, the optimum satisfies ∑kwk=0\sum_k \vb{w}_k = \vb{0}: otherwise subtracting the mean wˉ=1K∑kwk\bar{\vb{w}} = \frac{1}{K}\sum_k\vb{w}_k from all of them would leave loss unchanged and reduce the penalty, because ∑k∥wk−c∥2\sum_k\norm{\vb{w}_k - \vb{c}}^2 is minimized at c=wˉ\vb{c} = \bar{\vb{w}}. This is what scikit-learn does (the lab shows its coef_ rows sum to zero).

The negative log-likelihood is multiclass cross-entropy. With Y∈{0,1}n×K\vb{Y} \in \{0, 1\}^{n \times K} the one-hot encoding of labels, P∈Rn×K\mat{P} \in \R^{n \times K} the probability matrix and Θ∈R(d+1)×K\mat{\Theta} \in \R^{(d+1) \times K} parameters in columns,

L(Θ)=∑i=1n[log⁡∑j=1Kezij−zi,yi],∇ΘL=X⊤(P−Y).\Loss(\mat{\Theta}) = \sum_{i=1}^n \Big[\log\sum_{j=1}^K e^{z_{ij}} - z_{i,y_i}\Big], \qquad \grad_{\mat{\Theta}}\Loss = \mat{X}\T(\mat{P} - \vb{Y}).

Again the gradient has the form “prediction minus label.” The Hessian with respect to one example’s logits is diag⁡(pi)−pipi⊤\diag(\vb{p}_i) - \vb{p}_i\vb{p}_i\T, positive semidefinite (it is the covariance matrix of a one-hot categorical variable with probabilities pi\vb{p}_i), so L\Loss is convex; but it has 1\vb{1} in its null space, the lack of identifiability viewed through curvature: loss is flat in the direction “add the same value to all logits,” and the full Hessian is singular. Newton needs a reference class or a penalty; gradient descent does not, and, since ∑k(pik−yik)=0\sum_k(p_{ik} - y_{ik}) = 0, starting from Θ=0\mat{\Theta} = \mat{0} each step preserves ∑kwk=0\sum_k\vb{w}_k = \vb{0}.

Stable computation uses the log-sum-exp trick: log⁡∑jezj=M+log⁡∑jezj−M\log\sum_j e^{z_j} = M + \log\sum_j e^{z_j - M} with M=max⁡jzjM = \max_j z_j, which avoids overflow and preserves the dominant term. This operation ends classification networks and language models: predicting the next token is softmax regression over a vocabulary of tens of thousands of classes, with features learned by the network.

Softmax from scratch

The wine dataset has 178 wines from three cultivars with 13 chemical measurements. We implement loss with log-sum-exp, its gradient, and gradient descent on the same objective scikit-learn minimizes, C∑iℓi+12∑k∥wk∥2C\sum_i\ell_i + \frac{1}{2}\sum_k\norm{\vb{w}_k}^2 with unpenalized bkb_k. The Hessian of cross-entropy with respect to one example’s logits has eigenvalues at most 1/21/2, so L=C2λmax⁡(X⊤X)+1L = \frac{C}{2}\lambda_{\max}(\mat{X}\T\mat{X}) + 1 is a Lipschitz constant for the gradient.

[ ]Softmax regression from scratch versus LogisticRegressionBrowser
import numpy as np
from sklearn.datasets import load_wine
from sklearn.linear_model import LogisticRegression

Xv, yv = load_wine(return_X_y=True)
Xv = (Xv - Xv.mean(axis=0)) / Xv.std(axis=0)
n, d = Xv.shape
K = 3
Y = np.eye(K)[yv]                              # one-hot, n x K
A = np.column_stack([Xv, np.ones(n)])          # última columna: término independiente
C = 1.0

def logsumexp_filas(Z):
    M = Z.max(axis=1, keepdims=True)
    return (M + np.log(np.exp(Z - M).sum(axis=1, keepdims=True))).ravel()

def objetivo(T):                               # T: (d + 1) x K
    Z = A @ T
    return C * np.sum(logsumexp_filas(Z) - Z[np.arange(n), yv]) + 0.5 * np.sum(T[:-1] ** 2)

def gradiente(T):
    Z = A @ T
    P = np.exp(Z - logsumexp_filas(Z)[:, None])
    G = C * A.T @ (P - Y)
    G[:-1] += T[:-1]                           # penalización solo en los pesos
    return G

L = C / 2 * np.linalg.eigvalsh(A.T @ A)[-1] + 1
T = np.zeros((d + 1, K))
for t in range(1, 3001):
    T -= gradiente(T) / L
    if t in (100, 1000, 3000):
        print(f"t = {t:4d}: objetivo = {objetivo(T):.6f}   ||gradiente|| = {np.linalg.norm(gradiente(T)):.1e}")

sk = LogisticRegression(C=C, tol=1e-10, max_iter=10000).fit(Xv, yv)
T_sk = np.vstack([sk.coef_.T, sk.intercept_])
print(f"scikit-learn:  objetivo = {objetivo(T_sk):.6f}")
print(f"max|W - W_sk| = {np.abs(T[:-1] - T_sk[:-1]).max():.1e}   max|b - b_sk| = {np.abs(T[-1] - T_sk[-1]).max():.1e}")
print(f"suma de los w_k (desde cero): {np.abs(T[:-1].sum(axis=1)).max():.1e}   predicciones iguales: {np.mean((A @ T).argmax(axis=1) == sk.predict(Xv)):.0%}")

z = np.array([[1000.0, 999.0, 0.0]])
with np.errstate(over="ignore", invalid="ignore"):
    print("softmax ingenua de (1000, 999, 0):", np.exp(z) / np.exp(z).sum(), "  estable:", np.exp(z - logsumexp_filas(z)[:, None]).round(4))

After 3000 iterations, the objective is within 6×10−56\times 10^{-5} of scikit-learn’s (12.090398 versus 12.090336), weights agree within 2.3×10−32.3\times 10^{-3} and intercepts within 1.1×10−21.1\times 10^{-2}: gradient descent has not quite finished, especially for the unpenalized, low-curvature intercepts, while scikit-learn’s lbfgs reaches the requested tolerance. Predictions agree on every wine. The sum of wk\vb{w}_k is zero up to rounding without being imposed, as the gradient argument predicts, and naive softmax on large logits returns nan.

One versus rest and multinomial

The alternative to softmax trains KK independent binary logistic models, “class kk versus all others,” and predicts the highest-scoring one (one versus rest, OvR). This is what liblinear does and what scikit-learn did by default before version 0.22. It has three drawbacks: the KK probabilities do not sum to one (they must be normalized afterward, and the result is not the maximum-likelihood estimate of a joint model for the KK classes); each classifier sees an imbalanced problem (11 versus K−1K - 1); and the KK models do not coordinate, so they can contradict one another near boundaries. Softmax fits one joint distribution and is the default; OvR makes sense when classes are not mutually exclusive (multilabel classification) or when KK is so large that independent parallel training pays off.

GLMs from a prediction perspective: Poisson and Tweedie

Logistic regression is the Bernoulli case of a generalized linear model: an exponential-family distribution for Y∣xY \given \vb{x}, a linear predictor η=w⊤x\eta = \vb{w}\T\vb{x} and a link g(E[Y∣x])=ηg(\E[Y \given \vb{x}]) = \eta. In the GLM lesson you studied it as a statistical model (inference, deviance, tests). Here the other view matters: choosing a GLM means choosing a loss and link for a prediction problem.

When yy is a count (claims per policy, visits per day, failures per machine), the natural choice is Poisson with a log link, E[Y∣x]=μ(x)=ew⊤x\E[Y \given \vb{x}] = \mu(\vb{x}) = e^{\vb{w}\T\vb{x}}. The negative log-likelihood, omitting the term log⁡yi!\log y_i! independent of w\vb{w}, is

L(w)=∑i[μi−yilog⁡μi]=∑i[eηi−yiηi],∇L=X⊤(μ−y),∇2L=X⊤diag⁡(μi) X,\Loss(\vb{w}) = \sum_i \big[\mu_i - y_i\log\mu_i\big] = \sum_i \big[e^{\eta_i} - y_i\eta_i\big], \qquad \grad\Loss = \mat{X}\T(\vb{\mu} - \vb{y}), \qquad \hess\Loss = \mat{X}\T\diag(\mu_i)\,\mat{X},

with the same structure as logistic regression: convex, with gradient “mean minus observation” (the canonical link again) and a Hessian weighting each example by its variance. The associated metric is Poisson deviance, D=2∑i[yilog⁡(yi/μi)−(yi−μi)]D = 2\sum_i\big[y_i\log(y_i/\mu_i) - (y_i - \mu_i)\big], twice the log-likelihood difference from the saturated model. Why not use squared loss? With the right link both estimate the same thing, because both elicit the mean; but Poisson weights each example according to its assumed variance (Var⁡(Y)=μ\Var(Y) = \mu), and is more efficient if that variance is correct. With squared loss and the identity link (linear regression on counts), negative predictions appear and multiplicative structure is lost.

For costs (total claims on a policy, customer spending), the variable has a mass at zero and a positive skewed continuous part. The Tweedie family with power 1<p<21 < p < 2 is exactly that: a compound Poisson-gamma model, Y=∑j=1NGjY = \sum_{j=1}^N G_j with N∼Pois⁡N \sim \Pois and gamma GjG_j, having Var⁡(Y)=ϕ μp\Var(Y) = \phi\,\mu^p. The power interpolates among normal (p=0p = 0), Poisson (p=1p = 1) and gamma (p=2p = 2); in non-life insurance it commonly models pure premium, and scikit-learn provides TweedieRegressor(power=p, link="log").

[ ]Counts: squared versus Poisson loss, from scratch and with scikit-learnBrowser
import numpy as np
from sklearn.linear_model import LinearRegression, PoissonRegressor, TweedieRegressor
from sklearn.metrics import mean_poisson_deviance, mean_squared_error

rng = np.random.default_rng(0)
n, d = 4000, 3
X = rng.normal(size=(n, d))
beta, b0 = np.array([0.6, -0.4, 0.25]), 0.3
y = rng.poisson(np.exp(b0 + X @ beta)).astype(float)      # conteos con media log-lineal
tr = np.arange(n) < 3000
Xtr, ytr, Xte, yte = X[tr], y[tr], X[~tr], y[~tr]
print(f"ceros: {np.mean(y == 0):.1%}   media: {y.mean():.3f}   máximo: {y.max():.0f}")

# Poisson desde cero: descenso por gradiente sobre la pérdida media
A = np.column_stack([np.ones(len(ytr)), Xtr])
th = np.zeros(d + 1)
for t in range(2000):
    th -= 0.1 * A.T @ (np.exp(A @ th) - ytr) / len(ytr)
print("Poisson desde cero:", np.round(th, 4), "  verdad:", np.r_[b0, beta])

modelos = {
    "cuadrática, enlace identidad": LinearRegression().fit(Xtr, ytr).predict(Xte),
    "cuadrática sobre log(1 + y)": np.expm1(LinearRegression().fit(Xtr, np.log1p(ytr)).predict(Xte)),
    "cuadrática, enlace log": TweedieRegressor(power=0, link="log", alpha=0, tol=1e-10, max_iter=1000).fit(Xtr, ytr).predict(Xte),
    "Poisson desde cero": np.exp(np.column_stack([np.ones(len(yte)), Xte]) @ th),
    "PoissonRegressor": PoissonRegressor(alpha=0, tol=1e-10, max_iter=1000).fit(Xtr, ytr).predict(Xte),
    "media verdadera": np.exp(b0 + Xte @ beta),
}
print(f"\nmedia observada en test: {yte.mean():.3f}")
print(f"{'modelo':30s} {'desv. Poisson':>14s} {'ECM':>7s} {'media pred.':>12s} {'pred. <= 0':>11s}")
for nombre, mu in modelos.items():
    print(f"{nombre:30s} {mean_poisson_deviance(yte, np.clip(mu, 1e-3, None)):14.4f} {mean_squared_error(yte, mu):7.4f}"
          f" {mu.mean():12.3f} {np.mean(mu <= 0):11.1%}")

The table shows four numerical findings:

  • The identity link fails structurally: 11.2% of its predictions are negative (they must be clipped to compute deviance), and its mean test deviance, 1.615, is the worst.
  • Transforming the response is not the same as changing the link. Least-squares fitting of log⁡(1+y)\log(1 + y) and undoing the transformation gives a predicted mean of 1.519 versus 1.731 observed: it estimates exp⁡E[log⁡(1+Y)∣x]−1\exp\E[\log(1 + Y) \given \vb{x}] - 1, which by Jensen’s inequality is less than E[Y∣x]\E[Y \given \vb{x}]. That is 12% systematic bias in the total, unacceptable if the total sets a price (and 4.5% of predictions remain negative).
  • With the log link, squared loss already works (deviance 1.089): it elicits the mean, like Poisson loss. The remaining difference is efficiency.
  • Poisson from scratch and PoissonRegressor agree in all displayed figures (1.0862), very close to the true-mean deviance, 1.0828, the limit achievable with this noise.

To see the efficiency difference we must repeat the experiment; for Tweedie we check that it recovers the coefficients of a cost model with many zeros.

[ ]Poisson loss efficiency and a Tweedie cost modelBrowser
errores = []
for r in range(20):
    rr = np.random.default_rng(100 + r)
    Xr = rr.normal(size=(1000, d))
    yr = rr.poisson(np.exp(b0 + Xr @ beta)).astype(float)
    verdad = np.r_[b0, beta]
    po = PoissonRegressor(alpha=0, tol=1e-10).fit(Xr, yr)
    cu = TweedieRegressor(power=0, link="log", alpha=0, tol=1e-10, max_iter=1000).fit(Xr, yr)
    errores.append([np.sum((np.r_[po.intercept_, po.coef_] - verdad) ** 2), np.sum((np.r_[cu.intercept_, cu.coef_] - verdad) ** 2)])
e = np.mean(errores, axis=0)
print(f"error cuadrático medio de los coeficientes en 20 repeticiones: Poisson {e[0]:.4f}   cuadrática con enlace log {e[1]:.4f}   cociente {e[1] / e[0]:.2f}")

# costes: número de siniestros Poisson, importe de cada uno gamma(forma 2, escala 500)
rc = np.random.default_rng(1)
Xc = rc.normal(size=(4000, 2))
lam = np.exp(-1.0 + Xc @ np.array([0.5, -0.3]))
coste = np.array([rc.gamma(2.0, 500.0, size=k).sum() for k in rc.poisson(lam)])
tw = TweedieRegressor(power=1.5, link="log", alpha=0, max_iter=1000).fit(Xc, coste)
print(f"\ncostes: {np.mean(coste == 0):.1%} de ceros, media {coste.mean():.1f}")
print(f"Tweedie p = 1.5: término independiente {tw.intercept_:.3f} (verdad log(1000) - 1 = {np.log(1000) - 1:.3f}), coeficientes {np.round(tw.coef_, 3)} (verdad [0.5, -0.3])")

Across twenty repetitions with 1000 examples, coefficient mean squared error is 1.8 times greater with squared loss than Poisson loss: both estimators are consistent, but Poisson exploits knowledge of each observation’s variance. The Tweedie model recovers the structure of a cost with 67.7% zeros: each policy’s mean is λ(x)⋅2⋅500\lambda(\vb{x})\cdot 2\cdot 500, so the true intercept is log⁡1000−1\log 1000 - 1, and coefficients are those of frequency.

With scikit-learn

In practice all this takes only a few classes, and their conventions cause the most mistakes.

[ ]LogisticRegression, SGDClassifier and prior correctionBrowser
import numpy as np
from sklearn.datasets import load_breast_cancer, load_wine
from sklearn.linear_model import LogisticRegression, SGDClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

Xb, yb = load_breast_cancer(return_X_y=True)
for C in [0.01, 1.0, 100.0]:
    pipe = make_pipeline(StandardScaler(), LogisticRegression(C=C, max_iter=5000)).fit(Xb, yb)
    lr = pipe[-1]
    print(f"C = {C:6.2f}  (fuerza 1/C = {1 / C:6.2f}):  ||w|| = {np.linalg.norm(lr.coef_):6.2f}   p media = {pipe.predict_proba(Xb)[:, 1].mean():.4f}")

sgd = make_pipeline(StandardScaler(), SGDClassifier(loss="log_loss", alpha=1e-3, max_iter=50, tol=None, random_state=0)).fit(Xb, yb)
print(f"\nSGDClassifier(loss='log_loss'): exactitud en entrenamiento {sgd.score(Xb, yb):.3f}, primera probabilidad {sgd.predict_proba(Xb[:1])[0, 1]:.3f}")

# softmax: filas de coef_ que suman cero e invariancia a un desplazamiento común
Xw, yw = load_wine(return_X_y=True)
Xw = StandardScaler().fit_transform(Xw)
mw = LogisticRegression(C=1.0, max_iter=5000).fit(Xw, yw)
c = np.random.default_rng(0).normal(size=Xw.shape[1])
Zc = Xw @ (mw.coef_ + c).T + mw.intercept_
Pc = np.exp(Zc - Zc.max(axis=1, keepdims=True)); Pc /= Pc.sum(axis=1, keepdims=True)
print(f"\nwine, multinomial: |suma de las filas de coef_| máx = {np.abs(mw.coef_.sum(axis=0)).max():.1e},"
      f" cambio en las probabilidades al sumar c a todas = {np.abs(Pc - mw.predict_proba(Xw)).max():.1e}")

# reponderar clases desplaza el término independiente en log(n0/n1)
rng = np.random.default_rng(0)
Xr = rng.normal(size=(20000, 2))
yr = (rng.uniform(size=20000) < 1 / (1 + np.exp(-(-3.5 + Xr @ np.array([1.0, -0.8]))))).astype(int)
n1 = yr.sum(); n0 = len(yr) - n1
normal = LogisticRegression(C=np.inf).fit(Xr, yr)
bal = LogisticRegression(C=np.inf, class_weight="balanced").fit(Xr, yr)
print(f"\nprevalencia {yr.mean():.4f}:  p media sin pesos {normal.predict_proba(Xr)[:, 1].mean():.4f},  con class_weight='balanced' {bal.predict_proba(Xr)[:, 1].mean():.4f}")
print(f"b_balanced - b = {bal.intercept_[0] - normal.intercept_[0]:.3f}   log(n0/n1) = {np.log(n0 / n1):.3f}   coeficientes: {np.round(normal.coef_[0], 3)} y {np.round(bal.coef_[0], 3)}")
z_corr = bal.decision_function(Xr) - np.log(n0 / n1)
print(f"tras restar log(n0/n1): p media {np.mean(1 / (1 + np.exp(-z_corr))):.4f}")

Points to remember:

  • C is inverse regularization strength and multiplies summed losses: the objective is C∑iℓi+12∥w∥2C\sum_i\ell_i + \frac{1}{2}\norm{\vb{w}}^2. Increasing C regularizes less: in the cell, ∥w∥\norm{\vb{w}} rises from 0.90 to 3.84 to 21.41. Mean probability, however, is 0.6274 (the benign fraction) for all three values, because bb is unpenalized and ∑ipi=∑iyi\sum_i p_i = \sum_i y_i still holds with L2. This is equivalent to ridge with λ=1/C\lambda = 1/C on the sum of losses, or λ=1/(nC)\lambda = 1/(nC) on the mean; translate it when moving between libraries. Regularization is active by default (C=1C = 1).
  • SGDClassifier(loss="log_loss") is the same logistic regression trained by SGD, with its alpha penalty on mean loss. It scales to data that do not fit in memory using partial_fit.
  • scikit-learn softmax penalizes with L2 and, as predicted, its coef_ rows sum to zero up to rounding; adding a common vector to all of them changes no probabilities.
  • class_weight="balanced" changes probabilities. With prevalence 5.4%, mean predicted probability rises to 37%. Coefficients barely change; the intercept shifts by almost exactly log⁡(n0/n1)\log(n_0/n_1), and subtracting it restores probabilities with the correct mean. The next section explains why.

Common mistakes

Exercises

NumericA coefficient as an odds ratio
A logistic default model has coefficient 0.70.7 for the binary feature “has defaulted before.” Holding other variables fixed, by what factor do default odds change when the feature goes from 0 to 1?
NumericSoftmax probability
A three-class softmax regression assigns an example logits (2,1,0)(2, 1, 0). What probability does it assign to the first class?
NumericUndoing undersampling
To train a fraud detector you retained all fraudulent transactions and only 2% of legitimate ones, selected at random. A well-specified model fitted on that sample gives p′=0.8p' = 0.8 for a new transaction. What fraud probability corresponds to the real population?
NumericHow many gradient iterations?
At the optimum of logistic regression on ten breast_cancer variables, the lab measures L/μ≈2.44×105L/\mu \approx 2.44\times 10^5. If error contracts by a factor 1−μ/L1 - \mu/L per iteration, approximately how many iterations reduce it by a factor 10610^6? Use ln⁡(1−x)≈−x\ln(1 - x) \approx -x.
NumericIdentifiable parameters
A softmax regression classifies 28×2828\times 28 pixel images into 10 digits, with one weight vector and intercept per class. How many identifiable quantities do its parameters determine?
QuizTen million rows and L1
You have 10710^7 rows, 10510^5 sparse variables (50 nonzeros per row on average), and want a binary logistic model with an L1 penalty. Which LogisticRegression solver do you choose?
QuizIncreasing C
You fit LogisticRegression(C=1.0) and then LogisticRegression(C=100.0) on the same standardized, nonseparable data. What do you expect?
QuizCoefficients that depend on max_iter
With standardized features, LogisticRegression(C=np.inf) warns that it did not converge with max_iter=100 and returns ∥w∥=68\norm{\vb{w}} = 68; with max_iter=1000 it stops on its own at iteration 305 with ∥w∥=441\norm{\vb{w}} = 441 and lower mean loss. On the same data, C=1 converges in 19 iterations with ∥w∥=3.8\norm{\vb{w}} = 3.8. What is most likely?
QuizOne versus rest
Which statement about one versus rest (OvR) versus multinomial softmax is true?
ProofThe Hessian and convexity
Prove: For L(w)=∑i=1n[log⁡(1+ezi)−yizi]\Loss(\vb{w}) = \sum_{i=1}^n[\log(1 + e^{z_i}) - y_iz_i] with zi=w⊤xiz_i = \vb{w}\T\vb{x}_i, the Hessian is X⊤WX\mat{X}\T\mat{W}\mat{X} with W=diag⁡(pi(1−pi))\mat{W} = \diag(p_i(1 - p_i)); L\Loss is convex and, if X\mat{X} has full column rank, strictly convex.
0
Write pi=σ(zi)p_i = \sigma(z_i) and use ∇L(w)=∑i(pi−yi)xi\grad\Loss(\vb{w}) = \sum_i (p_i - y_i)\vb{x}_i.

Step 1 of 4. What is the derivative of pi=σ(w⊤xi)p_i = \sigma(\vb{w}\T\vb{x}_i) with respect to w\vb{w}?

ProofSeparable data have no maximum
Prove: If there exists wˉ\bar{\vb{w}} with siwˉ⊤xi>0s_i\bar{\vb{w}}\T\vb{x}_i > 0 for all ii (labels si∈{−1,+1}s_i \in \{-1, +1\}), then L(w)=∑ilog⁡(1+e−siw⊤xi)\Loss(\vb{w}) = \sum_i\log(1 + e^{-s_i\vb{w}\T\vb{x}_i}) does not attain its infimum at any finite w\vb{w}, and log-likelihood does not attain its supremum.
0
Let mi=siwˉ⊤xi>0m_i = s_i\bar{\vb{w}}\T\vb{x}_i > 0 and m=min⁡imi>0m = \min_i m_i > 0.

Step 1 of 4. What lower bound does L(w)\Loss(\vb{w}) have for any w\vb{w}?

CodeIRLS with L2 penalty
Implement logistic_irls(X, y, l2=0.0, tol=1e-10, max_iter=50), fitting logistic regression with an intercept by Newton (IRLS) and returning (b, w, n_iter). The objective is ∑i[log⁡(1+ezi)−yizi]+l22∥w∥2\sum_i[\log(1 + e^{z_i}) - y_iz_i] + \frac{l2}{2}\norm{\vb{w}}^2, with zi=b+w⊤xiz_i = b + \vb{w}\T\vb{x}_i and unpenalized bb (matching LogisticRegression(C=1/l2)). Start at zero and stop when every component of the Newton step is below tol in absolute value. n_iter is the number of steps taken. Use np.linalg.solve, not the inverse.
import numpy as np

def logistic_irls(X, y, l2=0.0, tol=1e-10, max_iter=50):
  X = np.asarray(X, dtype=float)
  y = np.asarray(y, dtype=float)
  n, d = X.shape
  A = np.column_stack([np.ones(n), X])
  theta = np.zeros(d + 1)
  # tu código: en cada iteración, p, gradiente y hessiana (con la penalización
  # solo en las componentes de w), paso de Newton y criterio de parada
  return theta[0], theta[1:], 0
Shift+Enter to run

Summary

Key idea
Logistic regression models log odds as a linear function and is fitted by minimizing cross-entropy, the Bernoulli negative log-likelihood: a convex loss with gradient X⊤(p−y)\mat{X}\T(\vb{p} - \vb{y}) and Hessian X⊤WX\mat{X}\T\mat{W}\mat{X}. Its KK-class version, softmax, is the output layer of neural classifiers.
  • The model is P(Y=1∣x)=σ(w⊤x+b)\Pr(Y = 1 \given \vb{x}) = \sigma(\vb{w}\T\vb{x} + b): linear boundary, steepness ∥w∥\norm{\vb{w}}, and each coefficient multiplies odds by ewje^{w_j}, an interpretation meaningful for comparable, weakly correlated variables.
  • Loss is convex, and strictly convex if X\mat{X} has full rank; at the optimum, with an intercept, ∑ipi=∑iyi\sum_i p_i = \sum_i y_i. Compute it with logaddexp, never direct log⁡σ\log\sigma.
  • Newton is IRLS: weighted least squares with weights pi(1−pi)p_i(1 - p_i), quadratic convergence in a few iterations costing O(nd2+d3)\bigO(nd^2 + d^3). Gradient descent costs O(nd)\bigO(nd) per step but suffers from poor conditioning: 9 iterations versus millions on breast_cancer.
  • At scale: lbfgs by default, newton-cholesky if n≫dn \gg d, liblinear for small problems or binary L1, sag and saga for huge nn, and saga for multinomial L1 or elastic net.
  • With separable data the MLE does not exist: ∥w∥\norm{\vb{w}} grows like ∥w^∥ln⁡t\norm{\hat{\vb{w}}}\ln t and gradient descent’s direction converges very slowly to maximum margin. Regularization (on by default in scikit-learn, with CC the inverse of its strength) gives a finite solution.
  • Softmax determines only differences between classes: parameters are identifiable up to a common translation, fixed by a reference class or L2 penalty (with ∑kwk=0\sum_k\vb{w}_k = \vb{0}).
  • Choosing a GLM means choosing loss and link: Poisson with log link for counts, Tweedie with 1<p<21 < p < 2 for costs with zeros. Log-transforming the response is not equivalent and biases the mean.