Unit 3 of 8 · about 4 hours · derive, implement

Logistic regression and stable binary cross-entropy

Logistic regression turns a linear score into a probability claim, and its likelihood is the template for every neural classifier loss later. Getting the stable form right here prevents silent infinities everywhere after.

You'll be able to

  • Derive the binary log likelihood, its prediction-error-times-input gradient, and the -penalized objective from a Gaussian prior.
  • Implement binary cross-entropy on logits that stays finite for extreme scores, with a gradient check.
  • Explain why there is no closed form, why concavity still guarantees a global optimum, and what C controls in sklearn.

Covers

Logistic regression, odds, sigmoid and log likelihoodStable binary cross-entropy with logits
1

Read

In this order, only the parts listed

0 of 5 done

  1. Logistic regression: likelihood, gradient and regularizationTom Mitchell - Generative and Discriminative Classifiers: Naive Bayes and Logistic Regression

    Sections 3.2 (conditional log likelihood with the gradient-ascent update from zero weights at 0.01) and 3.3 (-penalized log likelihood, Gaussian-prior MAP reading, penalized gradient rule 26)

    Read the likelihood and gradient derivations fully. Section 3.1 writes , the opposite sign convention, and 3.2 flips in (24)-(25) to the usual form, so check signs when you compare. Skim 3.1; its Gaussian-to-sigmoid bridge returns in the LDA unit.

  2. The logistic model and maximum likelihoodAn Introduction to Statistical Learning with Python

    Chapter 4, Sections 4.3.1 to 4.3.3 (pp. 139-141): the logistic model, likelihood (4.5) preferred over nonlinear least squares, and the Default-data arithmetic (balance $2,000 gives 58.6%)

  3. Maximum likelihood and gradient-based fittingDive into Deep Learning - linear models slice

    Section 22.7: The Maximum Likelihood Principle, then Numerical Optimization and the Negative Log-Likelihood with its set-up, initialize, descend and check-output worked example

  4. Binary logistic loss, C semantics and solversscikit-learn - linear models, discriminant analysis and naive Bayes

    Section 1.1.11 with 1.1.11.1 (expit form, averaged binary cross-entropy plus ; means no penalty) and 1.1.11.3 (solver-versus-penalty table; lbfgs is the default)

  5. Estimating probabilities and decision boundariesHands-On Machine Learning with Scikit-Learn and PyTorch - classification and linear models

    Book Chapter 4: Estimating Probabilities through Decision Boundaries (printed pp. 168-174). Notebook 04 cells: Estimating Probabilities (iris virginica detector on petal width) and Decision Boundaries (boundary contour with )

2

Focus on

  • The gradient is prediction error times input, summed over rows. Mitchell ascends the summed log likelihood from zero weights; sklearn minimizes averaged cross-entropy plus an term ( by default) with lbfgs. Their optima agree only when the penalties match, for example = np.inf against Mitchell's unpenalized rule.
  • sklearn regularizes by default at on an averaged loss, so its is not a textbook : smaller means stronger penalty, and recovers the unpenalized fit.
  • Never exponentiate before logging. In float64 the sigmoid rounds to exactly 1.0 once passes about 36.7, but to exactly 0 only below about -709.8, so the naive loss for is already at , and at it returns 36.044 instead of 36.0. The form stays exact.
Common mistakes · 3
  • Equating sklearn with a textbook . is inverse strength on an averaged loss, so doubling halves the penalty; sample and class weights rescale the effective through the total weight .
  • Trusting probabilities from a near-unpenalized fit on nearly separable data. The likelihood keeps rewarding larger weights, so scores saturate toward exactly 0 and 1 without becoming more accurate.
  • Starting gradient ascent from large random weights for symmetry breaking. The objective is concave with one global optimum and Mitchell starts at zero; large starts only waste steps or overflow the first sigmoid.
3

Try it yourself

Closed-book, before checking anything

