CS229 / STUDY NOTES
CS229 · Spring 2026 · approximately 4,105 words

Lecture 3 — From noise models to logistic regression and Newton steps

Recording: Stanford CS229 Machine Learning | Spring 2026 | Lecture 3: Weighted Least Squares · 62:14

English caption track marked non-automatic by YouTube · 1,740 timed segments · Retrieved 25 September 2026.

Timestamp links locate relevant discussion windows. Definitions and derivations are reconstructed; worked examples and exercises are original unless attributed. Research additions are labeled. Slide images were not comprehensively reviewed. See the section-level source map.

Editable Markdown

A property model must answer two different questions: “What price will this house sell for?” and “Will an inspection reveal a serious defect?” A numerical price and a binary event require different observation models. Maximum likelihood provides a common construction: describe a distribution for the observations, evaluate how well it explains the data, and optimize its parameters. The resulting loss is determined by the model, rather than selected because its graph looks convenient.

The upload title mentions weighted least squares, but the recording's main sequence is Gaussian regression, maximum likelihood, binary logistic regression, and Newton's method. Weighted least squares appears below as a clearly identified extension of the noise model.

1. A regression equation is an assumption about observations 04:00

What is random, and what is held fixed?

Let $x_i\in\mathbb R^p$ be the feature vector for house $i$, including a leading constant 1 for an intercept, and let $y_i\in\mathbb R$ be its sale price. Here $p$ counts all coefficients, including the intercept, and $i\in\{1,\ldots,n\}$ indexes the $n$ observations. For fixed features, assume

$$Y_i=x_i^\top\theta_*+\varepsilon_i.$$

The vector $\theta_*\in\mathbb R^p$ is an unknown fixed parameter. Capital $Y_i$ denotes a random response before it is observed; lowercase $y_i$ denotes its observed value. The noise $\varepsilon_i$ represents everything left outside the deterministic prediction, including measurement error and unmodeled influences. This is a model of the observations, not proof that house prices are generated by an affine physical law.

The condition needed for the affine function to be the conditional mean is $\mathbb E[\varepsilon_i\mid x_i]=0$. Unconditional mean-zero noise is weaker. If omitted neighborhood quality is correlated with floor area, averaging the noise over all houses may give zero while the average noise at a particular area remains nonzero. In that case the supposed conditional mean is misspecified.

Independent and identically distributed, abbreviated IID, imposes two separate requirements on the noise: joint probabilities factor across observations, and the marginal distributions are the same. Independence implies zero covariance when second moments exist. Zero covariance does not imply independence. For instance, if $U$ is uniform on $[-1,1]$, then $U$ and $U^2$ have zero covariance by symmetry but are dependent because the second is determined by the first.

Moments do not identify a Gaussian distribution

Write $\sigma^2=\mathbb E[\varepsilon_i^2]$ for a mean-zero noise variance. Knowing this variance and the mean does not determine the full distribution. A variable taking $-\sigma$ and $+\sigma$ with equal probabilities has the same first two moments as a centered Gaussian with variance $\sigma^2$, yet it is discrete. The Gaussian form is an additional modeling assumption. This distinction makes precise an overly compressed part of the spoken discussion.

A Gaussian variable $Z\sim\mathcal N(\mu,\sigma^2)$, with $\sigma\gt0$, has density

$$p(z)=\frac{1}{\sqrt{2\pi\sigma^2}} \exp\left[-\frac{(z-\mu)^2}{2\sigma^2}\right].$$

The standard deviation $\sigma$ has the same units as $z$, whereas the variance has squared units. The exponent is dimensionless. The density has inverse-response units and integrates to one. A density value is not the probability of one exact real-valued observation; that probability is zero under a continuous distribution. Densities can exceed one when the distribution is concentrated in a narrow interval.

Assuming $\varepsilon_i\sim\mathcal N(0,\sigma^2)$ therefore gives $Y_i\mid x_i\sim\mathcal N(x_i^\top\theta_*,\sigma^2)$. Adding a constant changes the mean but not the variance. Multiplying the noise by a constant $c$ would instead multiply its variance by $c^2$. This units check prevents confusing variance with standard deviation when changing price units.

