Docsity

CS229 Machine Learning Study Guide | Stanford ML Exam Prep PDF, Exams of Engineering

Toggle sidebar
bg1
CS229 Machine Learning — Study Guide
1
CS229 Machine Learning
Study Guide
Intermediate Level • Stanford CS229 Core Topics
This guide consolidates the four core pillars of Stanford’s CS229: supervised learning, learning
theory, unsupervised learning, and neural networks. It assumes comfort with linear algebra
(matrix operations, eigendecomposition), multivariable calculus (gradients, Hessians), and basic
probability (Gaussians, Bayes’ rule). Each section ends with a practice problem; complete
solutions are provided in the final section so you can attempt each problem before checking your
work. Read actively — re-derive every gradient and re-sketch every model.
Contents
1
Linear Regression & Least Squares 2
2
Logistic Regression & Generalized Linear Models 3
3
Generative Models: GDA & Naive Bayes 4
4
Support Vector Machines & Kernels 4
5
Learning Theory 5
6
Unsupervised Learning 6
7
Neural Networks & Backpropagation 7
8
Solutions to Practice Problems 9
9
Summary & Further Reading 11
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download CS229 Machine Learning Study Guide | Stanford ML Exam Prep PDF and more Exams Engineering in PDF only on Docsity!

CS229 Machine Learning

Study Guide

Intermediate Level • Stanford CS229 Core Topics

This guide consolidates the four core pillars of Stanford’s CS229: supervised learning , learning

theory , unsupervised learning , and neural networks. It assumes comfort with linear algebra

(matrix operations, eigendecomposition), multivariable calculus (gradients, Hessians), and basic

probability (Gaussians, Bayes’ rule). Each section ends with a practice problem; complete

solutions are provided in the final section so you can attempt each problem before checking your

work. Read actively — re-derive every gradient and re-sketch every model.

Contents

1 Linear Regression & Least Squares 2

2 Logistic Regression & Generalized Linear Models 3

3 Generative Models: GDA & Naive Bayes 4

4 Support Vector Machines & Kernels 4

5 Learning Theory 5

6 Unsupervised Learning 6

7 Neural Networks & Backpropagation 7

8 Solutions to Practice Problems 9

9 Summary & Further Reading 11

i =

m

∂θj

θ

θ j

4 3 5

10 − 3 2

− 3 ·6+2· 10 2

i =

Key formula: normal equations

Closed-form least-squares solution. Requires X