Derive the gradient from the binary log likelihood. In float64 show the naive loss returns for and already for , while returns 800.0 and 40.0. Match your analytic gradient to central differences to 1e-8 on a 3-point demo.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.Why does logistic regression need iterative fitting when linear regression has a closed form?Answer

    The sigmoid makes the log likelihood nonlinear in with no analytic maximizer. The objective is concave, so gradient ascent still reaches the one global optimum.

  2. 2.sklearn at default C = 1.0 disagrees with your zero-penalty NumPy fit. Which one is right?Answer

    Both solve their stated objectives: sklearn minimizes averaged cross-entropy plus an term at . Set to or a very large value to recover the unpenalized fit.

  3. 3.Training loss prints inf on the first epoch for a positive example with logit near -800. What happened, and what is the fix?Answer

    The sigmoid underflowed to exactly 0 and is . A negative example fails much sooner: at logit 37 the sigmoid rounds to exactly 1 and is . Score in logits with instead of exponentiating first.

  4. 4.Recompute ISLP's 58.6% default risk for balance $2,000 from Table 4.1.Answer

    ; . A one-unit balance rise adds 0.0055 to the log odds.

5

Practice

  • Deep-ML 106: Train Logistic Regression with Gradient Descent

    Gradient descent on binary cross-entropy returning coefficients plus 10 per-iteration losses rounded to 4 decimals. Both tests open at 6.9315 = : the reference prepends a bias column, starts from zero weights, sums (not averages) loss and gradient over the 10 rows, and records the loss before each update

    Implement the stable logit form; the naive probability form risks inf on confident rows.

  • NeetCode ML: Sigmoid and ReLU plus Cross-Entropy Loss

    Math Foundations pair: activation values first, then the loss that consumes them

    After the section gate, solve cold after Deep-ML 106 and state the input range where each saturates.

You're done when

Your logit loss matches central differences, stays finite on the (-800, 1), (40, 0) and (800, 0) probes, and your Deep-ML 106 losses open at 6.9315 and track the reference through all 10 iterations.

Only when you can do this without notes.

Leads to

Notes

Resources · 5 for this unit, 2 more in the section
  • An Introduction to Statistical Learning with PythonJames, Witten, Hastie, Tibshirani and Taylor · primary

    Use Chapters 3, 4 and 6 with their Python labs as the first pass: least squares and its diagnostics, logistic regression, LDA, QDA and naive Bayes, basis expansion and regularization paths.

  • Dive into Deep Learning - linear models sliceD2L authors · required

    Use 3.1, 3.4, 3.6, 3.7, 4.1, 4.4, 22.7 and 22.9 for linear regression, generalization, weight decay, softmax, maximum likelihood and naive Bayes. Implement with NumPy first and use the PyTorch versions only as a differential reference.

  • scikit-learn - linear models, discriminant analysis and naive Bayesscikit-learn · reference

    Use the official Linear Models, LDA and QDA, and Naive Bayes guides to verify estimator semantics and selected edge cases after the independent implementation works.

  • Hands-On Machine Learning with Scikit-Learn and PyTorch - classification and linear modelsAurelien Geron (O'Reilly, 2025) · support

    Read the Chapter 3 and 4 sections each unit names, then run notebooks 03 and 04 for classification diagnostics, linear and polynomial regression, regularization and logistic regression. Recreate the target mechanism independently before inspecting worked exercise code.

  • Tom Mitchell - Generative and Discriminative Classifiers: Naive Bayes and Logistic RegressionTom Mitchell, Carnegie Mellon University · required

    Read Sections 2 (naive Bayes, the smoothed estimates (7) and (9), parameter counts), 3 (Gaussian naive Bayes implies the logistic form, gradient ascent, the penalty, the -class rules) and 4 (generative versus discriminative, Ng and Jordan rates). This is the CS446 reading for Lectures 6-8; rework each derivation on a hand-sized dataset.

Also in this section

  • NeetCode ML - linear-model closing drillNeetCode · support

    After the section gate, solve Gradient Descent, Sigmoid and ReLU, Softmax, Cross-Entropy Loss, Linear Regression Forward and Linear Regression Training cold. Repeat only failed items from a blank file with changed values.

  • Deep-ML - linear and probabilistic model problemsDeep-ML · support

    Use 15 Linear Regression Using Gradient Descent, 106 Train Logistic Regression with Gradient Descent and 140 Bernoulli Naive Bayes Classifier as unit checks after the local implementation passes. Their tests were read in review; each card states what they pin. The local implementation remains the evidence.