For the running property case, a Gaussian error model might be a tolerable local approximation after conditioning on sufficiently informative features. It can fail for asymmetric price distributions, heavy tails, or mixtures of neighborhoods. Those failures suggest different models, rather than invalidating the general likelihood construction.

2. Maximum likelihood recovers least squares 23:00

Treat the observed data as fixed

For a candidate parameter $\theta$, the likelihood $L(\theta)$ is the joint density of the observed responses evaluated as a function of that parameter. In conditional regression, the features are held fixed. If the responses are conditionally independent and share the Gaussian noise variance, then

$$L(\theta;\sigma^2)=\prod_{i=1}^n \frac{1}{\sqrt{2\pi\sigma^2}} \exp\left[-\frac{(y_i-x_i^\top\theta)^2}{2\sigma^2}\right].$$

The product is justified by conditional independence. It does not require modeling the feature distribution. Nor is $L(\theta)$ a probability distribution over parameters: integrating it over $\theta$ need not give one. A Bayesian posterior would additionally require a prior distribution and normalization over parameters.

The natural logarithm is strictly increasing on positive numbers, so maximizing the likelihood is equivalent to maximizing its log. The log likelihood is

$$\ell(\theta;\sigma^2) =-\frac n2\log(2\pi\sigma^2) -\frac{1}{2\sigma^2}\sum_{i=1}^n(y_i-x_i^\top\theta)^2.$$

For fixed positive $\sigma^2$, the first term is constant in $\theta$ and the second is a negative multiple of squared residuals. Therefore the maximum-likelihood coefficient estimate is precisely the least-squares estimate. If $J(\theta)=\|X\theta-y\|_2^2/(2n)$ as in Lecture 2, then maximizing $\ell$ is equivalent to minimizing $J$. The sign distinction matters: one ascends log likelihood or descends negative log likelihood.

Products of many small numbers can underflow in floating-point arithmetic, whereas their logarithms add. This computational convenience is one reason additive negative log likelihoods recur throughout machine learning. It does not justify dropping every normalization term. A term constant in one parameter may depend on another parameter that is also being fitted.

Estimating the noise scale

Let $S(\theta)=\sum_i(y_i-x_i^\top\theta)^2$ be the residual sum of squares, and set $v=\sigma^2\gt0$. Differentiating negative log likelihood with respect to $v$ gives $n/(2v)-S/(2v^2)$. Setting the derivative to zero yields $\hat v=S(\hat\theta)/n$, provided the residual sum of squares is positive. This is the maximum-likelihood variance estimate.

Under the correctly specified full-rank Gaussian model, dividing by $n-p$ instead of $n$ gives an unbiased noise-variance estimate. The distinction reflects the degrees of freedom used to fit $p$ coefficients. Maximum likelihood and unbiasedness are different selection criteria. If the data are fitted exactly and variance is unrestricted, sending $v$ to zero makes the Gaussian density unbounded; there is no ordinary positive-variance maximum. The edge case matters in overparameterized models.

Suppose residuals after fitting are $-1,0,1$ price units. Their sum of squares is 2, so the maximum-likelihood variance estimate is $2/3$. If one coefficient was fitted under the appropriate linear model, the unbiased estimate would be $2/(3-1)=1$. The standard deviations are the square roots of these quantities, not the quantities themselves.

Extension: unequal reliability produces weights

If observation $i$ has known independent Gaussian noise variance $\sigma_i^2\gt0$, the coefficient-dependent negative log likelihood becomes $\frac12\sum_i(y_i-x_i^\top\theta)^2/\sigma_i^2$. Thus weighted least squares uses weights $w_i=1/\sigma_i^2$, called precisions. More reliable measurements receive more weight because a given residual is less plausible under their narrower noise distributions.

For two independent appraisals of the same value, 10 and 14, with standard deviations 1 and 3, minimizing weighted squared error gives the weighted mean

$$\hat\mu=\frac{10/1^2+14/3^2}{1/1^2+1/3^2}=10.4.$$

The noisier appraisal does not pull the estimate halfway toward 14. Correlated appraisals require a full covariance model; diagonal weights would count shared errors as independent information. With covariance matrix $\Sigma$ positive definite, the corresponding quadratic is $(y-X\theta)^\top\Sigma^{-1}(y-X\theta)/2$. The model must justify the covariance, rather than choosing weights merely to improve a preferred answer.

