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
- 11Margin-based classification lossesStatistical functional elicited by a lossLinear regression model and least-squares fittingLeast squares as Gaussian maximum likelihoodCentering, standardization and the interceptRidge regressionLasso
- 07Cross-entropy
- 06Local quadratic convergence of Newton's methodO(1/k) rate of gradient descent for smooth convex functionsLinear convergence of gradient descent for strongly convex functions
- 05Exponential familyMaximum likelihood estimator (MLE)Generalized linear modelCanonical linkIteratively reweighted least squares and Fisher scoring
- 04Bernoulli-trial distributionsPoisson distribution
- 09Log-sum-exp trick and stable softmaxNumerically stable reformulation
Motivation: probabilities, not labels
A bank does not just want to know whether a customer “will default”: it wants , 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 , 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 as soon as 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 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 , the odds are (0.8 gives odds of 4 to 1), and the logit function is their logarithm, , which ranges over all of . Its inverse is the sigmoid (logistic function),
Three properties are used constantly: ; , with maximum at ; and .
Geometrically, the model is a smooth step-shaped surface over the space of . The boundary is the hyperplane ; points toward increasing probability, and its norm determines the steepness of the step: along , the probability is , with maximum slope right at the boundary. The signed distance from to the boundary is : the logit is that distance multiplied by .
The data model in the figure is not arbitrary. If the two classes are Gaussian with the same covariance , Bayes’ rule gives exactly a logistic function:
because the quadratic terms cancel. With the figure’s values, and (the “True posterior” button). The maximum likelihood fit to those 40 points points in a similar direction but has twice the norm, versus : 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, , the log odds are plus a constant: linear in sufficient statistic , and in when the nonlinear components of have the same natural parameter in both classes (like the term for two Gaussians with equal covariance). The logistic function is shared by many generative models, and logistic regression fits it directly without modeling . This contrast between generative and discriminative models is the topic of lesson 11.
Coefficients as odds ratios
If variable increases by one unit while the others stay fixed, log odds increase by , so odds are multiplied by regardless of the starting point. This is the usual interpretation in epidemiology and credit risk: a coefficient of on a binary variable (smoker, customer with previous defaults) means odds are multiplied by . Watch two things. First, odds are multiplied, not probability: moving from (odds 1) to odds 2 gives , but starting at and doubling the odds gives . 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: has a 1 as its first coordinate and has as its first component (the design matrix has a column of ones). When there is a penalty, is not penalized.
Each label is Bernoulli with probability , , and its probability mass is . For independent observations the negative log-likelihood is
The second form follows from and . 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 between the empirical distribution and the model’s. Minimizing it minimizes , because the entropy of does not depend on .
- Logistic loss on the margin. With labels , each term is : a decreasing function of margin familiar from classification losses. For very negative margins it grows like , 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 values be interpreted as probabilities? Because logistic loss is a proper scoring rule: at a point where , conditional risk is minimized exactly at (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: . By the chain rule:
The gradient has the same form as in least squares, : 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 , large when the model is uncertain () and nearly zero when it is confident.
The first guided exercise proves this. Notice “at most”: strict convexity gives uniqueness, not existence. The function is strictly convex on 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 , the Hessian of mean loss is bounded by , so its gradient is Lipschitz with constant
and gradient descent with step has the guarantee for smooth convex functions, . But the loss is not strongly convex throughout : far from the origin the saturate, , and curvature tends to zero. If 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 the Hessian’s smallest eigenvalue there, gradient descent converges linearly, with a factor of order per iteration.
There is also a directly interpretable optimality condition. At the optimum, . The component for the column of ones says : with an intercept, mean fitted probability exactly matches the positive-class frequency in training. The others say residuals are orthogonal to each feature.
Computing loss without overflow
The formula is correct on paper and disastrous in floating point. In float64, rounds to 1 once , so ; and for , overflows, is exactly 0 and when the correct value is . The stable form is on the right of the definition: , computing as np.logaddexp(0, z), which uses the stable reformulation .
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 with the naive formula gives infinity when the correct value is , and at with it gives infinity where it should give . 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 . Each step costs two matrix-vector products, operations (or if is sparse), and memory is that of the data. The cost is the number of steps: near the optimum, error decreases by a factor per iteration. The ratio is an effective condition number (at least as large as that of the Hessian at the optimum, because 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: . Rearranging,
Check by multiplying: . Each Newton step is a weighted least-squares regression of a working response (the current logit plus a linearized correction) with weights . 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 iteration | Memory | Convergence | |
|---|---|---|---|
| Gradient | beyond the data | linear near the optimum, factor | |
| Newton / IRLS | quadratic near the optimum | ||
| SGD (one example) | 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 has full rank. Far from the optimum there is no guarantee: if initial logits are large, , the Hessian is nearly singular and the step may shoot off. Practical implementations damp the step with a line search or trust region. From , where all and weights are maximal, pure Newton often works well.
With uncentered (), the design matrix columns and are almost parallel: increasing while reducing 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 , while Newton, which corrects the geometry by multiplying by the inverse Hessian, takes four. SGD suffers similarly and its step, which starts here at to keep any example from destabilizing it and decreases as , 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.
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 until the gradient is on the order of rounding error, and gradient descent with step for ten thousand iterations, measuring the remaining gap.
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 to and then , that is, . The number of correct digits doubles each step.
- Gradient descent remains far off after ten thousand iterations: and one coefficient differs from its optimum by nearly 10 units. The middle line explains why: , so the local contraction factor is per step. It would need on the order of millions of iterations.
- Three columns are responsible. Mean radius, perimeter and area have correlations from to (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 and area , 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 in 9 iterations (it is Newton, like ours); withlbfgs, within in 87 iterations because its stopping criterion is looser. And the sum of 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 and the algorithm hardly matters. With rows or 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 pairs of iterate and gradient differences (10 in SciPy), so each iteration costs one gradient, , plus , and stores no 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 by conjugate gradients using only Hessian-vector products, , each costing . Few outer iterations, without forming . L2 or no penalty.newton-cholesky: exact Newton. It forms () and factorizes it (). This is what you implemented. Ideal with ; memory is prohibitive for large because it stores a dense 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 inOneVsRestClassifier) and penalizes the intercept, treating it as another variable with valueintercept_scaling.sagandsaga: 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 (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.
| solver | penalties (l1_ratio) | multinomial multiclass | dominant cost | when |
|---|---|---|---|---|
lbfgs | L2 or none | yes | one gradient per iteration | default, moderate dense and sparse data |
newton-cg | L2 or none | yes | Hessian-vector products | large , high accuracy |
newton-cholesky | L2 or none | yes | , one-hot categorical variables with rare levels | |
liblinear | L1 or L2 | no (binary only) | trust-region Newton or coordinates | small or sparse data, binary L1 |
sag | L2 or none | yes | per example | very large , scaled features |
saga | L1, L2, elastic net or none | yes | per example | very large , 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, (or 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.
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"])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-choleskyandliblinear), 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-choleskypays its cost: at it is several times slower thanlbfgsdespite needing half as many iterations, because forming without BLAS is expensive. With BLAS that product is much more efficient and the difference shrinks.sagandsaganeed between 19 and 40 epochs and at these sizes do not beatlbfgs; on dense data,sagis the slowest of all. Their advantage is asymptotic: for a strongly convex problem they need on the order of single-example gradients (with the worst-example smoothness constant), versus for full gradient descent. In epochs, versus : larger means fewer epochs, and epoch count stops depending on conditioning when . With or and a well-conditioned problem, this regime does not arrive.- All reach the same optimum, apart from relative differences from to reflecting different stopping criteria with the same
tol, not method quality. If the last digits matter, lowertoland compare. - With L1 only
liblinearandsagaremain, and both give the same sparse model (about 90% of coefficients exactly zero).liblinearis much faster at this size;sagascales to millions of rows and alone supports elastic net and multinomial with L1.newton-choleskyis 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 for every , loss along the ray is , which tends to 0 as ; and loss is strictly positive at every finite . 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 , 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 on the order of , generic data are often separable (in , points in general position are separable with any labeling, and by Cover’s 1965 theorem, with random labels the probability is still when ); 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 , where is the smoothness constant of one-example loss ( for logistic loss) and the loss is summed rather than averaged, the iterates satisfy
with bounded . The vector solves the maximum-margin SVM (hard margin), whose geometric margin is . Three consequences: the norm grows like without bound; the loss tends to zero as ; and the direction converges to maximum margin, but very slowly: for almost all datasets (their Theorem 5; in degenerate cases, ). 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.
Penalization changes the problem. With 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 , the normalized solution of logistic regression penalized by the norm converges to the maximum-margin separator measured in the norm: the maximum-margin SVM with L2 and, with L1, the maximum 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 using a constrained optimizer, and twenty thousand iterations of the same gradient descent.
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 , with and two support vectors. Gradient descent starts 47° from (its first step is the mean of , pointing toward each class’s mass rather than the gap between them) and the angle drops to about 14° at , 6.6° at and 3.8° at : each decade gained costs ten times as many iterations, the signature of . The measured slope of against approaches from below, and the classifier’s margin rises toward while mean loss is already on the order of . 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 with for every .
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 ; with more room it stops by its own criterion at iteration 305, with , mean loss and accuracy : 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 ). With the default penalty (), the problem has a unique solution, with , reached in 19 iterations and independent of max_iter. This is why scikit-learn regularizes by default.
Multiple classes: softmax regression
With classes, , each class gets its own linear function, (the logits), which are converted to probabilities by softmax.
With this is ordinary logistic regression: . This reveals the model’s central feature: only differences matter. Add the same vector to every and the same constant to every , and each logit increases by ; the factor cancels from numerator and denominator. The parameters determine only identifiable quantities. This is softmax’s lack of identifiability.
The boundary between classes and is the hyperplane , so the handle does not move it. There are two common ways to fix a representative:
- Reference class. Fix and : the other coefficients are log odds against class , . This is the parameterization of classical statistics (and
statsmodels). - Penalty. With , the optimum satisfies : otherwise subtracting the mean from all of them would leave loss unchanged and reduce the penalty, because is minimized at . This is what scikit-learn does (the lab shows its
coef_rows sum to zero).
The negative log-likelihood is multiclass cross-entropy. With the one-hot encoding of labels, the probability matrix and parameters in columns,
Again the gradient has the form “prediction minus label.” The Hessian with respect to one example’s logits is , positive semidefinite (it is the covariance matrix of a one-hot categorical variable with probabilities ), so is convex; but it has 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 , starting from each step preserves .
Stable computation uses the log-sum-exp trick: with , 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, with unpenalized . The Hessian of cross-entropy with respect to one example’s logits has eigenvalues at most , so is a Lipschitz constant for the gradient.
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 of scikit-learn’s (12.090398 versus 12.090336), weights agree within and intercepts within : 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 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 independent binary logistic models, “class 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 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 classes); each classifier sees an imbalanced problem ( versus ); and the 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 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 , a linear predictor and a link . 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 is a count (claims per policy, visits per day, failures per machine), the natural choice is Poisson with a log link, . The negative log-likelihood, omitting the term independent of , is
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, , 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 (), 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 is exactly that: a compound Poisson-gamma model, with and gamma , having . The power interpolates among normal (), Poisson () and gamma (); in non-life insurance it commonly models pure premium, and scikit-learn provides TweedieRegressor(power=p, link="log").
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 and undoing the transformation gives a predicted mean of 1.519 versus 1.731 observed: it estimates , which by Jensen’s inequality is less than . 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
PoissonRegressoragree 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.
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 , so the true intercept is , 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.
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:
Cis inverse regularization strength and multiplies summed losses: the objective is . IncreasingCregularizes less: in the cell, rises from 0.90 to 3.84 to 21.41. Mean probability, however, is 0.6274 (the benign fraction) for all three values, because is unpenalized and still holds with L2. This is equivalent to ridge with on the sum of losses, or on the mean; translate it when moving between libraries. Regularization is active by default ().SGDClassifier(loss="log_loss")is the same logistic regression trained by SGD, with itsalphapenalty on mean loss. It scales to data that do not fit in memory usingpartial_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 , and subtracting it restores probabilities with the correct mean. The next section explains why.
Common mistakes
Exercises
breast_cancer variables, the lab measures . If error contracts by a factor per iteration, approximately how many iterations reduce it by a factor ? Use .LogisticRegression solver do you choose?LogisticRegression(C=1.0) and then LogisticRegression(C=100.0) on the same standardized, nonseparable data. What do you expect?LogisticRegression(C=np.inf) warns that it did not converge with max_iter=100 and returns ; with max_iter=1000 it stops on its own at iteration 305 with and lower mean loss. On the same data, C=1 converges in 19 iterations with . What is most likely?Step 1 of 4. What is the derivative of with respect to ?
Step 1 of 4. What lower bound does have for any ?
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 , with and unpenalized (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:], 0Summary
- The model is : linear boundary, steepness , and each coefficient multiplies odds by , an interpretation meaningful for comparable, weakly correlated variables.
- Loss is convex, and strictly convex if has full rank; at the optimum, with an intercept, . Compute it with
logaddexp, never direct . - Newton is IRLS: weighted least squares with weights , quadratic convergence in a few iterations costing . Gradient descent costs per step but suffers from poor conditioning: 9 iterations versus millions on
breast_cancer. - At scale:
lbfgsby default,newton-choleskyif ,liblinearfor small problems or binary L1,sagandsagafor huge , andsagafor multinomial L1 or elastic net. - With separable data the MLE does not exist: grows like and gradient descent’s direction converges very slowly to maximum margin. Regularization (on by default in scikit-learn, with 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 ).
- Choosing a GLM means choosing loss and link: Poisson with log link for counts, Tweedie with for costs with zeros. Log-transforming the response is not equivalent and biases the mean.