⊤ X to be invertible (features linearly inde-

Practice Problem 1

{(1 , 3) , (2 , 5) , (3 , 7)}. Compute the least-squares parameter vector θ ( θ 0 , θ 1 ) using the

normal equations. Verify that the residuals are zero.

1. Linear Regression & Least Squares

Linear regression is the foundation of supervised learning: predict a real-valued output y ∈ R

as a linear function of features x ∈ R

n

. The hypothesis is

n

hθ ( x ) = θ

⊤ x = θjxj,

j =

where we append a bias feature x 0 = 1. Given a training set {( x

( i ) , y

( i ) )}

m , we choose θ to

minimize the squared-error cost

J ( θ ) =

h ( x

( i ) ) − y

( i )

2

.

Gradient descent updates θj := θj − α

∂J , where for a single example

∂J

= h ( x ) − y x.

This is the LMS (least-mean-squares) update. The update is proportional to the error ( hθ ( x )− y ),

which gives the algorithm its self-correcting character.

Batch gradient descent sums the gradient over all m examples; stochastic gradient descent

(SGD) updates after each example, which is cheaper and often faster on large datasets. The

learning rate α controls step size — too small and convergence is slow; too large and the cost

may diverge.

The normal equations give the closed-form minimizer. Stacking the data into a design matrix

X ∈ R

m ×( n +1) (rows are x

( i )

⊤

) and label vector y ∈ R

m , the optimal θ satisfies

∇ θJ = X

⊤ ( Xθ − y ) = 0 =⇒ θ = ( X

⊤ X )

−^1 X

⊤ y.

This is the maximum-likelihood estimator under Gaussian noise y

( i ) | x

( i ) ∼ N ( θ

⊤ x

( i ) , σ

2 ).

Worked mini-example. Two points: ( x, y ) = (1 , 2) , (2 , 4), with bias feature. Then X =

, y =

2

. Compute X

⊤ X =

, X

⊤ y =

6

. Inverse of X

⊤ X is

(det

= 1), giving θ =

5 · 6 − 3 · 10

=

0

. So the line is h ( x ) = 0 + 2 x = 2 x , exactly fitting both points.

∂θj

p ( x )

Y

j

i

is a logistic function

form.

Practice Problem 3

for some θ that depends on μ 1 , μ 0 , Σ. Express θ in closed

3. Generative Models: GDA & Naive Bayes

Discriminative algorithms (logistic regression) model p ( y | x ) directly. Generative algorithms

model the joint p ( x, y ) = p ( y ) p ( x | y ), then use Bayes’ rule p ( y | x ) =

p ( x |

y ) p ( y ) for prediction.

Gaussian Discriminant Analysis (GDA) assumes y ∼ Bernoulli( ϕ ) and x | y ∼ N ( μy, Σ)

with a shared covariance Σ:

p ( y ) = ϕ

y (1 − ϕ )

(^1) − y , p ( x | y ) =

exp −

1 ( x − μ )

⊤ Σ

−^1 ( x − μ ).

(2 π )

n/ 2 |Σ|

1 / 2 2

y y

The maximum-likelihood estimators are intuitive:

{ y

( i ) = 1 } , μ

i

1 { y

( i ) = k } x

( i )

( x

( i ) − μ ( i ) )( x

( i ) − μ ( i ) )

⊤ .

ϕ = 1

m

i

k 1 { y

( i ) = k } m

y y

i

The class posterior p ( y = 1 | x ) turns out to be a logistic function of x — but the converse is

not true. So GDA makes a strictly stronger modeling assumption than logistic regression.

GDA vs. logistic regression. If the Gaussian assumption holds, GDA is asymptotically

efficient and learns with fewer examples. If the assumption is wrong, logistic regression (which

only assumes p ( y = 1 | x ) is logistic) is more robust. Use GDA when you trust the generative

story and have limited data; use logistic regression when you do not.

Naive Bayes is a generative model for discrete features (e.g. text). With x ∈ { 0 , 1 }

d (a bag-

of-words indicator vector), the naive assumption is that features are conditionally independent

given y :

d

p ( x | y ) = p ( xj | y ).

j =

This drastically reduces parameters from O (

d ) to O ( d ). For text classification, parameters

ϕ j | y

= P ( xj = 1 | y ) and ϕy = P ( y ) are fit by MLE; Laplace smoothing

1 { x

( i ) = 1 ∧ y

( i ) = y } + 1

ϕ j | y

i

1 { y

( i ) = y } + d

prevents zero probabilities for unseen words.

4. Support Vector Machines & Kernels

SVMs combine geometric intuition with optimization. Given linearly separable data, define

the functional margin γ ˆ

( i ) = y

( i ) ( w

⊤ x

( i )

  • b ) and the geometric margin γ

( i ) = γ ˆ

( i ) / w. The

geometric margin is the signed perpendicular distance from x

( i ) to the decision boundary { x :

w

⊤ x + b = 0 }, normalized by w.

The maximum-margin classifier solves

γ ˆ

max

w,b,γ ˆ

s.t. y

( i ) ( w

⊤ x

( i )

  • b ) ≥ γ ˆ , i = 1 ,... , m.

w

i

2

m

2

2

2

Practice Problem 4

Because the norm w appears in the denominator, we can rescale ( w, b ) without changing the

constraint. Setting γ ˆ = 1 (normalization) gives the canonical form:

min

1 w

2

s.t. y

( i ) ( w

⊤ x

( i )

  • b ) ≥ 1_._

w,b

The boundary w

⊤ x + b = 0 is the maximum-margin hyperplane; points with y

( i ) ( w

⊤ x

( i )

  • b ) = 1

are the support vectors , which alone determine the solution.

Lagrange duality turns this constrained problem into a dual that depends only on inner

products:

L( w, b, α ) =

1

m

w

2

− αi y

( i ) ( w

⊤ x

( i )

  • b ) − 1 , αi ≥ 0_._

i =

Stationarity in w and b gives w = i

αiy

( i ) x

( i ) and i

αiy

( i ) = 0. Substituting back yields the

dual:

max

α

αi −

1

αiαjy

( i ) y

( j ) ⟨ x

( i ) , x

( j ) ⟩ , αi ≥ 0 ,

αiy

( i ) = 0_._

i =1 i,j i

The KKT conditions imply αi > 0 only for support vectors — sparsity that makes prediction

efficient.

The kernel trick. Because the dual uses only inner products ⟨ x

( i ) , x

( j ) ⟩, we can replace them

with a kernel K ( x, z ) = ϕ ( x )

⊤ ϕ ( z ), implicitly mapping data to a high-dimensional feature space

ϕ (·) without ever computing ϕ explicitly. Valid kernels (Mercer’s condition) are symmetric

positive semidefinite. Common choices:

  • Linear: K ( x, z ) = x

⊤ z.

  • Polynomial of degree d : K ( x, z ) = ( x

⊤ z + 1)

d .

  • Gaussian RBF: K ( x, z ) = exp − x − z

2

/ (2 σ

2 ) — an infinite-dimensional feature space.

Soft-margin SVM handles non-separable data by introducing slack variables ξi ≥ 0 measuring

margin violations:

min

w,b,ξ

m

1

w

2

  • C ξi s.t. y

( i ) ( w

⊤ x

( i )

  • b ) ≥ 1 − ξi, ξi ≥ 0_._

i =

The hyperparameter C > 0 trades off margin width against training error. Large C ⇒ low bias,

high variance (overfits); small C ⇒ wider margin, more violations but better generalization.

5. Learning Theory

Learning theory tells us when a model that fits training data will also generalize. The central

decomposition is the bias-variance tradeoff :

E ( h ( x ) − y )

2 = E[ h ( x )] − E[ y ]

2

  • E ( h ( x ) − E[ h ( x )])

2

  • σ

2 .

`

B

ia

s

2

x `

Var

ia

nce

x

irre

`

d

u

c

x

ible

Cj

j =

j

; θ ) =.

j

w (^) w

m

k

k

Σ n

w

( i )

, μ j

i j

, Σ j

i j

.

j

k

Practice Problem 6

You run k - means with k 2 on four 1 - D points { 0 , 1 , 9 , 10 }, with initial centroids μ 1

1 , μ 2 9. Execute two full iterations (assignment + update each). Report the cluster

assignments and centroids after each iteration. Does the algorithm converge?

  1. Assignment: c

( i ) := arg min j x

( i ) − μj

2

  1. Update: μj := |

1

|

i ∈ C

x

( i ) , where Cj = { i : c

( i ) = j }.

Each step monotonically decreases the distortion J = i

x

( i ) − μ c

( i )

2 , so the algorithm con-

verges to a local optimum. Run several random initializations and keep the lowest-distortion

result.

Mixture of Gaussians. Model p ( x ) =

k

ϕj N ( x | μj, Σ j ), with parameters ϕj (mixing

weights summing to 1), μj , Σ j. The direct MLE has no closed form because the cluster labels

are latent variables z

( i ) .

The EM algorithm iterates two steps:

  • E-step: compute responsibilities w

( i ) = P ( z

( i ) = j | x

( i )

ϕj N ( x

( i ) | μj, Σ j ) ∑

ϕ N ( x

( i ) | μ , Σ )

  • M-step: update parameters with w

( i ) as soft weights:

l l l l

w

( i )

x

( i )

w

( i )

( x

( i ) − μj )( x

( i ) − μj )

⊤

m

j (^) ( i )

i (^) i j

( i )

i j

EM monotonically increases the (observed-data) log-likelihood, but converges to a local maxi-

mum — hence the practical need for multiple restarts.

Jensen’s inequality underlies EM. For a concave function f (here, log), E[ f ( X )] ≤ f (E[ X ]).

EM constructs a lower bound (the ELBO) on the log-likelihood and tightens it at each E-step;

the M-step maximizes the bound. This guarantees monotonic increase of ℓ ( θ ).

Principal Component Analysis (PCA) finds a low-dimensional projection that preserves

variance. Center the data, compute the covariance Σ =

1 X

⊤ X , and take the top k eigenvectors

u 1 ,... , uk of Σ. The projection of x onto the principal subspace is x '→ U

⊤ x , where Uk =

[ u 1 · · · uk ]. Reconstruction x ˆ = UkU

⊤ x minimizes the squared reconstruction error over all

rank- k linear projections.

Choose k by the variance-retained criterion: pick the smallest k such that

j =

λ j

j =

λ j

i.e. 95% of variance is preserved. PCA is unsupervised: it ignores labels and may discard

directions that matter for classification — supervised alternatives include LDA.

7. Neural Networks & Backpropagation

A neural network composes simple linear-nonlinear layers. For an L - layer network with weight

matrices W

( l ) , bias vectors b

( l ) , and activation g :

a

(0) = x, z

( l ) = W

( l ) a

( l −1)

  • b

( l ) , a

( l ) = g z

( l ) , l = 1 ,... , L.

ϕj = Σ

2

i

Practice Problem 7

Consider a single-hidden-layer network with input x ∈ R

2 , two hidden ReLU units, and

θ

The output layer typically uses a different activation: sigmoid (or softmax) for classification,

identity for regression.

Activation functions.

  • Sigmoid σ ( z ) = 1 / (1 + e

−

z ): smooth, but saturates (gradient → 0 far from origin), and

outputs are non-zero-centered.

  • Tanh tanh( z ): zero-centered, still saturates.
  • ReLU max(0 , z ): no saturation for z > 0 , cheap gradient, but “dead” for z < 0 (zero

gradient). The modern default for hidden layers.

Loss functions. For binary classification, cross-entropy

J ( θ ) = −

y

( i ) log hθ ( x

( i ) ) + (1 − y

( i ) ) log(1 − hθ ( x

( i ) ))

matches the maximum-likelihood objective. For regression, squared error J =

1

i

( hθ ( x

( i ) ) −

y

( i ) )

2 .

Backpropagation computes ∇ θJ efficiently via the chain rule. Define the error at layer l as

δ

( l ) = ∂J/∂z

( l )

. Then

δ

( L ) = ∇ a

( L ) J ⊙ g

′ ( z

( L ) ) , δ

( l ) = W

( l +1)

⊤

δ

( l +1) ⊙ g

′ ( z

( l ) ).

Gradients w.r.t. parameters:

W

( l ) J^ =^ δ

( l ) a

( l −1)

⊤

, ∇ b

( l ) J^ =^ δ

( l ) .

The forward pass stores the activations a

( l ) and pre-activations z

( l ) ; the backward pass uses

them to assemble gradients in a single sweep, costing roughly twice the forward pass.

Optimizers.

  • SGD with mini-batches: θ → θ − α ∇ J ( θ ; B ). Noisy but often finds flat minima that gener-

alize well.

  • Momentum: v → βv + ∇ J , θ → θ − αv. Smooths out noisy gradients.
  • Adam: adaptive per-parameter learning rates via running first and second moment esti-

mates. Robust default for most modern training.

Practical notes. Initialize weights small and randomly (e.g. He or Xavier) — a zero initial-

ization collapses all units in a layer to identical gradients. Use normalization (BatchNorm,

LayerNorm) to stabilize deep training. Apply dropout ( p ≈ 0_._ 5 ) to regularize. Use a held-out

validation set to monitor for overfitting and apply early stopping.

2

Solution 4: 1 - D maximum-margin hyperplane

The two points are support vectors at the boundary. With canonical scaling y

( i ) ( wx

( i )

  • b ) = 1 :

(+1)( w · 1 + b ) = 1 ⇒ w + b = 1 , (−1)( w · (−1) + b ) = 1 ⇒ − w + b = − 1_._

Adding: 2 b = 0 ⇒ b = 0. Subtracting: 2 w = 2 ⇒ w = 1. The decision boundary is x = 0 ,

halfway between − 1 and +1. Margin = 2 / w = 2 / 1 = 2, which matches the geometric distance

2 between the two support vectors.

Solution 5: Bias-variance for polynomials

True function is quadratic-plus-noise, m = 30.

  • d = 1 (linear): high bias (cannot capture curvature), low variance ⇒ underfits.
  • d = 5 : moderate bias (can represent quadratic exactly), moderate variance. Should achieve

the lowest test error among the three.

  • d = 15 : low bias (can interpolate any 15 points), high variance (fits noise) ⇒ overfits.

Expected test error is minimized at d = 5 : it has enough capacity to fit the true quadratic, but

not so much that it fits the noise. To confirm, plot train vs. validation error across d and select

the elbow of the validation curve (cross-validation would give a principled choice).

Solution 6: k - means iterations

Iteration 1, Assignment: each point goes to the nearest centroid.

  • x = 0 : | 0 − 1 | = 1 < | 0 − 9 | = 9 ⇒ cluster 1.
  • x = 1 : | 1 − 1 | = 0 < 8 ⇒ cluster 1.
  • x = 9 : | 9 − 1 | = 8 > 0 ⇒ cluster 2.
  • x = 10 : | 10 − 1 | = 9 > 1 ⇒ cluster 2.

C 1 = { 0 , 1 }, C 2 = { 9 , 10 }.

Iteration 1, Update: μ 1 = (0 + 1) / 2 = 0_._ 5 , μ 2 = (9 + 10) / 2 = 9_._ 5.

Iteration 2, Assignment: nearest centroid for each point is unchanged ( 0_._ 5 is closer to 0 and

1 ; 9_._ 5 is closer to 9 and 10 ). So C 1 , C 2 stay the same.

Iteration 2, Update: μ 1 = 0_._ 5 , μ 2 = 9_._ 5 (no change). Algorithm has converged. Distortion

2

  • (1 − 0_._ 5)

2

  • (9 − 9_._ 5)

2

  • (10 − 9_._ 5)

2 = 4 · 0_._ 25 = 1.

Solution 7: Backprop on a tiny MLP

Let a

(0) = x ∈ R

2 , z

(1) = W

(1) x ∈ R

2 , a

(1) = ReLU( z

(1) ) ∈ R

2 , y ˆ = hθ ( x ) = W

(2) a

(1) ∈ R.

Define the output error δ

(2) = y ˆ − y ∈ R (this is ∂J/∂y ˆ, since ∂ (

1 ( y ˆ − y )

2 ) /∂y ˆ = y ˆ − y ).

Gradients w.r.t. W

(2) : since y ˆ = W

(2) a

(1) , we have ∂J/∂W

(2) = δ

(2) ( a

(1) )

⊤ , a 1 × 2 outer

product.

Backprop the error: δ

(1) = ( W

(2) )

⊤ δ

(2) ⊙ 1 { z

(1) > 0 }. The indicator is the ReLU derivative

(1 where the pre-activation is positive, 0 otherwise). The result δ

(1) ∈ R

2 .

Gradients w.r.t. W

(1) : ∂J/∂W

(1) = δ

(1) ( a

(0) )

⊤ = δ

(1) x

⊤ , a 2 × 2 outer product. Each row is

the gradient of J w.r.t. the corresponding row of W

(1) .

In words: the output error is multiplied by W

(2) (transposed) to give a hidden-layer error,

masked by the ReLU gate; that hidden error is then projected onto the input to give the input-

layer weight gradient. This factorization — “error times activation” — is exactly what makes

backprop a single backward sweep rather than O (params) separate chain-rule applications.

9. Summary & Further Reading

CS229’s four pillars form a coherent narrative. Supervised learning answers the question “how

do we predict y from x ?” — starting from the simplest linear model, generalizing through GLMs

to a principled family, and arriving at SVMs and neural networks that can fit nonlinear bound-

aries. Learning theory then asks “when can we trust the fit?” — bias-variance decomposition,

Hoeffding bounds, and VC dimension together explain why a low training error is necessary but

not sufficient for generalization. Unsupervised learning drops labels and asks “what structure is

in x alone?” — clusters, latent mixtures, and principal components all surface structure with-

out supervision. Finally, neural networks, formalized by backpropagation, scale these ideas to

high-dimensional function approximation and underpin modern deep learning.

A few recurring patterns are worth internalizing:

  • Maximum likelihood is the unifying principle. Linear regression, logistic regression,

GDA, and naive Bayes all reduce to MLE under different distributional assumptions; min-

imizing squared loss is MLE under Gaussian noise, and minimizing cross-entropy is MLE

under a categorical model.

  • The prediction-error-times-feature pattern ( y − hθ ( x )) x recurs in linear regression,

logistic regression, and GLMs — a consequence of the exponential-family link. Recognizing

this saves re-derivation each time.

  • Regularization is structural risk minimization in disguise. L2 ridge shrinks weights

smoothly; L1 lasso induces sparsity; both can be derived as MAP estimates under Gaussian

and Laplacian priors respectively.

  • Kernels and features are dual views. The dual SVM depends only on inner products,

which can be replaced by kernels — a trick that recurs in Gaussian processes, kernel PCA,

and kernel ridge regression.

Recommended further reading. The canonical reference for CS229 is Andrew Ng’s lecture

notes (https://cs229.stanford.edu/), which this guide closely follows. For deeper treat-

ment of learning theory, consult Understanding Machine Learning: From Theory to Algorithms

(Shalev-Shwartz & Ben-David). For convex optimization background, Boyd & Vandenberghe’s

Convex Optimization is the standard reference. For neural networks and deep learning, Good-

fellow, Bengio, & Courville’s Deep Learning covers backpropagation, optimizers, and modern

architectures in depth. Finally, Bishop’s Pattern Recognition and Machine Learning gives the

Bayesian perspective that complements the frequentist framing of CS229.