3. Binary observations lead to logistic probabilities 34:00

Why a bounded probability is useful

Now let $Y_i\in\{0,1\}$ indicate a serious inspection defect. A linear regression can output values below zero or above one. Thresholding such scores may sometimes classify well, but the raw outputs are not valid probabilities. A probability model should satisfy its own range constraint and use a loss appropriate to its intended interpretation.

Define the linear score $z_i=x_i^\top\theta$, sometimes called a logit, and transform it by the sigmoid $\sigma(z)=1/(1+e^{-z})$. In this section $\sigma(\cdot)$ denotes a function; the previous Gaussian standard deviation appeared without an argument. The model probability is $p_i=\sigma(z_i)\in(0,1)$. It obeys

$$\frac{p_i}{1-p_i}=e^{z_i},\qquad \log\frac{p_i}{1-p_i}=x_i^\top\theta.$$

The ratio is the odds, and its logarithm is the log odds. Logistic regression assumes log odds are affine in the chosen features. Increasing feature $j$ by one unit, with others fixed, multiplies the odds by $e^{\theta_j}$. It does not add a constant to the probability, because the sigmoid is nonlinear.

In standard generalized-linear-model terminology, the link maps the mean probability to the linear score: $g(p)=\log[p/(1-p)]$. The sigmoid is its inverse link. Some informal presentations call the sigmoid a link; distinguishing the two directions will prevent confusion in Lecture 4.

For a score zero, probability is one-half. A score $\log 3$ gives odds 3 and probability $3/4$. If false-negative cost is nine times false-positive cost, the decision threshold from Lecture 1 is probability $0.1$, corresponding to logit $\log(1/9)$ rather than zero. Fitting probabilities and choosing an action threshold remain separate operations.

The Bernoulli likelihood gives cross entropy

A Bernoulli distribution assigns probability $p$ to 1 and $1-p$ to 0. Its mass function can be written $p^y(1-p)^{1-y}$ for $y\in\{0,1\}$. Substituting either possible label verifies the formula: one exponent becomes zero and contributes a factor one.

Under conditional independence, multiplying these masses and taking negative logarithms gives the averaged binary cross-entropy loss

$$J(\theta)=-\frac1n\sum_{i=1}^n \left[y_i\log p_i+(1-y_i)\log(1-p_i)\right].$$

Using $p_i=e^{z_i}/(1+e^{z_i})$ simplifies each summand to $\log(1+e^{z_i})-y_i z_i$. This is the same loss in score coordinates. It is useful both for differentiation and stable computation. For a positive observation with predicted probability $0.9$, loss is about $0.1053$; assigning $0.1$ gives about $2.3026$. Confidently wrong predictions receive a large penalty.

The population interpretation is also precise. At an input with true event probability $q$, expected loss for prediction $p$ is $-q\log p-(1-q)\log(1-p)$. Its derivative with respect to $p$ is $(p-q)/[p(1-p)]$, which changes sign at $p=q$. Thus the unrestricted probability minimizing expected log loss is the true conditional probability. A restricted affine-logit model, finite data, or distribution shift can prevent the fitted probabilities from attaining that target.

4. The gradient is prediction error times features 44:00

Expose the cancellation

Differentiate the sigmoid: $\sigma'(z)=\sigma(z)[1-\sigma(z)]$. The derivative of a Bernoulli negative log likelihood with respect to $p$ is $(p-y)/[p(1-p)]$. Multiplying by the sigmoid derivative cancels the denominator, leaving $p-y$ as the derivative with respect to the score. Since $\nabla_\theta z_i=x_i$, the parameter gradient is

$$\nabla J(\theta)=\frac1n\sum_i(p_i-y_i)x_i =\frac1nX^\top(p-y).$$

The vector $p$ stacks model probabilities and $y$ stacks binary labels. This resembles the least-squares gradient, but the predictions inside the residual are now sigmoid probabilities. For a positive example predicted too low, $p_i-y_i\lt0$; a descent update increases the score along its feature direction. A negative example pushes the other way.

