🌏 中文版
Video status: Videos included. This article is written from the official MOOC handout 10_handout.pdf and transcripts of this lecture's four official videos, with formulas following the handout. The transcripts are machine transcripts made for this article (Whisper), not official captions, and no human has proofread them. The videos are taught in Mandarin; the slides are in English. Each section opens with its official video and the approximate time ranges. Page numbers refer to the number at the lower right of each slide (0/25 to 25/25), and wherever the text says "in the lecture" it is paraphrasing what is said in the video.
This is Foundations Lecture 10 in Reading NTU Hsuan-Tien Lin Machine Learning Foundations & Techniques. The Roadmap on page 1 of the handout places it under the third of the four big questions, "How Can Machines Learn?", right after Foundations Lecture 9: Linear Regression. The previous lecture takes up a single line on that page: linear regression hypotheses with squared error have the analytic solution . In the lecture, Lin opens by saying that Logistic Regression and Linear Regression differ by a single word, and this lecture is about what that word brings.
There are two differences. First, the output should be a probability between 0 and 1, but the data contains no probabilities, only whether something happened or not. Second, the error function that comes out of the derivation cannot be minimized in one step the way linear regression's can; you have to walk there step by step.
The prerequisites are the "set the gradient to zero" solution of linear regression, the update rule from Foundations Lecture 2: Perceptrons and PLA, the target distribution and pointwise error from Foundations Lecture 8: Noise and Error Measures, and partial derivatives, the chain rule, exponentials, and logarithms. After reading, you should be able to go from "pick the hypothesis with the largest likelihood" to the cross-entropy error on your own, compute its gradient with the chain rule, explain why there is no closed-form solution, derive the gradient descent update, and work out a few updates by hand on a small data set.
The derivation in this lecture runs in this order:
- Problem: the target function changes from to the probability .
- Hypothesis: the score goes through a logistic function .
- Error: maximum likelihood gives cross-entropy.
- Gradient: the chain rule gives .
- Stuck: the gradient-equals-zero equation cannot be solved.
- Algorithm: gradient descent, one step at a time toward the bottom of the valley.
Turning the target into a probability: soft binary classification and the logistic hypothesis
(Video 00:00–01:00 reviews the previous lecture, 01:00–04:03 covers the heart disease problem, 04:03–07:47 ideal and actual data, 07:47–13:06 the logistic hypothesis and the logistic function, and Fun Time follows.)
From "yes or no" to "how much risk"
Page 2 of the handout brings back the learning flow diagram with a hospital example: the input is a patient's age, gender, blood pressure, cholesterol level, and weight (the patient on the slide is 40 years old, male, blood pressure 130/85, cholesterol level 240, weight 70), and the output is "heart disease? yes". This is ordinary binary classification. Foundations Lecture 8 explained that noisy data is described by a target distribution , and that under the 0/1 error the ideal target function is
In other words, it looks at which side of one half the probability falls on. The handout notes that this choice is "because of classification err": what we care about is the fraction of mistakes. In the lecture, Lin adds that, to keep the figure simple, the box for the that generates the inputs is not drawn.
Page 3 changes one word of the problem: heart disease becomes heart attack, and the output changes from yes to "80% risk". In the lecture, Lin explains that the question a doctor often has to answer is how likely a heart attack (or a cancer recurrence) is some months from now, not merely whether it will happen. What we want to know is then the value itself, and the target function becomes
The handout calls this 'soft' binary classification: the output is no longer a hard circle or cross but a risk value.
The data we want and the data we can get
To learn an that outputs probabilities, the ideal data would attach a probability to every . The left column on page 4 of the handout calls this ideal (noiseless) data:
| ideal (noiseless) data | actual (noisy) data | |
|---|---|---|
| Example 1 | , drawn from | |
| Example 2 | , drawn from | |
| Example | , drawn from |
With the left column, things would be much like regression: find a hypothesis whose predictions at these points are close to 0.9, 0.2, and 0.6. But the left column is not available. In the lecture, Lin uses hospital records to explain: the record says whether the patient had a heart attack two or three months later, and nobody knows whether the probability was 0.9 or 0.2.
So all we have is the right column. The second slide of the same page rewrites the right column as numbers: with 1 for a circle and 0 for a cross, the three examples are , , and , each the outcome of "draw once from ; did a circle come up?" In the lecture, Lin reads this as: the actual data is a noisy version of the ideal data. We wanted 0.9 and got 1 after sampling; we wanted 0.2 and got 0; the third example has probability 0.6, larger than one half, yet the sample happened to land on the other side and gave 0, a rather large error.
The handout wraps up in one sentence: "same data as hard binary classification, different target function". The data has exactly the same form as in ordinary binary classification; what is to be learned is different. The question for the rest of the lecture is how to learn a hypothesis that outputs probabilities when all we have is circles and crosses.
The logistic hypothesis: pass the score through an S-shaped function
The first step of the hypothesis is the same as in earlier lectures (page 5). Write the patient's features as , where is the constant term, and compute a weighted "risk score":
Linear regression outputs directly, but can be any real number and we want a value between 0 and 1. The approach is to say that a higher score means higher risk, and then use an S-shaped function to convert the score to a probability. The handout calls the logistic function and writes the hypothesis as
In the figure on page 5 the horizontal axis is the score and the vertical axis runs from 0 to 1. The blue curve starts at the lower left hugging 0, climbs around , and approaches 1 to the right. In the lecture, Lin reads it this way: with a score of 1126, go to 1126 on the horizontal axis, look up to the curve, and read off the value to output; the same goes for a score of .
The formula of the logistic function
Page 6 gives the formula:
The second equality divides the numerator and denominator by . The handout lists three values, and the lecture checks them one by one:
- , exactly in the middle.
- As , using the right-hand form, , so . The lecture uses the left-hand form instead: the numerator and denominator both go to infinity and are about the same size, so the ratio goes to 1; Lin acknowledges that infinity divided by infinity needs a more rigorous definition mathematically.
- As , using the left-hand form, the numerator and the denominator approaches 1, so .
The handout describes it as a "smooth, monotonic, sigmoid function of ": smooth (differentiable everywhere), monotonic, and S-shaped. This article plugs in a few numbers to get a feel for how fast it changes:
| 0.0067 | 0.1192 | 0.2689 | 0.5 | 0.7311 | 0.8808 | 0.9933 |
The output changes fastest for scores between and , and beyond it is almost flat against 0 or 1. The table also shows a property that will be used later: and ; two scores placed symmetrically about zero have outputs that add up to 1.
Putting it together, logistic regression uses
to approximate the target function .
Fun Time: converting a probability back to circle or cross
Question (page 7): Consider any logistic hypothesis . 'Convert' it to a binary classification prediction by taking . What is the equivalent formula for the binary classification prediction?
- none of the above
Answer: 2. The handout's reason is that when , is exactly , so thresholding at is the same as thresholding the score at 0. Filling in the middle step: is strictly increasing, so if and only if , and if and only if .
Choice 1 puts the threshold at a score of , which corresponds to the probability ; that is, it says circle only when the probability exceeds 0.622. Choice 3 puts the threshold at a score of , corresponding to . Neither is the same as "more than one half".
The conclusion the lecture draws from this question is that a logistic hypothesis is really just a counterpart of the earlier binary classification hypothesis. An addition in this article: the boundary is still the hyperplane ; what the logistic hypothesis reports in addition is the probability that corresponds to how far the score is from 0.
Defining the error: from likelihood to cross-entropy
(Video 00:00–01:46 puts the three linear models side by side, 01:46–06:18 covers likelihood, 06:18–09:45 the symmetry of the logistic function and the product form, 09:45–14:47 the rearrangement into cross-entropy, and Fun Time follows.)
Three linear models, one error missing
Page 8 puts the three models learned so far together. All of them first compute the same linear score ; they differ in what happens to the score afterwards:
| linear classification | linear regression | logistic regression | |
|---|---|---|---|
| Hypothesis | |||
| Output function in the figure | step | slanted straight line | S-shaped curve |
| Error | 0/1 | squared | ? |
| The handout's reason | plausible (corresponds to small flipping noise) | friendly (easy to minimize) | to be decided |
In the lecture, Lin explains the icons: the box for linear classification shows a step-shaped sign; linear regression shows a slanted line, meaning the score is output unchanged (identity); logistic regression shows an S shape. The reason for the 0/1 error is that it is the most convincing, right or wrong; the reason for the squared error is that it leads to a clean algorithm. The third cell is still empty, and the handout asks "how to define for logistic regression?"
Likelihood: let h pretend to be f
Page 9 first spells out the relation between the target function and the target distribution. is equivalent to
because the probabilities of the two outcomes add up to 1.
Now consider a data set . What is the probability that generates this data? Each example is produced by first drawing and then drawing that label from ; the examples are independent, so the probability of the whole data set is a product:
Use the relation above to replace with and with :
But is unknown. The lecture's move is to let pretend to be for a moment: pretend is the function that generated the data and replace every in the expression with . That gives "how likely it is that generates the same data", a quantity called the likelihood:
The handout then makes two points:
- If , then probability using .
- The probability using is usually large. In the lecture, Lin explains that the data in hand really was generated by , so in hindsight the probability that generates this data should not be small, and says this is an intuition.
Put the two together: a good should have a large likelihood. So the choice on page 10 is
Among all hypotheses, pick the one with the largest likelihood as .
Working it once with the handout's three probabilities
What follows is an example made up for this article from the numbers on page 4 of the handout; it is not on the slides. Suppose there are only three examples, the true probabilities are , , and , and the labels drawn are circle, cross, cross. The part is the same for every hypothesis, so set it aside and compare only the product of the remaining three factors:
| Hypothesis outputs at the three points | Product | Value |
|---|---|---|
| itself: | 0.288 | |
| Close to : | 0.280 | |
| Says one half for everything: | 0.125 | |
| The opposite of : | 0.012 |
A hypothesis close to has a likelihood close to 's 0.288; a hypothesis that contradicts is left with a likelihood of only 0.012. That is what the handout's first point means.
An addition in this article, on something to watch for. If any function were allowed as a hypothesis, would have likelihood , higher than 's 0.288: it memorizes the labels it saw and states the probabilities with certainty. So for "the largest likelihood is close to " to hold, the hypothesis set has to be restricted (here to the form , with finite ) and there has to be enough data, the same condition under which the earlier lectures could go from "small " to "small ". The handout's word is "usually", not "always".
Symmetry: writing circles and crosses as one expression
The likelihood has two kinds of factors: for a circle and for a cross. Page 10 unifies them with a property of the logistic function. First verify the property:
The third equality multiplies the numerator and denominator by . For , this is what the handout writes as
The lecture calls this property symmetry and asks the audience to look at the S-shaped curve on the right of the slide and convince themselves it is true. An addition in this article, on what it means in the picture: the curve is symmetric about the point , and the heights at and add up to exactly 1.
So the cross factor can be written as , and the likelihood becomes
A circle has label and a cross has , so every factor is . The slide draws all the in gray, and in the lecture Lin explains why: when comparing different , everyone uses the same through , so this part is the same for every and does not affect which is larger. Dropping it leaves
The symbol "" means proportional to; the constant of proportionality is the product of those .
Take ln, add a minus sign, divide by N
Page 11 turns "maximize a product" into the familiar "minimize an average error" in four steps.
Step 1: replace with . Every logistic hypothesis is determined by , with :
Step 2: take ln. The lecture's reason is that every handled in earlier lectures was a sum, and products have not been handled; taking the logarithm turns the product into a sum, and since the logarithm is monotonic, the largest stays the largest. The natural logarithm is used to make differentiation convenient later.
Step 3: add a minus sign, then multiply by . Everything so far has been a minimization, so a minus sign turns the max into a min. The is gray on the slide; in the lecture, Lin says it is just a constant scaling that treats every equally and does not affect the optimal solution, and that it is put in to make the expression look like the earlier :
Step 4: substitute the formula for . , so
The lecture says the same thing: has its expression in the denominator, pulling it out of the logarithm produces another minus sign, and that cancels the minus sign in front. Substituting :
Each term in the sum depends on a single example; it is the pointwise error measure from Foundations Lecture 8. The handout calls it the cross-entropy error:
is its average over the examples. The summary on page 25 of the handout gives it another name, negative log likelihood, which is exactly the three operations just performed.
Back to the three-example calculation: itself gives , and the hypothesis that says one half for everything gives . A larger likelihood means a smaller error, with the ranking exactly reversed, so minimizing and maximizing the likelihood pick the same hypothesis.
The shape and the name of cross-entropy
The error is determined by the single number . means the sign of the score agrees with the label (as a classifier it is correct), and means it is wrong. This article computes a few values:
| err | 5.0067 | 2.1269 | 1.3133 | 0.6931 | 0.3133 | 0.1269 | 0.0067 |
Three observations. When the example is classified correctly, the farther the score is from 0 the closer the error gets to 0, but it is never exactly 0. At the error is , the price paid when the hypothesis says "fifty-fifty". On the wrong side, the error is almost as large as (5.0067 at ): the worse the mistake, the heavier the penalty, with no upper limit.
As for where the name comes from, the lecture says only that there are historical reasons, does not go into the details, and suggests that students with a reference book look it up. An addition in this article: a way of writing the error that makes the name visible, derived using only the formulas above. Relabel the examples as (circle) or (cross), and write :
- When , .
- When , .
The two cases combine into one line:
Fall 2024 HW4 Q1 tests exactly this equivalent form after relabeling, and the problem also explains that the name cross-entropy comes from the form .
Fun Time: four properties of cross-entropy
Question (page 12): The four statements below help us understand more about the cross-entropy error . Consider . Which statement is not true?
- For any , , and , .
- For any , , and , .
- When , .
- When , .
Answer: 2. The handout's answer is "1126, really? :-)", and it encourages plotting the curve of the error with respect to some fixed and a varying score ; after plotting, it is easy to see that the error is not bounded above and that the other three choices are correct. In the lecture, Lin jokes that a choice containing a strange number is usually the wrong one. The four choices are reasoned through one by one below, writing :
- Choice 1 is true. , so , and its is greater than 0.
- Choice 2 is false. Take (for example, in one dimension, , , ); then . Push further in the negative direction and the error can be as large as you like.
- Choice 3 is true. and the score have the same sign, so , , and .
- Choice 4 is true. and the score have opposite signs, so , , and , which certainly satisfies "".
The lecture singles out choices 3 and 4: a score of 0 is the switching point, with the error above on one side and held below on the other.
What the gradient looks like, and why there is no closed-form solution
(Video 00:00–01:38 covers the properties of , 01:38–07:28 derives the gradient with the chain rule, 07:28–10:30 explains why there is no closed-form solution, 10:30–14:12 revisits PLA and iterative optimization, and Fun Time follows.)
E_in is a valley
With in hand, what remains is finding the that minimizes it. The lecture first recalls why: this set of hypotheses has a finite VC dimension (see Foundations Lecture 7: The VC Dimension), so making small makes small too. Two minimization methods have been learned so far: the mistake-correcting approach of linear classification, and linear regression's "compute the gradient and find where it is zero". The latter applies to smooth, differentiable functions.
Page 13 says the of logistic regression is continuous, differentiable, twice-differentiable, and convex. A convex function looks like a valley, and the bottom of the valley is where the gradient is zero, so the goal is the same as in linear regression:
The handout does not prove "convex". In the lecture, Lin says the proof computes the matrix of second derivatives and confirms that it is positive definite, does not carry it out, and asks the audience to take it on trust for now. The check below is an addition in this article and is not on the slides; it uses the gradient derived in the subsection "Peeling the onion with the chain rule", and can be skipped on a first reading. Differentiating the gradient once more, with and , gives the matrix of second derivatives
For any vector , , and the coefficient in front is positive, so . This is positive semi-definiteness, which is already enough to guarantee that is convex. The "positive definite" mentioned in the lecture needs one more condition: the must span the whole -dimensional space, so that the expression above is strictly greater than 0 for every nonzero .
Peeling the onion with the chain rule
contains an , an , and . The lecture's attitude is not to be afraid: differentiation has no secret trick, and doing it one layer at a time and stringing the layers together is the chain rule. Page 14 first gives temporary names to the intermediate quantities:
The piece inside the exponential is called , and the whole piece inside the is called . In the lecture, Lin explains why shapes are used instead of A, B, C: thinking of them as a circle and a square makes it easier to remember that they are only temporary intermediate values.
The -th component of the gradient is the partial derivative with respect to . The chain rule splits it into three parentheses, which the lecture likens to peeling an onion from the outermost layer inward:
Each of the three parentheses is simple:
- The derivative of with respect to is .
- The derivative of with respect to : the constant 1 vanishes, and the derivative of is still .
- ; only the term of the sum contains , so the derivative is . The lecture reminds the audience not to drop the minus sign.
Substituting back:
The second equality merges the first two parentheses and replaces with . The merged is exactly the first form of the logistic function, which the lecture calls our new friend :
The is the same for every component; only the final changes with . Stacking the results for into a vector stacks the into :
How to read it: each example contributes a vector , multiplied by a weight between 0 and 1, , and everything is averaged. Page 15 of the handout calls it a "scaled -weighted sum of ".
An addition in this article, on what the weight means. By symmetry, , and is the probability the current hypothesis assigns to "this example appearing with its actual label". So the weight is the probability the hypothesis assigns to this label not appearing: the more surprised the hypothesis is, the louder this example speaks in the gradient.
Setting the gradient to zero cannot be solved
Now solve (page 15). When is a weighted sum the zero vector? The handout distinguishes two cases.
Case 1: all the weights are 0. approaches 0 only when its argument goes to , so every example needs . The handout writes this as "only if ", and the lecture adds that strictly speaking it has to go to positive infinity. means the label and the score have the same sign, so this classifies example correctly; for that to hold for every example, the data must be linearly separable. The lecture puts it the other way round: if the data is not linearly separable, then for any at least one example has below 0, and this route is closed.
Case 2: the weights are not all 0, but the weighted sum happens to cancel out. What has to be solved is then an equation in , and appears inside , so it is a non-linear equation of .
Compare with linear regression: there the gradient is , and setting it to zero gives a linear equation of the form "a matrix times equals some vector", which we know how to solve, so the answer comes in a single step. The equation here is not linear. The handout concludes "closed-form solution? no :-(". In the lecture, Lin says that, as far as Lin knows, there is no closed-form solution as neat as linear regression's.
Looking back at PLA: iterative optimization
If the answer cannot be reached in one step, go back and look for a method that corrects itself step by step, and that is PLA. Page 16 reviews PLA: start from some (say, the zero vector), and for :
- Find a mistake of , called , that is, .
- Correct it: .
When it stops, return the last . The same page merges the two steps into one: pick some , and then
The double square brackets are a boolean operation: 1 if the condition holds, 0 if it does not. If the chosen point is misclassified, the factor is 1 and is added as usual; if the chosen point is classified correctly, the factor is 0 and nothing is updated. The lecture asks the audience to confirm for themselves that this is the same as the original two steps.
Now split this expression into two parts:
is the direction of the update, and is how large a step to take in that direction. In the lecture, Lin says is a constant quietly slipped in here: PLA does not single out the step size, which amounts to always stepping 1, and its importance only shows up in the gradient descent section.
The handout's conclusion is "choice of and stopping condition defines iterative optimization approach". Different directions, different step sizes, and different stopping conditions give different iterative optimization methods. PLA is one of them, and gradient descent will be another.
Fun Time: who has the largest weight in the gradient
Question (page 17): Consider the gradient . That is, each example contributes to the gradient by an amount of . For any given , which example contributes the most amount to the gradient?
- the example with the smallest value
- the example with the largest value
- the example with the smallest value
- the example with the largest value
Answer: 1. The handout's reason is that is monotonic. Spelled out: is increasing, so the largest is the same as the largest , that is, the smallest .
Choice 2 is the example with the smallest weight, the one classified most correctly and most confidently. Choices 3 and 4 look only at the score and not at the label: a point with a very low score whose label is has a large positive and a small weight, so the score alone cannot decide.
The lecture's reading is this: the example with the smallest may have a very negative value, and negative means makes a mistake on this example, so the mistaken points get especially large weights. This resembles PLA's "pick a mistaken point and correct it": PLA looks at one mistake, while the gradient combines every point, whether its mistake is big or small.
An addition in this article: the question asks about the weight . The vector actually added into the gradient is , whose length is further multiplied by , so the point with the largest weight is not necessarily the point with the longest vector.
Gradient descent: which way each step goes and how far
(Video 00:00–03:45 covers rolling the ball downhill and the greedy choice, 03:45–09:26 the linear approximation and the best direction, 09:26–14:47 the choice of and the fixed learning rate, 14:47–16:48 the full algorithm, 16:48–17:54 Fun Time, and the summary follows.)
The greedy choice: the largest drop in one step
The skeleton of iterative optimization is (page 18): for , do , and when it stops, return the last . PLA's comes from mistake correction. The of logistic regression is a smooth valley, and the handout's idea is to "choose to get the ball roll 'downhill'": in the lecture, Lin asks the audience to imagine placing a ball somewhere on the slope (corresponding to some ) and letting it roll; where it reaches the bottom of the valley is where the gradient is zero.
To make the derivation easier, start with two assumptions:
- The direction has unit length, . In the lecture, Lin explains that all the information about how big a step to take goes into , and handles only the direction.
- The step size is positive.
For some given , the greedy approach picks the direction that makes drop the most in this step:
The picture given in the lecture: think of as a limit of the human body, a stride of at most 30 centimeters; you have to choose a place to put your foot on the circle of radius 30 centimeters centered on yourself. In practice this circle may live in a space of many dimensions.
Linear approximation: look only at a short segment
Page 19 points out that this problem is no simpler: it is "still non-linear optimization, now with constraints", the constraint being , and "not any easier than ".
The way out is to make it linear. In the lecture, Lin explains that the easy problems we have learned all involve linear expressions, and that any winding curve, looked at over a very short stretch, is no different from a short line segment. Mathematically this is the Taylor expansion. The one-dimensional version is ; the multi-dimensional version replaces the slope with the gradient and the displacement with :
The handout notes the condition: "if really small". The lecture's explanation: when the curve bends a lot, a long segment ends up far from the curve; the segment has to be short for the approximation to be good.
Replacing the original expression with the approximation gives the "approximate greedy approach":
is a constant that does not depend on ; is already given and positive, so it does not change which choice is smallest. The slide draws these two terms in gray. All that really has to be solved is:
The best direction is opposite to the gradient
When is the inner product of a unit vector with a known vector smallest? The lecture's analogy is two people who have quarrelled and keep as far apart as they can: the inner product is most negative when the directions are exactly opposite.
This article writes the step out in full. Let and let be the angle between the two vectors; then . The smallest value of is , reached at , that is, when points in the direction of . Then scale the length to 1 (page 20):
Now , and the approximation says drops by about . Substituting back into the update gives gradient descent: for small ,
The handout's comment on it is "a simple & popular optimization tool". The lecture adds that it can be used whenever the gradient can be computed.
η too small, too large, just right
With the direction settled, next comes . Page 21 compares three figures, all of the same valley:
| Figure | What it shows | The handout's comment |
|---|---|---|
| too small | many tiny stairs drawn down the left slope, descending slowly one stair at a time | too slow :-( |
| too large | a zigzag line jumping back and forth between the left and right slopes | too unstable :-( |
| just right | large steps where the slope is steep high up (labeled large ) and small steps near the bottom (labeled small ) | use changing |
The lecture describes the three cases as three ways of walking. Someone with a very small is conservative, crawling like a snail; they will get there eventually, only slowly. Someone with a very large believes they are walking on a short line segment, but with a big stride the linear approximation is no longer accurate, and they miss their footing and fall onto the opposite slope. Nothing guarantees that the landing point is lower; it might even be higher. Because the Taylor expansion no longer applies, nobody knows what happens after a very large step.
The idea of the third figure is that should change with the slope. The lecture's reasoning: where the slope is steep it is safe to stride a bit farther; where the slope is already gentle, a very large stride may carry you past the optimum in one go. This is a heuristic that feels reasonable, and the handout writes it as
The slope is the length of the gradient, and the step size should go up and down with it.
Fixed learning rate: cancelling the two lengths
Page 22 gives the simplest way to do this: make the step size proportional to the length of the gradient. The slide uses color to tell two 's apart: the original step size is red and the ratio is purple. Here the red one is written and the purple one (the subscript is this article's addition):
Substituting into the gradient descent update, the gradient lengths in the numerator and denominator cancel:
In the lecture, Lin says the ratio is named purple because it mixes the red and the blue gradient. The result is a simpler update: there is no need to normalize the gradient, just multiply it by a fixed . This is called the fixed learning rate, and the method is fixed learning rate gradient descent:
What is "fixed" is the ratio . The length actually stepped is , which still changes: a steep slope means a long step, and near the bottom of the valley the gradient approaches zero and the step shrinks automatically. On the name, the lecture explains that "learning rate" was coined by machine learning people, and optimization people do not necessarily call it that; a small learns slowly, a somewhat larger learns faster, and one that is too large is unstable.
The logistic regression algorithm
Page 23 puts everything together:
- Initialize .
- For :
- Compute the gradient .
- Update by .
- Until , or enough iterations.
- Return the last as .
For the stopping condition, the handout writes that the gradient equals zero. The lecture is more practical: with floating-point arithmetic an exact 0 is hard to get, so usually the gradient is only required to be close enough to zero (roughly at the bottom is good enough); another common condition is to stop after enough steps and pretend to have reached a reasonably good place.
The last line on the slide is "similar time complexity to pocket per iteration". The lecture explains: the most expensive part of each iteration is computing the gradient, which averages the contributions of all examples; pocket also uses all examples in each iteration to check whether the new has a good enough , so the two cost about the same.
Numerical example: five patients, two steps by hand, then run to the bottom
What follows is an example made up for this article, not from the slides; the numbers were verified with Python. It keeps the heart attack setting but only one feature: is the standardized score of some lab test, and means the patient later had a heart attack. With added, and .
| 1 | |||
| 2 | |||
| 3 | |||
| 4 | |||
| 5 |
People with a high test value have heart attacks more often, but patient 3 (a middling value, yet a heart attack) and patient 4 (a fairly high value, yet fine) break the ordering. No threshold classifies all five correctly; the data is not linearly separable.
Step 0: , . Every example has score 0 and weight , and . The gradient is
Update:
becomes positive, meaning a higher test value means higher risk; the direction is right.
Step 1: compute the gradient at . The five weights are now different:
| Score | Weight | ||
|---|---|---|---|
| 1 | 0.4775 | ||
| 2 | 0.4875 | ||
| 3 | 0.5025 | ||
| 4 | 0.5075 | ||
| 5 | 0.4825 |
Examples 3 and 4 have negative : they are misclassified, and their weights exceed 0.5. Example 4 has the smallest value and the largest weight, consistent with the conclusion of "Fun Time: who has the largest weight in the gradient". Multiply each weight by its and average:
Update:
at the three points in time is 0.6931, 0.6766, and 0.6615, dropping at every step.
Running to the bottom. Continuing with , the gradient length falls below at step 344, and the run finally converges to
| Weight | ||||
|---|---|---|---|---|
| 1 | 0.057 | 0.057 | ||
| 2 | 0.153 | 0.153 | ||
| 3 | 0.349 | 0.651 | ||
| 4 | 0.615 | 0.615 | ||
| 5 | 0.826 | 0.174 |
What this result means.
- The model reports risk: about 6% for a test value of and about 83% for . Thresholding at one half, as in "Fun Time: converting a probability back to circle or cross", puts the boundary at ; examples 3 and 4 are still misclassified, and the 0/1 error is . The risks of these two are estimated as 0.349 and 0.615, both not far from one half; the model was never confident about them.
- The likelihood rises from at to .
- The gradient is zero by way of Case 2 from the subsection "Setting the gradient to zero cannot be solved". None of the weights is 0; the weighted sum cancels: the first component is , and the second is . The two misclassified examples have the largest weights and pull the three correctly classified ones to a draw.
Trying different . Same data, same start at , changing only the fixed learning rate:
| after step 1 | Steps until the gradient length falls below | What happens | |
|---|---|---|---|
| 0.01 | 0.6915 | 3,460 | each step drops only a tiny bit, the handout's too slow |
| 0.1 | 0.6766 | 344 | steady descent |
| 1 | 0.5634 | 32 | steady descent, ten times faster |
| 3 | 0.4955 | 8 | the fastest of the values in this table (trying others, needs only 5 steps, slows to 21 steps, and never gets there) |
| 10 | 0.8739 | never | higher than the starting 0.6931 after step 1; afterwards it gradually settles into bouncing between the two points and , where is 0.6148 and 0.5308, and the gradient length stays at 0.176 |
| 100 | 8.0000 | never | cycles every three steps, jumping among roughly 4, 14, and 6; it is 13.87 at step 1,000 and 5.84 at step 5,000 |
The row corresponds to the middle figure on page 21: one step crosses the bottom of the valley and lands on the opposite slope. Here the landing point of step 1 is even higher than the starting point, which is the situation the lecture warns about: after crossing to the opposite slope, you end up higher. How large an counts as too large depends on the data, and the numbers in this table do not carry over to other problems.
One more experiment, with the normalized version, that is, the update on page 20 that moves a fixed length at every step, with . It gets near the bottom of the valley within 30 steps, but after that every step still has to cover the full length of 0.05, so it can only stride back and forth between two points on either side of the bottom: even steps land at , with gradient length 0.0044; odd steps land at , with gradient length 0.0087. All the way to step 5,000 these two points keep alternating, and the gradient length stays above 0.004 and never falls to . This shows why page 21 asks for a step size that changes with the gradient length; in the fixed learning rate version the step shrinks by itself near the bottom, and the problem does not arise.
Fun Time: the first step from the zero vector
Question (page 24): If , and take . What is in the logistic regression algorithm?
Answer: 3. The handout only says to substitute using . The full substitution: with , every example has , so every weight is ,
Choice 1 leaves out . Choices 2 and 4 have the wrong sign: the gradient contains a minus sign and the update subtracts the gradient, and two minuses make a plus. The five-patient example can be used to check the answer: , and multiplying by 0.05 gives , which is the computed earlier.
The handout's comment on this result is that a scaled average of is somewhat 'one-step' better than the zero vector. In the lecture, Lin explains that averaging the products of and is a fairly good direction, a little better than the zero vector, because it has already rolled downhill once.
This lecture in four sentences
The summary on page 25, one sentence per section:
- Problem: as target and as hypotheses.
- Error: cross-entropy (negative log likelihood).
- Gradient: -weighted sum of data vectors.
- Gradient descent: roll downhill by .
The preview of the next lecture is "linear model'S' for classification". In the lecture, Lin says that linear classification, linear regression, and logistic regression are all linear methods, and the next lecture will bring them together and apply them to more complicated problems.
Self-check
1. An example has and , and currently . Compute , this example's cross-entropy error, and the vector it contributes to the gradient sum, . In which direction does this example push ?
Answer: the score is and ; the hypothesis considers almost impossible, yet the label is . The error is . The weight is , and the contributed vector is . The update subtracts the gradient, so this example pushes in the direction of , that is, of , raising its own score.
2. A hypothesis outputs on all three examples, whose labels are circle, circle, cross. Ignoring , what is the likelihood? What is ? What is the score of these three examples?
Answer: the likelihood is . ; computed term by term it is , the same result. Solving gives and . Criterion: the two ways of computing must agree, which is what " is the negative log likelihood divided by " means.
3. In the five-patient example, switch to and take one step from . What is ? Can it be obtained directly from the result without recomputing the gradient?
Answer: yes. The gradient at the first step does not depend on and is either way, so , ten times the value for . Here . From the second step on this conversion no longer works, because differs along the two paths and so does the gradient.
4. Two one-dimensional examples (with added): labeled , and labeled . Take with . What function of is ? Where does gradient descent stop? What does this say about the stopping condition?
Answer: both examples have , so : 0.3133 at , 0.0067 at , and about at . It keeps decreasing with and approaches 0 without reaching it; both weights are , always positive. When the data is linearly separable, a zero gradient occurs only in the limit where the length of goes to infinity, which is the "all are 0" case. So the algorithm never stops because the gradient is exactly zero; it relies on the two conditions "gradient small enough" or "enough iterations".
5. Explain in your own words: (a) why the best unit direction is ; (b) how long each step actually is in the fixed learning rate version; (c) what and are when PLA is put into the framework .
Criteria: (a) should mention that for very small the Taylor expansion approximates by , that only the inner product term depends on , and that the inner product is smallest when the unit vector is opposite to the gradient. (b) The length is , scaling with the gradient; the answer should point out that what is "fixed" is the ratio. (c) , and is when the chosen point is misclassified and the zero vector when it is classified correctly; even better if the answer goes on to note that PLA looks at one example per step while gradient descent looks at all .
Exercises and corresponding reading
The corresponding week in two semesters. The Fall 2026 course page puts Foundations Lectures 9 and 10 in the same week (W5, 10/07). The corresponding Fall 2024 slides are 10u; this article uses only the MOOC handout and has not compared the two versions page by page.
Textbook. The Fall 2024 course page maps this lecture to Section 3.3 of Learning from Data (LFD).
Homework. None of the problems below has official solutions.
- Fall 2024 HW3 (released 2024-10-07, due 10-21) Q4: for samples drawn from a uniform distribution on , what is the likelihood of a given estimate. It practices the move "pretend some parameter is the true one and compute how likely it is to generate the data in hand".
- HW3 Q9: switch to a different sigmoid hypothesis and follow the steps of logistic regression to derive the new and gradient. The method is to walk through this article's "Take ln, add a minus sign, divide by N" and "Peeling the onion with the chain rule" once more.
- Fall 2024 HW4 (released 2024-10-21, due 11-04) Q1: after the labels change from to , which expression is equivalent to the cross-entropy from the lecture. The subsection "The shape and the name of cross-entropy" has already derived it once.
- HW4 Q5 (extension): derive Newton's method from the second-order Taylor expansion and apply it to the cross-entropy of logistic regression; it can be treated as an advanced version of gradient descent.
The guide to the whole assignment is in Foundations Homework.
Hands-on. Write the four steps of "The logistic regression algorithm" as a dozen or so lines of Python. First reproduce this article's numbers on the five-patient data (, , and the converged ), then vary from 0.01 to 100, plot against the number of iterations, and compare with the three figures on page 21.
Further reading. Stanford CS229 Lecture 3: Maximum Likelihood and Logistic Regression derives the same model with labels; Stanford CS109's Maximum Likelihood Estimation and Logistic Regression cover likelihood from the angle of a probability course.
Next lecture. Foundations Lecture 11: Linear Models for Classification compares these three linear models side by side, asks whether linear regression and logistic regression can be used for classification, turns gradient descent into stochastic gradient descent (SGD), and finally handles multiclass classification.
Course video sources
Original videos: Logistic Regression Problem, Logistic Regression Error, Gradient of Logistic Regression Error, Gradient Descent
Checked: 2026-10-13. The video IDs, titles, and lengths were taken from the official playlist that day; the videos have no caption track on YouTube, and what this article reports from the lecture comes from transcripts made for it.
Update Log
- 2026-10-13: The series now has one article per lecture; this lecture is a newly split-out article, written from the handout and the video transcripts.
References
- Foundations Lecture 10 handout, 10_handout.pdf: the main source for this article. The derivations in the four sections, the four Fun Time questions, and the three figures on page 21 all come from this handout.
- Machine Learning Foundations YouTube playlist: the IDs and titles of the four videos; what the text reports as said "in the lecture" is paraphrased from machine transcripts of these four videos.
- Hsuan-Tien Lin > MOOCs: the official entry for handouts and recordings.
- Machine Learning, Fall 2024 course page: the corresponding LFD section.
- Fall 2024 slides, 10u_handout.pdf: the corresponding Fall 2024 slides, not compared page by page in this article.
- Machine Learning, Fall 2026 course page: the corresponding week.
- Fall 2024 Homework 3 (hw3_red.pdf): the content of Q4 and Q9.
- Fall 2024 Homework 4 (hw4_red.pdf): the content of Q1 and Q5, and the explanation of the name cross-entropy.
- Learning from Data textbook website: the source of Section 3.3.
- Reading NTU Hsuan-Tien Lin Machine Learning Foundations & Techniques: Course Overview: where this lecture sits in the whole course and the reading routes.
Loading...