[KongchangAI]
· 3 min read· 1,570 words

Stanford CS229 Machine Learning Course: A Detailed Guide to Linear Regression and Gradient Descent

Stanford CS229 Machine Learning Course: A Detailed Guide to Linear Regression and Gradient Descent

The first three CS229 lectures build the supervised learning framework of models, cost functions, and optimization from linear regression.

This article reviews the first three lectures of Stanford's CS229 course: starting from the definition of supervised learning and a house price prediction example, it explains linear regression's model representation, squared error cost function and convex optimization properties, and compares batch versus stochastic gradient descent with mini-batch compromises. It also discusses non-convex optimization in modern ML, initialization strategies, and how over-parameterized models may break the traditional bias-variance tradeoff. Linear regression's notation and solution approach permeate later classification and exponential family models, while gradient descent is the core optimization tool throughout machine learning.

Course Overview: Starting from Linear Regression

The first three lectures of Stanford's CS229 machine learning course are led by a professor who systematically builds machine learning models from simple to complex. The course starts with the most basic linear regression, gradually transitioning to classification problems and introducing the unifying framework of exponential family models. The professor emphasizes that the structure of these models is highly similar—once you master the core ideas of linear regression, learning subsequent models becomes much easier.

According to a video shared by a Bilibili creator, the course first clarifies the definition of supervised learning: given a training set (consisting of inputs X and labels Y), the goal is to find a prediction function h that performs well on unseen data. Using house price prediction as an example, the professor demonstrates how to predict sale prices from features such as house area using the Ames dataset (available for download online).

Random sampling illustration

Linear Regression: Fitting a High-Dimensional Line

The goal of linear regression is to find a set of parameters θ such that the predicted value hθ(x) = θ0 + θ1x1 + ... + θdxd is as close as possible to the true value. By introducing the convention x0=1, the professor converts the affine model into a purely linear form, simplifying the notation. He emphasizes that although linear regression appears simple, through feature embedding, high-dimensional linear models can still achieve state-of-the-art performance in many domains.

The course shows visualizations of real data: house area is positively correlated with price, but there is fluctuation, indicating that other factors also affect price. This is precisely why multiple features are introduced.

Data representation illustration

Feature Embedding refers to mapping raw inputs through some nonlinear transformation into a higher-dimensional feature space, and then applying a linear model in that high-dimensional space. For example, for a one-dimensional input x, one can construct a feature vector [1, x, x², x³] and fit the linear function θ₀ + θ₁x + θ₂x² + θ₃x³, which is essentially equivalent to cubic polynomial regression, yet the solution process still fully follows the closed-form or gradient descent methods of linear regression. Similarly, in house price prediction, one can add interaction terms such as area squared or number of rooms × area, enabling the linear model to capture nonlinear relationships. This property of being "linear in parameters, nonlinear in inputs" is the key to the enduring appeal of linear models: as long as feature engineering is sufficiently thorough, high-dimensional linear models can often approach the performance of complex models in domains such as text classification and recommender systems, while maintaining interpretability and training efficiency.

Cost Function and Optimization Problem

To measure how good a model is, the course defines the squared error cost function J(θ) = 1/2 Σ (hθ(xi) - yi)^2. The professor explains the origin of the 1/2 coefficient: it cancels with the 2 from the squared term during differentiation, simplifying calculations. He emphasizes that in actual optimization, we only care about the parameter θ that minimizes J(θ), not the specific numerical value of J(θ). This cost function is called least squares, and its choice is partly out of computational convenience.

The cost function transforms the model selection problem into an optimization problem: finding the θ in parameter space that minimizes J(θ). For linear regression, this function is convex and has a unique global minimum.

Optimization problem illustration

Convex Functions and Global Optima are core concepts for understanding the optimization properties of linear regression. A function J(θ) is called convex if for any two points θ₁, θ₂ and any λ∈[0,1], it satisfies J(λθ₁+(1-λ)θ₂) ≤ λJ(θ₁)+(1-λ)J(θ₂), which geometrically appears as a "bowl-shaped" curve. The squared error cost function J(θ)=½Σ(hθ(x⁽ⁱ⁾)-y⁽ⁱ⁾)² is a quadratic form in θ, with Hessian matrix XᵀX (where X is the design matrix); J(θ) is convex when XᵀX is positive semidefinite. The significance of convexity is that any local minimum is a global minimum, and if XᵀX is positive definite, the global minimum is unique. This means that gradient descent in linear regression will not get trapped in poor local optima—as long as the learning rate is appropriate and iterations are sufficient, it will always converge near the optimal solution. While the cost functions of subsequent models such as logistic regression remain convex, the optimization of non-convex models like neural networks loses this guarantee.