Differentiate once more. If $W$ is diagonal with entries $p_i(1-p_i)$, the Hessian is $H=X^\top WX/n$. For any vector $v$, $v^\top Hv=\sum_i p_i(1-p_i)(x_i^\top v)^2/n\ge0$. Logistic negative log likelihood is convex in the coefficients for fixed features. This proof does not extend automatically to a neural network whose features also depend on fitted parameters.

At every finite coefficient vector, sigmoid probabilities lie strictly between zero and one. If $X$ has full column rank, $H$ is then positive definite. However, strict convexity on finite points does not guarantee that a minimum is attained at a finite point. A function may decrease toward an infimum at infinity. Separable data provide exactly this case.

A two-house calculation

Use standardized feature values $-1$ and $+1$, include an intercept, and assign labels 0 and 1. Then $X=\begin{bmatrix}1&-1\\1&1\end{bmatrix}$ and $y=(0,1)^\top$. At $\theta=(0,0)^\top$, both probabilities are $1/2$. The averaged gradient is $(0,-1/2)^\top$, and the Hessian is $I/4$.

A gradient step with learning rate one yields $\theta=(0,1/2)^\top$. The positive house's probability becomes $\sigma(1/2)\approx0.622459$. The negative house receives the complementary probability. The average loss decreases from $\log 2\approx0.693147$ to $\log(1+e^{-1/2})\approx0.474077$. This verifies the sign, the averaging convention, and the coordinate ordering.

The example is perfectly separable: a positive slope makes both classification decisions correct. Increasing that slope continues to reduce log loss even after the binary error is zero. Classification accuracy and probability fitting can therefore continue changing on different scales.

Stable executable loss and gradient

The expression $\log(1+e^z)$ overflows for a sufficiently large positive score if computed naively. Instead use $\max(z,0)+\log(1+e^{-|z|})$. For a binary label, an even cleaner per-example form is $\log(1+e^{-(2y-1)z})$, evaluated by a stable log-add-exp operation. This also avoids subtracting two nearly equal large terms for a confidently correct positive example.

The code accepts finite arrays with a two-dimensional nonempty design, flat binary labels, and matching coefficients. It returns the averaged loss and gradient without mutating inputs or performing external effects. It rejects shape errors and nonbinary labels. The sigmoid uses separate positive and negative branches to avoid exponential overflow.

import numpy as np


def logistic_loss_gradient(X, y, theta):
    X = np.asarray(X, dtype=float)
    y = np.asarray(y, dtype=float)
    theta = np.asarray(theta, dtype=float)
    if X.ndim != 2 or min(X.shape) == 0:
        raise ValueError("X must be a nonempty matrix")
    if y.shape != (len(X),) or theta.shape != (X.shape[1],):
        raise ValueError("incompatible shapes")
    if not all(np.isfinite(a).all() for a in (X, y, theta)):
        raise ValueError("inputs must be finite")
    if not np.isin(y, [0.0, 1.0]).all():
        raise ValueError("labels must be binary")
    with np.errstate(over="raise", invalid="raise"):
        z = X @ theta
        probabilities = np.empty_like(z)
        positive = z >= 0
        probabilities[positive] = 1 / (1 + np.exp(-z[positive]))
        exp_z = np.exp(z[~positive])
        probabilities[~positive] = exp_z / (1 + exp_z)
        loss = np.logaddexp(0, -(2 * y - 1) * z).mean()
        gradient = X.T @ (probabilities - y) / len(X)
    return float(loss), gradient


X = np.array([[1.0, -1.0], [1.0, 1.0]])
y = np.array([0.0, 1.0])
loss, gradient = logistic_loss_gradient(X, y, np.zeros(2))
assert np.isclose(loss, np.log(2))
assert np.allclose(gradient, [0.0, -0.5])
loss_after, _ = logistic_loss_gradient(X, y, -gradient)
assert np.isclose(loss_after, np.logaddexp(0, -0.5))
extreme_loss, _ = logistic_loss_gradient(X, y, [0.0, -1000.0])
assert np.isfinite(extreme_loss) and np.isclose(extreme_loss, 1000)

The extreme-score check uses confidently wrong predictions and would expose a naive overflow-prone implementation. Stability does not repair a poor model: a finite loss of 1000 is computationally valid evidence that the predictions are terrible. Saturated probabilities can still make second-order systems ill-conditioned.

5. Newton's method uses a local curvature model 49:00

