Regression gradients: linear, logistic and softmax
Ten problems on the gradients of linear, logistic and softmax regression in matrix form: the 2/N of the mean squared error, the normal equations and ridge, the logistic gradient Xᵀ(σ(Xw) − y)/N, its Hessian and convexity, and the softmax-regression gradient Xᵀ(S − Y)/N with shapes, with worked solutions and the mistakes that lose a factor or a transpose.
Before you start
Linear, logistic and softmax regression are one-layer networks, and their gradients are the first place the rules of the previous two pages meet a whole dataset at once. These ten problems derive each gradient in matrix form with the 1/N of a mean loss kept in view, solve the linear case in closed form with and without a ridge penalty, show why the logistic loss is convex, and then extend to many classes. The five mistakes at the end are the ones that survive a quick check: a constant dropped from the gradient, a closed form copied from a loss without the ,1/N, an extra sigmoid derivative, a Hessian over examples instead of weights, and a weight gradient in the other library's layout.
The conventions are those of the previous pages: vectors are columns, Jacobians are in numerator layout, a gradient has the shape of the variable it is taken with respect to, and for a scalar L of u with u a function of ,w,.∇wL=(∂u/∂w)⊤∇uL.
The data: N examples with d features each. Rows are examples: X∈RN×d has row n equal to ,x(n)⊤, so x(n)∈Rd is example n as a column, and Xnj is feature j of example .n.
Linear regression: targets ,y∈RN, weights ,w∈Rd, predictions ,Xw, and the mean squared error .L(w)=N1∥Xw−y∥2=N1∑n(x(n)⊤w−yn)2. Ridge adds λ∥w∥2 with .λ>0.
σ(t)=1/(1+e−t) is the logistic sigmoid; on a vector it acts entry by entry, and ⊙ is the elementwise product.
Logistic regression: labels ,yn∈{0,1}, probabilities p=σ(Xw)∈RN with entries ,pn=σ(x(n)⊤w), per-example loss ℓn=−[ynlogpn+(1−yn)log(1−pn)] (binary cross-entropy, natural log), and .L=N1∑nℓn.D=diag(p⊙(1−p)) is the N×N diagonal matrix of the weights .pn(1−pn).
Softmax regression with k classes: W∈Rd×k has one column wi per class, ,b∈Rk, the logits are Z=XW+1b⊤∈RN×k with 1 the all-ones vector, S is the softmax of Z taken row by row, Y holds the one-hot targets as rows, and .L=−N1∑n,iYnilogSni.
∇w2L is the Hessian, the d×d matrix of second derivatives ;∂2L/∂wi∂wj; it is the Jacobian of .∇wL.
Let .L(w)=N1∥Xw−y∥2. Compute ∇wL and check its shape.
··
Set the gradient of Problem 1 to zero. Derive the normal equations, say when their solution is unique, and show it is a minimum. Does the 1/N change the answer?
··
Ridge: Lλ(w)=N1∥Xw−y∥2+λ∥w∥2 with .λ>0. Compute ,∇wLλ, solve ,∇wLλ=0, and show the solution exists even when the columns of X are dependent.
·
Show that σ′(t)=σ(t)(1−σ(t)) and that .1−σ(t)=σ(−t).
··
One example: ,x∈Rd,,y∈{0,1},p=σ(x⊤w) and .ℓ=−[ylogp+(1−y)log(1−p)]. Compute .∇wℓ.
··
Batch: L=N1∑nℓn with ℓn as in Problem 5 for example .n. Write ∇wL in matrix form.
···
Compute the Hessian ∇w2L of the logistic loss of Problem 6. Show that it is positive semidefinite, so that L is convex.
···
Softmax regression: ,Z=XW+1b⊤,S the row-wise softmax of ,Z,Y one-hot rows, .L=−N1∑n,iYnilogSni. Compute ,∇ZL,∇WL and ,∇bL, with shapes.
···
Take k=2 and no bias, so Z=XW with columns .w1,w2. Show that Sn1=σ(x(n)⊤(w1−w2)) and that the loss is the logistic loss of Problem 6 with w=w1−w2 and .yn=Yn1. What does that say about ?W?
···
Newton's method updates .wnew=w−(∇w2L)−1∇wL. Write the step for logistic regression and show that the 1/N cancels.
Answers
∇wL=N2X⊤(Xw−y)
;X⊤Xw=X⊤y; when the columns of X are independent, ,w∗=(X⊤X)−1X⊤y, the unique minimiser, because the Hessian N2X⊤X is positive definite
;∇wLλ=N2X⊤(Xw−y)+2λw;w∗=(X⊤X+NλI)−1X⊤y
;σ′(t)=σ(t)(1−σ(t));1−σ(t)=σ(−t)
∇wℓ=(σ(x⊤w)−y)x
∇wL=N1X⊤(σ(Xw)−y)
∇w2L=N1X⊤DX with ,D=diag(p⊙(1−p)),;p=σ(Xw); it is positive semidefinite, so L is convex
∇WL=N1X⊤(S−Y) ();d×k);∇bL=N1(S−Y)⊤1 ()k)
,Sn1=σ(x(n)⊤(w1−w2)), so two-class softmax regression is logistic regression with w=w1−w2
wnew=w−(X⊤DX)−1X⊤(p−y)
Worked solutions
Problem 1
Let .L(w)=N1∥Xw−y∥2. Compute ∇wL and check its shape.
Let ,r=Xw−y∈RN, the residuals, so L=N1r⊤r=N1∑nrn2 with .rn=x(n)⊤w−yn.Naming the residual separates the square from the affine map inside it, so each can be differentiated on its own.
,∇rL=N2r,.N×1.Only the n-th term of the sum contains ,rn, and rn2 differentiates to .2rn.
,∂r/∂w=X,.N×d.r is X times w minus a constant, and the Jacobian of Ax is A (the matrix-calculus page, Problem 2).
.∇wL=(∂r/∂w)⊤∇rL=X⊤N2r.L depends on w only through ,r, so the chain rule for gradients applies.
∇wL=N2X⊤(Xw−y),(d×N)(N×1)=d×1, the shape of .w. Entry j is :N2∑nXnjrn: every example's residual, weighted by its feature ,j, averaged over the data.
Problem 2
Set the gradient of Problem 1 to zero. Derive the normal equations, say when their solution is unique, and show it is a minimum. Does the 1/N change the answer?
.N2X⊤(Xw−y)=0⟺X⊤Xw=X⊤y.Multiply both sides by .N/2=0. Scaling a loss by a positive constant does not move its minimiser, so the 1/N changes the size of gradient steps, never where they lead.
,∇w2L=N2X⊤X,.d×d.The gradient N2X⊤Xw−N2X⊤y is affine in ,w, so its Jacobian is the matrix that multiplies .w.
v⊤X⊤Xv=(Xv)⊤(Xv)=∥Xv∥2≥0 for every .v∈Rd.Associativity groups the product into a vector with itself, and a squared norm cannot be negative.
If the columns of X are independent, Xv=0 only for ,v=0, so v⊤X⊤Xv>0 for v=0 and X⊤X is invertible.Xv is the combination of the columns of X with coefficients ;v; independence means only the zero combination vanishes. A positive definite matrix has no null space.
;X⊤Xw=X⊤y; when the columns of X are independent, ,w∗=(X⊤X)−1X⊤y, the unique minimiser, because the Hessian N2X⊤X is positive definiteA function whose Hessian is positive definite everywhere is strictly convex, so its one stationary point is the global minimum. With dependent columns (fewer examples than features, or a repeated feature) X⊤X is singular and the minimisers form a whole affine set; Problem 3 removes that.
Problem 3
Ridge: Lλ(w)=N1∥Xw−y∥2+λ∥w∥2 with .λ>0. Compute ,∇wLλ, solve ,∇wLλ=0, and show the solution exists even when the columns of X are dependent.
.∇w(λ∥w∥2)=2λw.,λ∥w∥2=λ∑jwj2, and only the j-th term contains .wj.
.∇wLλ=N2X⊤(Xw−y)+2λw.The gradient of a sum is the sum of the gradients; the first term is Problem 1.
Setting it to zero and multiplying by :N/2:,X⊤Xw−X⊤y+Nλw=0, so .(X⊤X+NλI)w=X⊤y.The data term carries the 1/N of the mean and the penalty does not, so clearing the 1/N leaves an N on the penalty.
v⊤(X⊤X+NλI)v=∥Xv∥2+Nλ∥v∥2>0 for every .v=0.The first term is ≥0 (Problem 2, step 3) and the second is >0 because ,Nλ>0, whatever X is; so the matrix is positive definite and invertible.
;∇wLλ=N2X⊤(Xw−y)+2λw;w∗=(X⊤X+NλI)−1X⊤yStep 4 holds for every ,X, including ,N<d, so the solution always exists and is unique. For the summed loss ∥Xw−y∥2+λ′∥w∥2 the same steps give the familiar ;(X⊤X+λ′I)−1X⊤y; the two agree when .λ′=Nλ.
Problem 4
Show that σ′(t)=σ(t)(1−σ(t)) and that .1−σ(t)=σ(−t).
,σ(t)=(1+e−t)−1, so .σ′(t)=(1+e−t)2e−t.Chain rule: u−1 differentiates to ,−u−2, and 1+e−t to ;−e−t; the two minus signs cancel.
.1−σ(t)=1+e−t1+e−t−1=1+e−te−t.Put 1 over the common denominator.
.σ′(t)=1+e−t1⋅1+e−te−t=σ(t)(1−σ(t)).Split the square in step 1's denominator; the second factor is step 2.
.1+e−te−t=et+11=σ(−t).Multiply the numerator and denominator by ;et; the result is the definition of σ at .−t.
;σ′(t)=σ(t)(1−σ(t));1−σ(t)=σ(−t)Both factors lie in (0,1) and sum to ,1, so ,σ′(t)≤41, with equality at .t=0. The second identity says the probability of class 0 is the sigmoid of the negated logit, so the two classes are treated symmetrically.
Problem 5
One example: ,x∈Rd,,y∈{0,1},p=σ(x⊤w) and .ℓ=−[ylogp+(1−y)log(1−p)]. Compute .∇wℓ.
Let ,t=x⊤w, the logit, so .p=σ(t).ℓ depends on w only through the scalar ,t, so the chain rule has one link per variable.
.∂ℓ/∂p=−py+1−p1−y=p(1−p)p−y.logu differentiates to ,1/u, and log(1−p) to ;−1/(1−p); over the common denominator the numerator is .−y(1−p)+(1−y)p=p−y.
.∂p/∂t=p(1−p).Problem 4 at .t.
.∂ℓ/∂t=p−y.Chain rule, steps 2 and 3. The p(1−p) cancels, which is allowed because 0<p<1 for every finite .t.
.∇wt=x.t=x⊤w is linear in ,w, and ∇w(a⊤w)=a (the matrix-calculus page, Problem 3).
∇wℓ=(σ(x⊤w)−y)x,∇wℓ=(∂ℓ/∂t)∇wt, because t is a scalar. The shape is .d×1. It is the prediction error times the input, the same form as linear regression's residual times input.
Problem 6
Batch: L=N1∑nℓn with ℓn as in Problem 5 for example .n. Write ∇wL in matrix form.
∇wL=N1∑n(pn−yn)x(n) with .pn=σ(x(n)⊤w).The gradient of a mean is the mean of the gradients; each term is Problem 5 for example .n.
For any ,c∈RN,.∑ncnx(n)=X⊤c.The columns of X⊤ are the ,x(n), and a matrix times a vector combines its columns with the vector's entries as weights.
p=σ(Xw) has entries .pn.Entry n of Xw is row n of X times ,w, that is ,x(n)⊤w, and σ acts entry by entry.
∇wL=N1X⊤(σ(Xw)−y)Step 2 with .c=p−y. The shape is .(d×N)(N×1)=d×1. It is Problem 1's gradient with the prediction Xw replaced by σ(Xw) and without the ,2, which came from the square. Because σ is nonlinear, setting it to zero has no closed-form solution, so the weights are found iteratively (Problem 10).
Problem 7
Compute the Hessian ∇w2L of the logistic loss of Problem 6. Show that it is positive semidefinite, so that L is convex.
.∇wL=N1∑n(pn−yn)x(n).Problem 6, step 1.
.∇wpn=pn(1−pn)x(n).pn=σ(tn) with :tn=x(n)⊤w: Problem 4 for ∂pn/∂tn and Problem 5, step 5 for .∇wtn.
,∂w∂[(pn−yn)x(n)]=x(n)(∇wpn)⊤=pn(1−pn)x(n)x(n)⊤,.d×d.x(n) and yn do not depend on ;w; for a scalar c(w) times a constant vector ,a, entry (i,j) of the Jacobian is ,ai∂c/∂wj, which is .a(∇wc)⊤.
,∑nDnnx(n)x(n)⊤=X⊤DX, with .Dnn=pn(1−pn).,(X⊤DX)ij=∑nXniDnnXnj, which is entry (i,j) of the weighted sum of outer products, because .Xni=xi(n).
v⊤X⊤DXv=∑npn(1−pn)(x(n)⊤v)2≥0 for every .v∈Rd.Entry n of Xv is ,x(n)⊤v,D weights its square by ,pn(1−pn), and every weight is positive because .0<pn<1.
∇w2L=N1X⊤DX with ,D=diag(p⊙(1−p)),;p=σ(Xw); it is positive semidefinite, so L is convexA function whose Hessian is positive semidefinite everywhere is convex, so every stationary point is a global minimum and gradient descent cannot be trapped in a worse one. With independent columns the inequality in step 5 is strict for v=0 and L is strictly convex. Unlike Problem 2's Hessian, this one changes with w through .D.
Problem 8
Softmax regression: ,Z=XW+1b⊤,S the row-wise softmax of ,Z,Y one-hot rows, .L=−N1∑n,iYnilogSni. Compute ,∇ZL,∇WL and ,∇bL, with shapes.
For one example with logits ,z∈Rk, softmax s and one-hot target y at class :c:,ℓ=−zc+log∑iezi, so .∇zℓ=s−y.;logsc=zc−log∑iezi; the log-sum-exp differentiates to ,ezj/∑iezi=sj, and zc to 1 exactly at ,j=c, which is .yj. The next page derives this result three ways.
,∇ZL=N1(S−Y),.N×k.Row n of Z feeds only ,ℓn, through its own row of the softmax, and the mean puts N1 on each ;ℓn; row n is step 1 for example .n.
,Zni=∑jXnjWji+bi, so .∂Wji∂L=∑n∂Zni∂LXnj.Wji sits in column i of ,Z, in every row ,n, with coefficient :Xnj: the loss reaches it through all N examples, so their contributions add.
.∑nXnj(∇ZL)ni=(X⊤∇ZL)ji.,(X⊤)jn=Xnj, and the sum over n is the definition of the matrix product.
,∂L/∂bi=∑n(∇ZL)ni, so .∇bL=(∇ZL)⊤1.1b⊤ adds bi to every row of column i with coefficient ,1, and (∇ZL)⊤1 sums each column of .∇ZL.
∇WL=N1X⊤(S−Y) ();d×k);∇bL=N1(S−Y)⊤1 ()k)(d×N)(N×k)=d×k and ,(k×N)(N×1)=k×1, the shapes of W and .b. Column i of ∇WL is ,N1X⊤(S:,i−Y:,i), Problem 6's form once per class, with the softmax column in place of .σ(Xw).
Problem 9
Take k=2 and no bias, so Z=XW with columns .w1,w2. Show that Sn1=σ(x(n)⊤(w1−w2)) and that the loss is the logistic loss of Problem 6 with w=w1−w2 and .yn=Yn1. What does that say about ?W?
For ,z∈R2,.softmax(z)1=ez1+ez2ez1=1+e−(z1−z2)1=σ(z1−z2).Divide the numerator and the denominator by .ez1.
.softmax(z)2=1−σ(z1−z2).The two entries of a softmax sum to .1.
Row n of XW is ,(x(n)⊤w1,x(n)⊤w2), so .z1−z2=x(n)⊤(w1−w2).Column i of XW is ,Xwi, and x(n)⊤ distributes over the difference.
With yn=Yn1 and ,Yn2=1−yn,−∑iYnilogSni=−[ynlogpn+(1−yn)log(1−pn)] with ,pn=σ(x(n)⊤w),.w=w1−w2.A one-hot row with two classes is ;(yn,1−yn); steps 1 to 3 give Sn1=pn and .Sn2=1−pn.
,Sn1=σ(x(n)⊤(w1−w2)), so two-class softmax regression is logistic regression with w=w1−w2Only the difference w1−w2 is determined by the data: adding the same vector to both columns leaves every probability, and so the loss, unchanged. Two-class softmax regression therefore has a whole set of minimisers where logistic regression may have one; a ridge penalty on W picks the one with .w2=−w1. The next page meets the same shift invariance in the logits.
Problem 10
Newton's method updates .wnew=w−(∇w2L)−1∇wL. Write the step for logistic regression and show that the 1/N cancels.
∇wL=N1X⊤(p−y) and ,∇w2L=N1X⊤DX, with .p=σ(Xw).Problems 6 and 7.
.(∇w2L)−1∇wL=N(X⊤DX)−1N1X⊤(p−y).(cA)−1=c−1A−1 for a scalar .c=0. The inverse exists when the columns of X are independent, because then X⊤DX is positive definite (Problem 7).
wnew=w−(X⊤DX)−1X⊤(p−y)The N and the N1 cancel, so Newton's step is the same for the mean loss and the summed loss, while a gradient step changes by a factor of N between them. Each step solves a weighted least-squares problem with weights ,D, recomputed from the new :p: this is why the method is called iteratively reweighted least squares.
Where this goes wrong
1. Dropping the 2/N from the mean-squared-error gradient
Many texts write the least-squares loss as ,21∥Xw−y∥2, whose gradient carries no constant, and the clean form is the one that gets remembered.
L(w)=N1∥Xw−y∥2Right so far: the mean squared error as defined on this page.
“The gradient of a least-squares loss is .X⊤(Xw−y).”The shortcut that causes the mistake: the gradient of ,21∥Xw−y∥2, recalled without the loss it belongs to.
∇wL=X⊤(Xw−y)The gradient of the mean squared error is N2X⊤(Xw−y) (Problem 1). Setting either to zero gives the same normal equations, which hides the slip; but a gradient step with this formula is N/2 times too large, so the learning rate has to absorb the factor, and it changes whenever the batch size does.
2. Ridge closed form without the N
The ridge formula (X⊤X+λI)−1X⊤y is printed in every textbook, and a loss written as a mean looks like the same loss.
Lλ(w)=N1∥Xw−y∥2+λ∥w∥2Right so far: a mean data term plus a penalty, the form most libraries document.
“The ridge solution is .(X⊤X+λI)−1X⊤y.”The shortcut that causes the mistake: the textbook formula belongs to the summed loss ,∥Xw−y∥2+λ∥w∥2, which has no 1/N on the data term.
w∗=(X⊤X+λI)−1X⊤yFor the mean loss the minimiser is (X⊤X+NλI)−1X⊤y (Problem 3): clearing the 1/N multiplies the penalty by .N. With the formula above the penalty is N times weaker than the one written down, and the effective regularisation shrinks as the dataset grows.
3. Logistic gradient with an extra p(1 − p)
A chain rule through a sigmoid output always produces a σ′ factor, and with a squared-error loss that factor really does stay in the gradient.
∂pn/∂tn=pn(1−pn)Right so far: Problem 4, at the logit .tn=x(n)⊤w.
“The derivative of the loss with respect to the prediction is the error ;pn−yn; multiply by .σ′.”The analogy that causes the mistake: p−y is the derivative of the squared error .21(p−y)2. For cross-entropy the derivative is (p−y)/(p(1−p)) (Problem 5, step 2), and its denominator cancels the .σ′.
∇wL=N1X⊤[(p−y)⊙p⊙(1−p)]This is the gradient of the mean of ,21(σ(x(n)⊤w)−yn)2, a different loss and not a convex one. The correct gradient is N1X⊤(p−y) (Problem 6). The symptom: an example that is confidently wrong, with pn near 1 when ,yn=0, gets a factor pn(1−pn) near ,0, so learning stalls exactly where the error is largest.
4. Hessian built as X D Xᵀ
Each example contributes ,pn(1−pn)x(n)x(n)⊤, and an outer product xx⊤ looks as if it should become XX⊤ for the whole batch.
∇w2L=N1∑npn(1−pn)x(n)x(n)⊤Right so far: Problem 7, step 3, summed over the examples.
“Stack the x(n) into ,X, and the sum of outer products becomes .XDX⊤.”The analogy that causes the mistake: treating x(n) as a column of ,X, when with rows as examples x(n)⊤ is a row of .X.
∇w2L=N1XDX⊤It is ,N×N, a matrix over pairs of examples, where the Hessian is ,d×d, over pairs of weights. A sum of outer products of the rows of X is X⊤DX (Problem 7, step 4). When N=d the shapes agree, and Newton's step (Problem 10) runs with the wrong matrix.
5. Softmax-regression gradient in the k × d layout
PyTorch's nn.Linear stores its weight as output features by input features and computes .XW⊤+1b⊤. In that layout the weight gradient is ,(∇ZL)⊤X, and the formula travels with the reader to code where W is .d×k.
,∇ZL=N1(S−Y),N×kRight so far: Problem 8, step 2.
“The weight gradient is the upstream gradient, transposed, times the input.”The habit that causes the mistake: the rule for ,Z=XW⊤+1b⊤, where W is ,k×d, applied to .Z=XW+1b⊤.
∇WL=N1(S−Y)⊤XIt is ,k×d, the transpose of W's .d×k. In ,Z=XW,Wji multiplies Xnj into ,Zni, so the gradient is N1X⊤(S−Y) (Problem 8). The entries are the right numbers transposed; when d=k the update runs and silently applies the transpose.
Print this set: regression-gradients.pdf (problems, answers, and worked solutions on separate pages).