Gradient Descent: Batch and Stochastic

The course introduces the gradient descent algorithm: starting from an initial guess θ, iteratively update parameters along the negative gradient direction. The learning rate α controls the step size—too large causes oscillation or even divergence, too small leads to slow convergence. For linear regression, gradient computation can be simplified to the product of the error term and feature values.

The professor compares batch gradient descent and stochastic gradient descent in detail. The batch method uses all training data to compute the gradient each time—accurate but computationally expensive; the stochastic method uses only one sample each time—fast but noisy. In practice, mini-batch is often used as a compromise, leveraging hardware parallelism, with batch sizes typically set to values like 128. The convergence of stochastic gradient descent is still guaranteed under loose conditions, and work such as Hogwild! has demonstrated its robustness.

Local minimum illustration

Learning Rate and Convergence are key to whether gradient descent works effectively. The learning rate α determines the step size of each parameter update: if α is too large, parameter updates may overshoot the minimum, causing the cost function to oscillate or even diverge (numerical overflow); if α is too small, convergence is extremely slow and training time becomes unacceptable. In practice, learning rate decay strategies are often used, such as proportionally reducing α each iteration, or using adaptive optimizers like AdaGrad or Adam that adjust the effective step size individually for each parameter. For the convex cost function of linear regression, there theoretically exists a critical learning rate α* (related to the largest eigenvalue of XᵀX); when α<α*, batch gradient descent is guaranteed to converge. Stochastic gradient descent requires the Robbins-Monro conditions (Σα_t=∞ and Σα_t²<∞) to converge almost surely. Although these theories do not directly apply to deep networks, they provide intuition for tuning: monitoring whether the cost curve decreases steadily is a practical way to judge whether the learning rate is appropriate.

Non-Convex Optimization and Modern Practice

The professor acknowledges that loss functions in modern machine learning are often non-convex, with many local minima. Gradient descent may get trapped in poor local optima, and there is a lack of reliable criteria for judging convergence. He cites a DeepMind paper noting that sometimes models need to be trained longer to achieve better results, and the industry often decides training duration based on experience.

Regarding initialization, random initialization is common practice, but the high cost of training large-scale models has prompted more systematic initialization strategies. The course also touches on overfitting and notes that modern models (such as over-parameterized networks) may break the traditional bias-variance tradeoff, perfectly interpolating training data while still generalizing well.

Over-parameterization and Double Descent are important background for understanding the generalization phenomena of modern models. The traditional bias-variance tradeoff holds that as model capacity increases beyond the "interpolation threshold" (the number of parameters that exactly perfectly fits the training data), test error first decreases then increases; however, Belkin et al. (2019) found that continuing to increase model capacity beyond the interpolation threshold causes test error to decrease again, forming a "double descent" curve. This phenomenon challenges classical statistical learning theory. One explanation is that over-parameterized networks contain numerous perfect interpolation solutions in high-dimensional parameter space, and the implicit bias of stochastic gradient descent tends to select the "simplest" or "smoothest" among them, thereby achieving good generalization. This explains why modern deep networks with far more parameters than training samples can still generalize, and also suggests that practitioners need not panic when training error is zero—the key remains validation set performance.

Summary and Extensions

This lecture establishes the basic framework of supervised learning: model representation, cost function, and optimization algorithm. Linear regression serves as the starting point, and its notation system and solution approach will permeate subsequent topics such as classification and exponential family models. Gradient descent and its variants are core optimization tools in machine learning, and understanding their principles is essential for mastering more complex models. The course briefly mentions the normal equation at the end but emphasizes that it is not the focus.

(Note: This article is based on publicly available course videos and is for learning reference only.)

One-line Summary

The first three CS229 lectures start from linear regression to build the model, cost function, and optimization framework of supervised learning.

Paragraph Summary

This article reviews the core content of the first three lectures of Stanford's CS229 course: starting from the definition of supervised learning and a house price prediction example, it systematically explains the model representation of linear regression, the squared error cost function and its convex optimization properties, and provides an in-depth comparison of batch gradient descent versus stochastic gradient descent along with the mini-batch compromise. The course also discusses the prevalence of non-convex optimization in modern machine learning, the importance of initialization strategies, and the phenomenon that over-parameterized models may break the traditional bias-variance tradeoff. The article emphasizes that linear regression's notation system and solution approach will permeate subsequent classification and exponential family models, and that gradient descent is the core optimization tool throughout machine learning.

#Stanford CS229#linear regression#gradient descent#cost function#supervised learning#stochastic gradient descent#non-convex optimization#over-parameterization
Share:

Related articles