From root finding to optimization

For a scalar function $f$, approximate it near $a$ by $f(a)+f'(a)(u-a)$. Setting this approximation to zero gives the Newton proposal $u=a-f(a)/f'(a)$, provided the derivative is nonzero. To minimize a differentiable objective, apply the same idea to its gradient: stationary points satisfy $\nabla J=0$.

In several dimensions, approximate the gradient at $\theta+\Delta$ by $\nabla J(\theta)+H\Delta$. Setting it to zero gives the linear system $H\Delta=-\nabla J(\theta)$. Solve the system, then set $\theta_{\rm new}=\theta+\Delta$. Writing $-H^{-1}\nabla J$ is a mathematical shorthand; numerical code should normally solve the system rather than form an inverse.

The same step minimizes the local quadratic model $J(\theta)+\nabla J(\theta)^\top\Delta+\frac12\Delta^\top H\Delta$ when $H$ is positive definite. The Hessian accounts for different curvature in different directions, allowing a longer move along a flatter direction. This explains why Newton steps can converge rapidly near a well-behaved minimizer.

For the two-house example, $H=I/4$ and $\nabla J=(0,-1/2)^\top$, so $\Delta=(0,2)^\top$. The positive-house probability becomes $\sigma(2)\approx0.880797$, and the average loss becomes $\log(1+e^{-2})\approx0.126928$. One Newton step reduces the loss more than the previous gradient step, but that comparison counts iterations, not their cost.

Global behavior needs safeguards

An undamped Newton step uses the local model at full scale. Far from a minimum, that approximation can be poor. A damped step uses $\theta_{\rm new}=\theta+\alpha\Delta$ with $0\lt\alpha\le1$, choosing a smaller value when the full proposal fails a decrease test. Thus “Newton has no learning rate” describes the pure local formula, not every robust implementation.

If the Hessian is singular, a pseudoinverse can solve a least-squares version of the linearized equation, but it is not a universal repair for nonexistence or poor conditioning. Adding a positive diagonal term, constraining the step, or changing the statistical objective addresses different problems. These interventions must be identified explicitly.

Dense logistic Newton iterations can require order $np^2$ work to form the Hessian, order $p^3$ work to factor it, and order $p^2$ memory. A minibatch gradient uses order $bp$ work for batch size $b$. These are dense arithmetic estimates, not universal wall-time predictions. Sparse designs, structured matrices, and iterative solvers can change the practical comparison.

In particular, the Hessian-vector product is $Hv=X^\top[W(Xv)]/n$, computable without storing the full Hessian. This makes iterative second-order methods possible. It does not make the inverse free; an iterative linear solve may need many such products. The Bottou–Curtis–Nocedal review discusses these computational trade-offs beyond the introductory comparison.

theta = np.zeros(2)
_, gradient = logistic_loss_gradient(X, y, theta)
weights = np.full(len(X), 0.25)
hessian = X.T @ (weights[:, None] * X) / len(X)
step = np.linalg.solve(hessian, -gradient)
assert np.allclose(step, [0.0, 2.0])
new_loss, _ = logistic_loss_gradient(X, y, theta + step)
assert np.isclose(new_loss, np.logaddexp(0, -2.0))

direction = np.array([0.3, -0.7])
product = X.T @ (weights * (X @ direction)) / len(X)
assert np.allclose(product, hessian @ direction)

This block continues the preceding example and has the same no-external-effects contract. The direct linear solve is appropriate only for this tiny nonsingular system. The final assertion checks the matrix-free product against the explicitly formed matrix. It tests a useful building block without claiming to implement a production Newton solver.

Research extension: finite accuracy can coexist with infinite coefficients

For linearly separable data, choose a vector $v$ such that $(2y_i-1)x_i^\top v\gt0$ for every observation. Along $\theta=cv$ with $c\to\infty$, every logistic loss term tends to zero. At any finite $c$, each term remains positive. Thus the loss has infimum zero but no finite unregularized minimizer. Full column rank and convexity do not prevent this.

This resolves an apparent contradiction in the two-house example: Newton and gradient descent can keep increasing the slope after classification is perfect because their actual objective still decreases. Soudry and colleagues analyze the implicit directional bias of gradient descent on separable logistic problems under stated assumptions. Convergence of a direction is different from convergence to finite coefficients. Their theorem should not be transferred indiscriminately to arbitrary neural networks or optimizers.

