Logistic Regression: Deriving the Sigmoid and the Cross Entropy from Maximum Likelihood
Prerequisite:Linear Regression and Least Squares: Reading the Normal Equations as an Orthogonal Projection
0. Key points
Section titled “0. Key points”- In a classification problem the output is a label, or . Fitting least squares directly to such data produces predictions outside the range of a probability, and lets far-away points that ought to be irrelevant to the decision drag the boundary around.
- To turn the linear score into a probability we use the sigmoid function . This is not an arbitrary choice: it is equivalent to assuming that the log odds (the logit) is linear.
- The loss function is not something we pick by hand. Writing down the maximum likelihood estimate for a Bernoulli model, the negative log likelihood is the cross entropy error.
- The gradient takes the surprisingly simple form . The derivative of the sigmoid cancels against the derivative of the cross entropy, and this cancellation is what keeps learning fast.
- The Hessian is , so is convex. But the stationarity condition is a transcendental equation: unlike linear regression, there is no closed-form solution. Hence one has no option but to search numerically using derivatives, which leads directly to gradient descent in the next chapter.
- When the data are linearly separable the maximum likelihood estimate fails to exist and the weights diverge. Adding regularisation restores existence and uniqueness of the minimiser, and this coincides with MAP estimation under a Gaussian prior.
1. Motivation: what breaks when we fit a line to labels 0 and 1
Section titled “1. Motivation: what breaks when we fit a line to labels 0 and 1”1.1. The classification problem
Section titled “1.1. The classification problem”In Linear regression and least squares the output was a real number, as when predicting weight from height. Most problems one actually wants to solve, however, are not of that kind.
- Is this email spam or not?
- Does a patient with this set of test values have the disease or not?
- Is the animal in this image a cat or not?
In each case the output is a yes/no choice. Such a problem is called a binary classification problem. Mathematically, we formulate it as predicting a label from a feature vector .
A naive question arises at once. Labels are, after all, numbers, so why not simply use linear regression? Fit by least squares and declare “yes” when and “no” otherwise. This looks plausible. Trying it out makes clear what goes wrong.
1.2. Least squares applied to labels
Section titled “1.2. Least squares applied to 0/10/10/1 labels”Consider predicting the pass/fail outcome of an examination ( means pass) from the study time in hours, with the following four data points.
| 1 | 2 | 3 | 4 | |
|---|---|---|---|---|
| 0 | 0 | 1 | 1 |
Fit by least squares. Since , , and , we get
The decision boundary is , that is , and all four points are classified correctly. So far so good. But look at the predicted values themselves: and . We have obtained a negative probability and a probability exceeding . “Your probability of passing is ” carries no meaning.
The trouble is not merely cosmetic. Add the point — someone studied for 20 hours and passed, an entirely unremarkable observation. Now , , and , so
The boundary moves to , that is . Consequently the point now has , so a point that had been classified correctly becomes misclassified.
Why does this happen? The squared error penalises for being far from . From the point of view of classification, however, the point at is equally correct whether or : both are comfortably on the “pass” side. The squared error counts being too deep on the correct side as an error, and flattens the line in order to reduce it. In short, the squared error is the wrong objective for classification.
1.3. What we need
Section titled “1.3. What we need”Two requirements now stand out.
- A mechanism squeezing the output into , so that predictions can be read as probabilities.
- A loss function derived from a probability model, so that the difference between “answered and was right” and “answered and was right” is measured by a non-arbitrary criterion.
Logistic regression supplies both. The sigmoid function (Definition 3.1) answers the first, and the cross entropy error coming from maximum likelihood (Definition 4.1) answers the second. Only at the last stage, when we come to minimise that loss, does differentiation become genuinely indispensable: linear regression needed only the normal equations, a system of linear equations, whereas logistic regression admits no closed-form solution (Remark 5.4).
flowchart LR A["feature vector x"] --> B["linear score z = w·x"] B --> C["probability p = sigmoid(z)"] C --> D["negative log likelihood = cross entropy error L"] D --> E["gradient grad L = sum of (p - y) x"] E --> F["update weights w"] F -.-> B
2. Preliminaries: notation and assumptions
Section titled “2. Preliminaries: notation and assumptions”Throughout, the data consist of pairs with and . The intercept (bias) is absorbed into the feature vector: the first component of every is taken to be , so that the corresponding weight plays the role of the intercept. With this convention no intercept appears explicitly and every formula below is uniformly of the form .
Let the design matrix be the matrix whose -th row is (the same notation as the design matrix(Definition 2.1)[Linear Regression and Least Squares] of Linear regression and least squares). We write for the vector of labels.
Probabilistically, we assume that the are conditionally independent given the . We do not model the distribution of itself in any way (we return to this point in Example 3.4). For the basics of random variables and expectation see Random variables and expectation.
Differentiation with respect to a vector means collecting the partial derivatives, , and the Hessian is . For details see the definition of the Hessian(Definition 7.3)[多変数関数の微分と偏微分] in Differentiation of functions of several variables. For a symmetric matrix , we write for positive semidefiniteness and for positive definiteness.
3. Turning outputs into probabilities: the sigmoid and the logit
Section titled “3. Turning outputs into probabilities: the sigmoid and the logit”3.1. The sigmoid function
Section titled “3.1. The sigmoid function”Definition 3.1(Sigmoid function (standard logistic function))
Define by
This function is called the sigmoid function, or the standard logistic function.
The name comes from the shape of the graph, an (from the stem of the Greek letter sigma, plus eides, “shaped like”). It was originally introduced by Verhulst in 1838 as the solution of the differential equation describing population growth. Note that this differential equation is precisely property (3) below.
Proposition 3.2(Basic properties of the sigmoid)
For the function of Definition 3.1, the following hold.
- For every we have ; moreover is of class on , strictly increasing, and , .
- For every , . In particular .
- For every , .
- is a bijection, and its inverse is for .
Proof(Proposition 3.2)
(1) For every we have , so and therefore . The map is and the denominator never vanishes, so the quotient is as well. Strict monotonicity follows from , proved in (3). As for the limits: as we have , hence ; as we have , hence .
(2) By definition . On the other hand
and multiplying numerator and denominator by turns this into , which is . Setting gives , that is .
(3) Apply the chain rule to . The outer derivative is and the derivative of the inner function is , so
On the other hand, the intermediate computation in (2) gives , whence
and the two agree. Finally, by (2), so . By (1) both and , so .
(4) By (3) the function is strictly increasing, hence injective. By (1) it is continuous, its range is contained in , and its limits at the two ends are and , so by the intermediate value theorem it attains every value in . Hence is a bijection. The inverse is found by solving for . Taking reciprocals gives , that is . Taking logarithms gives , hence .
Property (3) is the identity used most often in this article. The fact that the derivative of the sigmoid is a polynomial in the sigmoid itself is what will make the gradient computation come out clean (Theorem 5.1).
3.2. Why this function — the logit and Bayes’ theorem
Section titled “3.2. Why this function — the logit and Bayes’ theorem”There are plenty of smooth increasing functions with values in ; the cumulative distribution function of the standard normal would do, and the resulting model is called probit regression. So why the sigmoid? The answer lies in part (4) of Proposition 3.2.
Definition 3.3(Odds and logit)
For , the quantity is called the odds of the probability , and its logarithm
is called the logit, or the log odds. By Proposition 3.2 (4) we have .
The odds is the ratio of the number of favourable cases to the number of unfavourable ones. It is the same usage as “3 to 1” in horse racing or sport: for the odds are , that is “3 to 1”. A probability is confined to the bounded interval , whereas the odds ranges over and its logarithm, the logit, over all of . The role of the logit is to convert a probability into a quantity one may move linearly.
Consequently, setting is exactly equivalent to applying the logit to both sides:
So the assumption behind logistic regression is neither that the probability is linear nor that it has a sigmoid shape; it is the single statement that the log odds is a linear combination of the features. The sigmoid is nothing but that assumption solved for the probability.
The assumption does hold in natural situations, as the following example shows.
Example 3.4(The sigmoid emerges from two normal distributions)
Let the prior probabilities of the classes be and , and let be the class-conditional densities of the features. By Bayes' theorem(Theorem 2.2)[確率論とベイズ統計],
The middle step is nothing more than dividing numerator and denominator by and using . Thus the sigmoid appears with no assumption at all, because is precisely the log odds.
What remains is the question whether is an affine function of . If both classes are normal with a common (invertible) covariance matrix , say and , the normalising constants cancel and
In the second line we used that the quadratic term comes out of both brackets and cancels (it would not cancel if the covariance matrices differed). What is left is affine in .
Let us put in numbers in one dimension. With , , variance and ,
The boundary is at , the midpoint of the two means. Logistic regression may be read as the model that estimates the coefficients of this directly, without passing through or .
Example 3.4 says that assuming normal distributions leads to logistic regression, but the converse fails. Many class-conditional distributions besides the normal give linear log odds (most of the exponential family does), and logistic regression covers all of them at once. The stance of modelling directly without ever building is called a discriminative model. The comparison with generative models is taken up in The role of probability and Bayesian statistics.
3.3. The logistic regression model and how to read its coefficients
Section titled “3.3. The logistic regression model and how to read its coefficients”Definition 3.6(Logistic regression model)
For a parameter , the model defining the conditional distribution of the label given a feature by
is called the logistic regression model. We call the logit or the score, and the predicted probability. The two formulas combine into
(substituting gives , and gives ). That is, follows a Bernoulli distribution with success probability .
Example 3.7(A coefficient is a multiplier of the odds)
Suppose a model predicting the probability of passing from study time has been estimated as . How should the coefficient be read?
The correct reading is: increasing by increases the log odds by , that is, multiplies the odds by . Let us check.
- : , , odds .
- : , , odds . The odds ratio is .
- : , , odds .
- : , , odds . The odds ratio is again .
The odds ratio is constant everywhere, but the increase in probability is not. From the probability moves a great deal, (a gain of ), whereas from it moves only (). Where the probability is already close to , tripling the odds barely raises it. Reading the coefficient as “raises the probability by ” is simply wrong.
4. Where the loss comes from: maximum likelihood and the cross entropy error
Section titled “4. Where the loss comes from: maximum likelihood and the cross entropy error”4.1. The likelihood
Section titled “4.1. The likelihood”Definition 3.6 writes the data-generating rule as a probability. The standard principle for fixing the parameters of such a model is maximum likelihood: choose the parameter that makes the data at hand as probable as possible.
Write . By the conditional independence assumption of §2, the joint probability of the observed labels — the likelihood — is a product:
A product is awkward, so we take logarithms. Since is strictly increasing, the maximisers of and of coincide exactly. Flipping the sign, as is customary in optimisation, produces the following quantity.
Definition 4.1(Cross entropy error (negative log likelihood))
For data and the model of Definition 3.6, writing , the quantity
is called the cross entropy error, or the negative log likelihood. Since (Proposition 3.2 (1)) the logarithms are always defined, and .
4.2. The name “cross entropy”
Section titled “4.2. The name “cross entropy””The name comes from information theory. For two probability distributions on a finite set, is called their cross entropy. The -th term of Definition 4.1 is exactly the cross entropy between the distribution determined by the label, (since is or , this is a distribution concentrated at a point), and the model distribution .
Moreover there is the decomposition , and here is a point mass, so its entropy is . Therefore
The information-theoretic reading is thus that lowering the cross entropy error is the same as bringing the model’s predictive distribution closer to the distribution of the observed labels.
Proposition 4.2(Equivalence of maximum likelihood and cross entropy minimisation)
Let be the likelihood above and the cross entropy error of Definition 4.1. For every we have , and consequently, as sets,
(the equality holds including the case where both sides are empty).
Proof(Proposition 4.2)
Every factor of is strictly positive by Proposition 3.2 (1), so and its logarithm exists. The logarithm of a product is the sum of the logarithms, so
The map is a strictly decreasing bijection of , so (together with the monotonicity of ) the inequalities and are equivalent. Hence the set of maximisers of and the set of minimisers of coincide.
In other words, a loss function is not designed but derived from a probability model. One may restate the failure of the squared error in §1.2 by saying that the squared error is the negative log likelihood of a different model, one in which the output is normally distributed (maximum likelihood under Gaussian noise(Proposition 3.3)[確率論とベイズ統計]). Labels taking the values and are not normally distributed.
4.3. Solving the simplest case
Section titled “4.3. Solving the simplest case”Example 4.3(The intercept-only model can be solved explicitly)
Consider a model with no features, only an intercept: with . Then is a constant independent of . If of the observations have , then
Differentiate. By Proposition 3.2 (3) we have , and likewise . Hence
The equation is equivalent to . If then , so by Proposition 3.2 (4) there is a unique solution,
For instance with and we get , so the predicted probability is , which is the empirical rate of positives itself. Maximum likelihood returns the obvious answer, as it should.
If, on the other hand, or , then lies outside and has no solution. For the loss tends to as but never attains it: the maximum likelihood estimate does not exist. This is the simplest instance of Theorem 6.3.
5. Differentiation becomes necessary: the gradient and its meaning
Section titled “5. Differentiation becomes necessary: the gradient and its meaning”5.1. The gradient formula
Section titled “5.1. The gradient formula”In Example 4.3 there was a single parameter, so we could differentiate and solve. What happens for general ? First we compute the gradient.
Theorem 5.1(Gradient of the cross entropy error)
Fix and arbitrarily, let be the cross entropy error of Definition 4.1, and put . Then is of class on and
where is the design matrix whose -th row is and .
Proof(Theorem 5.1)
Put and . Each is affine in hence , is (Proposition 3.2 (1)), and is on with ; so , being a finite sum of compositions of these, is .
Write the -th term as and apply the chain rule along .
Step 1: differentiate with respect to .
Along the way we put the fractions over the common denominator and used that and cancel in the numerator.
Step 2: differentiate with respect to . By Proposition 3.2 (3), .
Step 3: differentiate with respect to . From we get .
Multiplying the three, the denominator of Step 1 cancels against the factor of Step 2:
The cancellation is legitimate because , which follows from (Proposition 3.2 (1)). Summing over and collecting gives
Finally, since is the -th row of , we have (the columns of are the , so multiplying by a vector forms a linear combination of those columns).
This formula looks just like the one for linear regression, whose least squares gradient was . The only difference is that the prediction has changed from to . The structure — weight the residual (prediction minus observation) by the features and add up — is shared.
Corollary 5.2(Mean calibration of a model with an intercept)
Suppose the model contains an intercept, that is, for some we have for all . Then every satisfying obeys
That is, the mean predicted probability equals the proportion of positives in the data.
Proof(Corollary 5.2)
By Theorem 5.1 the -th component of is . By hypothesis , so this equals . Since , this component vanishes as well, that is . Dividing both sides by gives the claim.
Corollary 5.2 guarantees that a maximum-likelihood logistic regression is “right on average”. If it assigns an average probability of to 100 people, then exactly 30 of them were positives. Example 4.3 is nothing but the case of this corollary.
5.2. What the clean cancellation means
Section titled “5.2. What the clean cancellation means”The cancellation in the proof of Theorem 5.1 is no accident: the sigmoid and the cross entropy are a pair chosen to be combined that way. Seeing what happens with the squared error instead makes the point clear.
Example 5.3(With squared error the gradient vanishes, and convexity is lost too)
Using the squared error with the same model changes only Step 1 of the proof of Theorem 5.1, to ; the factor from Step 2 then survives uncancelled:
To see what the extra factor does, take a single point that is “confidently wrong”: , , , . Then , so
- cross entropy gradient: ;
- squared error gradient: .
The ratio is about . At the point where the model is most badly wrong, the squared error learns essentially nothing. The reason is that the sigmoid saturates and ; this is the simplest form of the phenomenon known as vanishing gradients.
Worse still, this is not even convex. In the same one-point setting, put , so that . Using (Proposition 3.2 (2),(3)),
Since , the sign of is the sign of , that is, it depends on whether . At (i.e. ) we get , whereas at (i.e. ) we get . Convexity flips across the inflection point .
At the same single point the cross entropy is , with and , so it is strictly convex. Moreover as : the gradient does not vanish.
5.3. There is no closed-form solution
Section titled “5.3. There is no closed-form solution”Now that we have the gradient, the maximum likelihood estimate must satisfy the stationarity condition
(where acts componentwise). This is the decisive parting of the ways from linear regression.
The stationarity condition for linear regression is the normal equation (the normal equation(Theorem 3.3)[Linear Regression and Least Squares]), a system of linear equations in . If is invertible, we may write , obtained by finitely many arithmetic operations.
The stationarity condition for logistic regression, by contrast, is a transcendental equation mixing exponentials with polynomials. Even in the case with it reads
whose left-hand side is an elementary function of , yet no general formula solving it for in elementary functions is known (apart from special cases that reduce to and can be solved as in Example 4.3). A rigorous proof that no elementary closed form exists belongs to differential Galois theory and we do not enter into it here, but the practical consequence is plain: we must give up on solving by symbolic manipulation and search numerically instead.
And when searching numerically, the only local information telling us, from the current point , which way to move so that decreases is the gradient . Here differentiation ceases to be a computational device and becomes a compass for search. The method that actually runs this search is gradient descent (Definition 4.1[勾配降下法]), and the machinery for computing gradients efficiently in multilayer models is described in Neural networks and backpropagation.
5.4. A numerical example
Section titled “5.4. A numerical example”Example 5.5(Running one gradient step by hand)
Fit the data of §1.2 ( with ) with an intercept, so that and .
Initial point . Since , we have (Proposition 3.2 (2)). The loss is
The residuals are , so by Theorem 5.1
The intercept component vanishes exactly as Corollary 5.2 predicts, because . The slope component is negative, so increasing decreases the loss.
One step. With learning rate we set . Then and , giving
Indeed the loss has decreased from . The new gradient, from , is
This time the intercept component is positive. Raising only the slope pushed all the predictions upward and broke the mean calibration. The next step will therefore lower the intercept while raising the slope.
Turning the computation above into code gives the following. Following the remark in §4.2, the loss is collapsed into the form and then rewritten as to avoid overflow.
import numpy as np
def softplus(z): # a safe computation of log(1 + exp(z)) return np.maximum(z, 0.0) + np.log1p(np.exp(-np.abs(z)))
def loss(w, X, y): z = X @ w return float(np.sum(softplus(z) - y * z))
def grad(w, X, y): # the gradient formula verbatim mu = 1.0 / (1.0 + np.exp(-(X @ w))) return X.T @ (mu - y)
X = np.array([[1.0, 1.0], [1.0, 2.0], [1.0, 3.0], [1.0, 4.0]])y = np.array([0.0, 0.0, 1.0, 1.0])
w = np.zeros(2)print(loss(w, X, y), grad(w, X, y)) # 2.772588722239781 [ 0. -2.]
for _ in range(3): w = w - 0.1 * grad(w, X, y) print(w, loss(w, X, y))The losses printed decrease monotonically: .
6. Convexity: why the search works, and when it does not
Section titled “6. Convexity: why the search works, and when it does not”Having decided to search numerically, the next thing to check is whether the search can find anything. For a general function, a point where the gradient vanishes may be a local minimum, a local maximum or a saddle point. The cross entropy error, however, has a good property.
6.1. The Hessian and convexity
Section titled “6.1. The Hessian and convexity”Theorem 6.1(Convexity of the cross entropy error)
In the setting of Theorem 5.1, put . Then
This matrix is positive semidefinite for every , and consequently is a convex function on . If moreover (the columns of are linearly independent), then for every and is strictly convex.
Proof(Theorem 6.1)
Computation of the Hessian. By Theorem 5.1, . The are constants, so differentiating once more with respect to only the contribute:
The second equality is the chain rule and the third uses Proposition 3.2 (3) together with . Since is the entry of the matrix , in matrix form . As the -th row of is , this equals .
Positive semidefiniteness. For any ,
Each summand is nonnegative because by Proposition 3.2 (1), hence , and .
Convexity. Take arbitrary and put and . Since is (Theorem 5.1), is on , and by the chain rule . A function of one variable with nonnegative second derivative is convex, so is convex on and , that is,
As were arbitrary, is convex.
Strict convexity. Assume and let . Suppose in the identity above. Since all summands are nonnegative, each must vanish, that is . As , we get for every , which means . Since , the kernel of is , so , a contradiction. Hence implies , that is . In that case the function above has , so is strictly convex and therefore so is .
Corollary 6.2(Stationary points are global minima)
In the setting of Theorem 6.1, if satisfies , then is a global minimiser of . Conversely, every global minimiser is a stationary point.
Proof(Corollary 6.2)
Take any and put and . Since is , Taylor’s theorem in one variable with Lagrange remainder provides with
Here , , by hypothesis, and by the positive semidefiniteness in Theorem 6.1. Therefore for every . The converse follows because is differentiable, so its gradient vanishes at a global minimum (Fermat’s theorem). For Taylor’s theorem see Theorem 5.3[Mean Value Theorems and Taylor's Theorem] in The mean value theorem and Taylor’s theorem.
This is why it is legitimate to search using the gradient alone: there is no risk of being trapped in a local minimum, and wherever the gradient vanishes is the answer. Loss functions in deep learning are generally not convex, so this guarantee is a considerable advantage of logistic regression.
6.2. When the data are linearly separable the estimate does not exist
Section titled “6.2. When the data are linearly separable the estimate does not exist”Convexity guarantees that whatever is found is globally optimal; it does not guarantee that anything is found. Indeed, in the following common situation there is no minimiser.
Theorem 6.3(No maximum likelihood estimate under linear separability)
Suppose the data with are strictly linearly separable, that is, there exists a vector such that
for every . Then, for the function of Definition 4.1,
but this infimum is not attained. Moreover every sequence with satisfies .
Proof(Theorem 6.3)
(a) . By Proposition 3.2 (1) we have , so a term with , namely , is strictly positive because , and a term with , namely , is strictly positive because . Being a sum of strictly positive numbers, for every .
(b) . Let and put , so that gives . For a term with , Definition 3.1 gives , hence
(by hypothesis , so ). For a term with , Proposition 3.2 (2) gives , hence
(by hypothesis , so ). Being a finite sum, .
(c) The infimum and its non-attainment. By (a), ; by (b), comes arbitrarily close to ; hence . But by (a) no gives , so the infimum is not attained.
(d) Divergence. Suppose and were bounded. By the Bolzano–Weierstrass theorem some subsequence converges, . Since is continuous (indeed by Theorem 5.1), , contradicting (a). Hence is unbounded. Furthermore, if it had a bounded subsequence, that subsequence would also satisfy and the same argument would give a contradiction. Having no bounded subsequence is precisely .
Example 6.4(Watching the weights diverge)
The data of §1.2 ( with , and with ) are separated at . Taking in Theorem 6.3 gives , so the sign conditions hold. Computing the loss along gives the following.
| 1 | 2 | 5 | 10 | 20 | |
|---|---|---|---|---|---|
| 2.69 | 5.39 | 13.46 | 26.93 | 53.85 | |
| 1.3510 | 0.7237 | 0.1589 | 0.01343 | 0.0000908 |
Let us verify the value at by hand. Here , the two points with contribute and the two with contribute , so
The loss decreases monotonically towards while grows without bound. This is why running the gradient descent of Example 5.5 indefinitely makes the weights grow forever. The practical nuisance is that on separable data all predicted probabilities stick to or , so the information about how confident the model is gets lost. When the number of features exceeds the number of data points the data are almost always separable, so this is no exotic scenario.
6.3. Fixing it by regularisation
Section titled “6.3. Fixing it by regularisation”Theorem 6.5(Existence and uniqueness for L2-regularised maximum likelihood)
Let and, for the function of Definition 4.1, put
No condition whatsoever is imposed on the data (they may be separable, and need not have full column rank). Then has exactly one global minimiser on , and it is the unique solution of the equation
Proof(Theorem 6.5)
Existence. By part (a) of Theorem 6.3 we have , so . On the other hand, at we have and hence . Taking , for we get
Therefore the infimum of over coincides with its infimum over the closed ball . That ball is a bounded closed subset of , hence compact, and is continuous, so by the Weierstrass extreme value theorem the minimum is attained at some point . This is a global minimiser over all of .
Uniqueness. The Hessian of is , so . For any , positive semidefiniteness from Theorem 6.1 gives
Now suppose were both global minimisers. Both are stationary, so . Carrying out the same Taylor expansion as in the proof of Corollary 6.2 with , there is with
contradicting the minimality of . Hence the minimiser is unique.
The equation. By Theorem 5.1 and we have . As is convex (a sum of the convex function and the convex function ), the argument of Corollary 6.2 shows that being stationary and being a global minimiser are equivalent. Since the minimiser is unique, so is the solution of the stationarity equation.
Remark 6.6(Regularisation is a Gaussian prior)
The term in looks like an engineering trick that penalises large weights, but in the language of probability it has a natural interpretation. Regard itself as a random variable with prior . By Bayes’ theorem the posterior satisfies , so its negative logarithm is
This is exactly with . Minimising with regularisation is the same as MAP estimation (maximising the posterior) under a Gaussian prior. The correspondence also matches intuition: the smaller is — the more strongly we believe the weights lie near — the larger becomes. For details see L2 regularisation as MAP estimation under a Gaussian prior(Theorem 5.1)[確率論とベイズ統計] in The role of probability and Bayesian statistics.
7. Exercises
Section titled “7. Exercises”Exercise 7.1Easy
For the function of Definition 3.1, show that and verify that has an inflection point at .
Solution
By Proposition 3.2 (3), . Differentiating with respect to , by the product rule (or the chain rule),
By Proposition 3.2 (3) we have , so the sign of is determined solely by the sign of . Since is strictly increasing with (same proposition, (2)):
- for we have , so , that is (convex);
- at we have ;
- for we have , so (concave).
The concavity changes across , so is an inflection point. Since , the tangent there has slope , the maximal steepness of the sigmoid.
Exercise 7.2Standard
A model for the probability of contracting a certain disease has been estimated as , where is age measured in units of 10 years and equals for a smoker and for a non-smoker.
- Find the probability of contracting the disease for a 50-year-old () non-smoker.
- Holding everything else fixed, by what factor are the odds for a smoker larger than for a non-smoker?
- Under this model, being a smoker raises the odds by as much as how many years of ageing?
Solution
1. We have , so by Proposition 3.2 (2) the probability is , that is .
2. Changing from to increases the log odds by , so the odds are multiplied by . As in Example 3.7, this factor does not depend on the value of . The factor by which the probability changes, however, does depend on : at the probability only goes from to , a factor of .
3. We look for making the log odds of a smoker equal to those of an older non-smoker :
Since is measured in units of 10 years, this is 18.75 years. Checking numerically: a smoker with (aged 50) has , and a non-smoker with (aged 68.75) has ; they agree. Both have probability .
The reason this computation does not depend on the value of is that the log odds is a linear combination of and . In a model with an interaction term , the conversion depends on age and can no longer be expressed as a fixed number of years.
Exercise 7.3Standard
Relabel by . With , show that the function of Definition 4.1 can be written
then compute the gradient from this expression and check that it agrees with Theorem 5.1.
Solution
The expression. Treat the -th term case by case. If (so ), the term in Definition 4.1 is . From in Definition 3.1 we get .
If (so ), the term is . By Proposition 3.2 (2) we have , so
which is the same formula in both cases.
The gradient. Put , so the -th term is , and (divide numerator and denominator by to recover the definition of ). By the chain rule, , so
Agreement with Theorem 5.1 is checked case by case. If : . If : . Both equal , so the two expressions agree.
This form exhibits the structure “the larger the margin , the smaller the loss”, and puts the loss into a shape directly comparable with the hinge loss of support vector machines.
Exercise 7.4Hard
Let and consider of Theorem 6.5 together with its unique minimiser . Show that for every
and use this to deduce .
Solution
The inequality. Put and . Since is (Theorem 5.1) and is a polynomial, is and is . By Taylor’s theorem there is with
Since is a minimiser, and therefore . Also, as shown in the proof of Theorem 6.5, , and by Theorem 6.1, so
Substituting gives . This property is called -strong convexity; it is stronger than strict convexity, asserting that the function is bounded below by a quadratic.
The upper bound. Take in the inequality. As seen in the proof of Theorem 6.5, (there are terms with ), so
The last inequality uses , which follows from part (a) of Theorem 6.3 together with . Rearranging, , that is .
That the weights stay within this range even for linearly separable data is quantitative evidence that regularisation really does stop the divergence of Theorem 6.3. The bound tending to as is likewise consistent with the unregularised situation.
References
Section titled “References”- C. M. Bishop, Pattern Recognition and Machine Learning, Springer, 2006 — Chapter 4, “Linear Models for Classification”. §4.2 contains the derivation from a generative model given in Example 3.4, and §4.3 treats logistic regression and IRLS.
- T. Hastie, R. Tibshirani, J. Friedman, The Elements of Statistical Learning, 2nd ed., Springer, 2009 — Chapter 4, “Linear Methods for Classification”, including the unboundedness in the linearly separable case and the treatment of regularisation. Version made available by the authors.
- S. Boyd, L. Vandenberghe, Convex Optimization, Cambridge University Press, 2004 — Chapter 3 (convex functions and strong convexity) and Chapter 7 (maximum likelihood estimation as convex optimisation). Version made available by the authors.
- I. Goodfellow, Y. Bengio, A. Courville, Deep Learning, MIT Press, 2016 — Chapter 6, on the correspondence between the choice of output unit and the cross entropy loss, and on the gradient saturation discussed in Example 5.3. Public version.
- J. Berkson, “Application of the Logistic Function to Bio-Assay”, Journal of the American Statistical Association 39 (1944), 357–365 — the paper introducing the word “logit”.
- J. A. Nelder, R. W. M. Wedderburn, “Generalized Linear Models”, Journal of the Royal Statistical Society, Series A 135 (1972), 370–384 — the paper placing logistic regression within the framework of generalised linear models.
- Takuya Kubo, Data Kaiseki no tame no Tokei Modeling Nyumon (Introduction to Statistical Modelling for Data Analysis), Iwanami Shoten, 2012 (in Japanese) — a chapter treating logistic regression from the standpoint of generalised linear models. An accessible introduction from the practical side of statistical modelling.
Appendix: generalisation to several classes, and Newton’s method
Section titled “Appendix: generalisation to several classes, and Newton’s method”Softmax regression. When there are classes, provide a weight vector for each class and set
This is the softmax function. For , dividing numerator and denominator by gives , recovering the sigmoid (only differences of weights matter, so the parameters carry only blocks’ worth of freedom). Writing the label as a one-hot vector (with a in the -th component only), the loss is , again a cross entropy. The gradient has the same shape as in Theorem 5.1:
(see the gradient of softmax with cross entropy(Proposition 7.1)[ニューラルネットワークと逆伝播]). The point is that the structure producing the cancellation is preserved intact.
Newton’s method and IRLS. Since Theorem 6.1 gave us the Hessian as well, we can use second-order information rather than the gradient alone. The Newton update
can, after rearranging the right-hand side, be rewritten as with , which is the form of a weighted least squares problem. Because the weights are updated at every iteration, this is called IRLS (iteratively reweighted least squares). It converges quickly, but each iteration handles the inverse of a matrix (in practice, a system of linear equations), which becomes heavy for large . That difference in cost is one reason why first-order gradient descent is used in deep learning.
Report an error in this article ・Operated by: Mugen Giken LLC ・Pricing ・Terms ・Legal notice
© 2026 夢現技研合同会社 ・Feeding the text to an LLM is welcome. Code samples are MIT licensed.