Probability quality also requires a separate check. Calibration asks whether predicted event probabilities agree with observed event frequencies in the relevant population. A model can classify almost every house correctly yet assign excessively extreme probabilities. Guo and colleagues studied calibration in neural networks and evaluated temperature scaling, which divides logits by a fitted positive scalar. Such a correction can change confidence without changing the binary threshold at zero. It needs held-out calibration data and does not automatically transfer under distribution shift.

Limitations, exercises, and worked solutions

Gaussianity is an assumption beyond mean and variance. Independence is stronger than uncorrelatedness. A valid probability range is not calibration. Convexity does not guarantee an attained finite minimum. Newton's local speed does not guarantee inexpensive iterations or global convergence. These boundaries are part of the mathematical model and should remain visible when its formulas are reused inside larger systems.

  1. Counterexample. Construct a non-Gaussian mean-zero variable with variance 4. Explain why first and second moments cannot establish Gaussianity.
  2. Derive. For independent Gaussian observations with common unknown mean and known variances, derive the precision-weighted mean and recover 10.4 for the appraisal example.
  3. Compute. Derive the gradient and Hessian at zero for the two-house logistic example. Compare its one-step gradient and Newton predictions.
  4. Diagnose. A training run reaches zero classification error while its coefficient norm keeps growing. Give a mathematical explanation and one defensible intervention.
  5. Design. How would you compare gradient descent and damped Newton for a modest property dataset without confusing optimizer performance with model quality?
Solutions
  1. Let the variable equal $-2$ or $2$, each with probability one-half. Its mean is zero and its second moment, hence variance, is 4. Its distribution has two point masses, whereas a nondegenerate Gaussian has a continuous density. This explicit pair of distributions with matching moments refutes uniqueness. Choosing a Gaussian may be useful, but it must be justified as a model rather than deduced from those moments alone.

  2. Ignoring terms independent of the mean $\mu$, negative log likelihood is $Q(\mu)=\frac12\sum_i(y_i-\mu)^2/\sigma_i^2$. Differentiating gives $Q'(\mu)=\sum_i(\mu-y_i)/\sigma_i^2$. Setting it to zero yields $\hat\mu=(\sum_i y_i/\sigma_i^2)/(\sum_i1/\sigma_i^2)$. The second derivative is the positive sum of precisions, so this stationary point is the unique minimum. Substituting 10, 14 and variances 1, 9 gives $\hat\mu=(10+14/9)/(1+1/9)=10.4$. Correlated errors invalidate the diagonal likelihood used in the derivation.

  3. At zero, probabilities are $(1/2,1/2)$ and residuals are $(1/2,-1/2)$. Multiplication by $X^\top/2$ gives gradient $(0,-1/2)$. Since $X^\top X=2I$ and every Bernoulli variance is $1/4$, the Hessian is $I/4$. A unit gradient step produces slope $1/2$, giving positive-house probability about $0.62246$. Solving the Newton system produces slope 2 and probability about $0.88080$. Both are valid finite probabilities; neither is the finite maximum-likelihood optimum because none exists for this separable sample.

  4. If all signed margins are positive, scaling the coefficient vector increases every margin and monotonically lowers logistic loss toward zero. The zero-one error cannot improve further, but the probability loss can. Add a stated regularization penalty, such as a positive quadratic penalty on all coefficients, to obtain a coercive objective with a finite minimizer; alternatively select an early stopping point using held-out performance. These choices change the estimator. Merely imposing an arbitrary iteration cap should be described as a computational limit, not evidence that the original optimum was reached.

  5. Fix features, preprocessing, labels, training/validation split, and the exact averaged objective, including any regularization. Compare objective decrease against elapsed time and arithmetic work, record gradient norms and linear-solve failures, and use a decrease test for Newton proposals. Check that both methods approach the same optimum when one exists. Evaluate probability loss and calibration separately on held-out data. If a method has a different penalty or uses test labels for tuning, the comparison no longer isolates optimization. A direct Hessian-vector check and finite-difference gradient check help distinguish implementation errors from genuine algorithm behavior.

Primary sources