Skip to main content
Machine Learning

Gradient Descent, Regularization, and Logistic Regression

📅 Published: 2026-06-29
🎓 Level: postgraduate
👥 Audience: Postgraduate students in Machine Learning

Prerequisite Knowledge

This lecture builds on the following concepts from earlier lectures. If any feel unfamiliar, review the linked notes before proceeding.

Previously Covered in This Subject

  • Linear Regression — covered in Lecture 1
  • Logistic Regression — covered in Lecture 1
  • Linear Basis Functions — covered in Lecture 3
  • Gradient Descent — covered in Lecture 4
  • Overfitting — covered in Lecture 4

Gradient Descent, Regularization, and Logistic Regression

This lecture bridges the gap between linear regression (Lecture 4) and logistic regression (Lecture 7). It covers three major pillars. : (1) gradient descent as the iterative workhorse for training linear models, (2) regularization (Ridge, Lasso, Elastic Net) as the primary defense against overfitting, and (3) logistic regression as the transition from regression to probabilistic binary classification. Along the way, the lecture develops evaluation metrics, the bias-variance tradeoff, and practical Python implementation. All building toward the bike rental prediction assignment.

5.1 Lecture Scope

This lecture spans the bridge between linear regression (Lecture 4) and logistic regression (Lecture 7). It introduces regularization. A substantial topic that extends beyond the core linear regression curriculum — and provides a full gradient descent implementation in Python.

Topic Connects To
Gradient Descent (full worked example) Lecture 4 — Linear Regression
Types of Gradient Descent (batch, SGD, mini-batch) Lecture 4 — Optimization
Evaluation Metrics (MAE, MSE, RMSE, R-squared) Lecture 4 — Model Evaluation
Linear Basis Functions Lecture 4 — Feature Engineering
Underfitting, Overfitting, Bias-Variance Tradeoff Lecture 4 — Model Selection
Handling Overfitting (data size, early stopping) Lecture 4 — Model Selection
Regularization (Ridge L2, Lasso L1, Elastic Net) New material — bridges Lectures 4 and 7
Python Implementation (NumPy + Scikit-learn) Practical application
Logistic Regression (sigmoid, log loss, decision boundary) Lecture 7 — Classification

Note: Regularization (Ridge, Lasso, Elastic Net) is covered here as a natural extension of overfitting prevention. It does not appear in the Lecture 4 mapping but is essential for the bike rental assignment and for understanding regularized logistic regression in Lecture 7.

5.2 Gradient Descent — Full Worked Example (Coronary Heart Disease)

Hook. Imagine you are a blindfolded hiker standing somewhere on a foggy mountain. Your only goal. : reach the valley floor. You can't see the whole mountain. But you can feel the slope under your boots at every step. Take one step downhill, feel again, step again. That is exactly how gradient descent learns the best line for your data.

Intuition + Analogy. The "hiker" is your model's parameters (the weights ). The "mountain" is the cost function. A bowl-shaped surface that measures how wrong your predictions are. The hiker starts at a random position (random initial weights). At each step, the hiker feels the steepest downhill direction (the gradient), then takes a step of size (the learning rate) in that direction. The hiker's position changes — which means the line (hypothesis) changes. After enough steps, the hiker reaches the bottom of the bowl. : the global minimum, where predictions are as good as they can get.

Where the analogy breaks: a real hiker might get stuck on a ledge; gradient descent on a convex (bowl-shaped) cost function is guaranteed to find the bottom. For non-convex functions (like neural networks), the hiker can get stuck in local valleys. But for linear regression with MSE, the surface is convex, so the hiker always finds the true bottom.

Purpose. Gradient descent finds the parameter values that minimize the cost function . The total prediction error across all training examples. It is an iterative numerical method. Unlike the closed-form normal equations (), which solve the problem exactly in one shot, gradient descent steps toward the solution gradually. Why use an iterative method when a closed-form exists? Because the normal equations require inverting a matrix, which costs — impractical when is large (thousands of features). Gradient descent scales to high dimensions.

Inputs & Outputs.

  • Input: Training data examples, each with features, plus a bias column . Hyperparameters: learning rate , number of iterations (or a stopping condition).
  • Output: A parameter vector that (approximately) minimizes the cost function. The trained model is .

Steps — Batch Gradient Descent Algorithm.

  1. Initialize to a small random vector (or zeros). Set iteration counter .
  2. Repeat until convergence or :
  • (a) Compute predictions for ALL examples: for .
  • (b) Compute the gradient of the cost w.r.t. each parameter:

  • (c) Update all parameters simultaneously:

  • (d) .
  1. Return .

Why simultaneous update matters. Compute ALL the temporary gradients first (using the old values), then update ALL parameters at once. If you update first and then use the new to compute the gradient for , you are not following the true gradient. You are following a corrupted direction. Use temporary variables:

Then apply: for all .

Trace — First Iteration on Coronary Heart Disease Data.

Setup. Predict relative risk of heart disease from BMI () and diastolic pressure ().

Data:

Patient BMI () Diastolic Pressure () Actual Risk ()
1 35 80 1.81
2 28 75 1.55
3 32 85 1.92

Step 1 — Compute predictions :

  • Patient 1:
  • Patient 2:
  • Patient 3:

Step 2 — Compute errors :

  • Patient 1:
  • Patient 2:
  • Patient 3:

Step 3 — Gradient for bias ( always):

Step 4 — Gradient for (BMI):

Step 5 — Gradient for (Diastolic Pressure):

Step 6 — Simultaneous update:

Result: After one iteration, .

Sense-check: The errors were mostly negative (predictions below actual values), so the weights increased. The line shifted upward. This is exactly what we want. : the model is correcting its underestimation.

Pitfalls.

  1. Forgetting simultaneous update. Updating first and then using the new to compute 's gradient gives incorrect results. Always use temporary variables.
  2. Choosing too large a learning rate. If is too big, the hiker takes giant leaps and overshoots the valley — the cost diverges to infinity instead of converging. If is too small, convergence is painfully slow.
  3. Not scaling features. If BMI ranges from 20–40 and diastolic pressure ranges from 60–100, the gradients for different parameters have very different scales. Feature scaling (standardizing to zero mean, unit variance) makes gradient descent converge much faster. Without scaling, the cost surface becomes an elongated bowl and the hiker zigzags.
  4. Confusing "slope" and "line." The professor emphasized this repeatedly: the hiker's position changes at each step (the line changes), not the mountain (slope of the cost function). The slope underfoot is different at the new position.

Q: Is "slope" the same as "weight parameter"?

A: Slope is a weight parameter of individual features. We are updating the slope, the line, the location. The hiker starts from a random position and every time we are updating the position of the hiker. Practically, when you see the line changes. The hiker moves one step, and the line changes. It is not the slope of the cost function that changes, it is where you are on it.

Recap. Gradient descent iteratively updates parameters by stepping downhill on the cost surface. Each step uses the average gradient across ALL training examples (batch). The learning rate controls step size. Simultaneous update is mandatory. After enough iterations, the parameters converge to values that minimize prediction error. Bridge: The example above uses ALL three patients per update. That makes it batch gradient descent. Section 5.3 shows two faster (but noisier) alternatives.

Real-World & Domain Connection. Gradient descent powers virtually every modern ML training loop. From linear regression to deep neural networks with billions of parameters. The coronary heart disease example is deliberately small (3 patients) to make the arithmetic traceable by hand, which is exactly what exam problems will ask for. In practice, libraries like scikit-learn's SGDRegressor and deep learning frameworks (PyTorch, TensorFlow) implement highly optimized variants. The core idea — take a step downhill — remains the same whether you have 3 data points or 300 million. The math from this section appears verbatim in the standard optimization reference (Tan et al., AppE), which defines gradient descent as — identical to our update rule with (their notation for learning rate) playing the role of .


5.2.2 Symbol Registry

Symbol Meaning Type Domain
Intercept (bias) scalar
Weight for BMI (feature 1) scalar
Weight for diastolic pressure (feature 2) scalar
BMI value scalar
Diastolic pressure value scalar
Actual relative risk scalar
Predicted relative risk scalar
Learning rate (step size); standard texts also use or scalar
Number of training examples scalar

5.3 Vectorized vs. Scalar Representation

Hook. Multiplying a weight vector by a single feature vector gives ONE prediction. Multiplying the full data matrix by the weight vector gives ALL predictions at once. The difference between these two forms is the difference between doing laundry one sock at a time versus loading the whole machine.

Intuition + Analogy. Think of a restaurant kitchen. A single order ticket (one row of features) times the recipe card (the weights ) gives one dish. But the dinner-rush stack of ALL tickets (the full design matrix ) times the recipe card gives every dish at once. A column of completed orders. That is the difference between the scalar form and the vectorized form. : one prediction versus all predictions. The vectorized form is not just notationally cleaner; it is what makes computers fast — matrix multiplication is heavily optimized in libraries like NumPy and runs on specialized hardware.

Two Forms of the Hypothesis.

Scalar form — for a single training example. Given one feature vector (with for the bias):

Here is a dot product between two vectors — the result is a single scalar (one predicted value).

Matrix/vectorized form — for ALL training examples. Given the full design matrix (one row per example, one column per feature, first column all ones):

Here is a matrix-vector product producing a column vector of predictions — one entry per training example. The result is in .

Key distinction: is a scalar (one number). is a column vector (N numbers). The professor emphasized. : " is for one particular training example. This is for one record. Capital is for all the examples together."

Pitfall. Confusing with . The former returns a column vector of predictions; the latter returns a single number. When implementing gradient descent in code, you use the vectorized form for efficiency. One matrix multiply computes all predictions, then one vector subtract computes all errors, then one matrix multiply computes the full gradient. The scalar form is for understanding; the vectorized form is for implementation.

Recap. The scalar form makes a single prediction. The vectorized form makes all predictions at once. Both represent the same linear model; they differ only in how many examples they process simultaneously. Bridge: The vectorized form is what makes batch gradient descent efficient. It computes the gradient for ALL examples in one matrix operation, which is why NumPy implementations run orders of magnitude faster than nested loops.

Real-World & Domain Connection. Vectorization is the reason modern ML can scale. Libraries like NumPy and PyTorch delegate matrix multiplication to BLAS (Basic Linear Algebra Subprograms). Highly tuned Fortran/C routines that exploit CPU cache hierarchies and SIMD instructions. A single np.dot(X, theta) call can process millions of examples in milliseconds. The same principle applies at larger scale. : GPU-based training in deep learning relies entirely on batched matrix operations.


5.2.1 Symbol Registry

Symbol Meaning Type Dimension
Single feature vector (one example, with bias) vector
Design matrix (all examples, with bias column) matrix
Parameter (weight) vector vector
Scalar prediction for one example scalar
Vector of predictions for all examples vector

5.4 Types of Gradient Descent

Hook. Batch gradient descent reads every book in the library before taking one step. Stochastic gradient descent reads one random page and steps immediately. Mini-batch reads a chapter at a time. Which one reaches the exit first?

Intuition + Analogy. Imagine you are learning to cook by tasting your dish. Batch. : you cook the ENTIRE meal, taste everything, then adjust the seasoning once. Accurate, but slow. Stochastic (SGD): you taste ONE spoonful right after adding it, adjust immediately, repeat. Fast and jittery. You might over-salt one bite but correct it on the next. Mini-batch: you taste 32 spoonfuls, average the flavor, then adjust. The sweet spot between speed and stability. The "noise" in SGD is not always bad — it can help the model escape shallow local minima in non-convex problems (like neural networks).

Three Variants — Formal Definition.

Consider a training set of examples. All three variants use the same update rule:

The difference is which examples are used to compute the gradient:

  1. Batch Gradient Descent. Uses ALL examples.

One update per full pass through the dataset. Stable, deterministic, but slow for large .

  1. Stochastic Gradient Descent (SGD). Uses ONE randomly chosen example per step.

updates per full pass (epoch). Very fast, noisy. The parameter path zigzags toward the minimum. The noise acts as a natural regularizer, sometimes helping generalization.

  1. Mini-Batch Gradient Descent. Uses a random subset of examples ().

updates per epoch. Balances speed and stability. Typical batch sizes: 32, 64, 128, 256. This is the default in modern deep learning frameworks.

Comparison Table:

Property Batch Stochastic (SGD) Mini-Batch
Examples per step (all) 1 (e.g., 32–256)
Updates per epoch 1
Speed per epoch Slowest Fastest Fast
Gradient noise None (deterministic) High Moderate
Convergence path Smooth, direct Zigzag, noisy Smoother than SGD
Memory needed All data in RAM One example Batch in RAM
Best for Small datasets () Very large datasets, streaming Most practical cases

When to pick which:

  • Batch: small datasets where a single matrix multiply is cheap.
  • SGD: massive or streaming data where you cannot fit everything in memory.
  • Mini-batch: the default choice for most real-world training, especially with GPUs (batch sizes are tuned to fit GPU memory).

:::

Pitfalls.

  1. Calling mini-batch "SGD." In modern deep learning, "SGD" almost always means mini-batch SGD. Pure SGD (batch size = 1) is rare in practice. Know the context.
  2. Batch-too-large trap. Batch gradient descent on 10 million examples requires computing the gradient over ALL of them before one update. If your machine cannot hold the entire dataset in RAM, it may crash or thrash.
  3. Noise-is-good misconception. SGD noise helps escape shallow local minima but hurts for convex problems (linear regression). For convex problems, batch or mini-batch with small noise is preferred because the global minimum exists and noise just slows convergence.

Recap. Batch uses all data, SGD uses one point, mini-batch uses a small set. Mini-batch is the practical default. The worked example in Section 5.1 is batch gradient descent because . All data fits in one step. Bridge: These variants share the same core math; only the data sampled for each gradient computation differs. In Section 5.14, we see mini-batch SGD implemented via scikit-learn's SGDRegressor.

Real-World & Domain Connection. Google's BERT language model was trained with a batch size of 256–512 sequences. GPT-3 used 3.2 million samples per batch (distributed across thousands of GPUs). The choice of batch size directly affects training time and model quality. Scikit-learn's SGDRegressor and SGDClassifier implement mini-batch SGD with built-in learning rate schedules and regularization. The partial_fit() method in scikit-learn allows true online learning where data arrives in a stream and the model updates continuously.


5.5 Evaluation Metrics for Regression Models

Hook. You have trained a regression model. How do you know if it is any good? A single number like "average error" sounds nice. But is it enough? The answer depends on whether you care more about a few huge mistakes or many small ones.

Intuition + Analogy. Think of three archers at a range. Archer A measures how far each arrow lands from the bullseye and averages that distance. That is MAE. Archer B squares each miss distance before averaging, so a single wild shot (10 cm off) counts 100 times more than a near-miss (1 cm off) — that is MSE. Archer C takes the square root of Archer B's score to get back to centimeters — that is RMSE. Archer D asks. : "What fraction of the total spread in the target is explained by my skill?" — that is . Each metric answers a different question about the same set of arrows.

Metric Definitions.

Let be the predicted value and be the actual value for .

Mean Absolute Error (MAE):

  • Each error contributes proportionally to its size. A 10-unit error is 10 times worse than a 1-unit error.
  • Same units as the target variable.
  • Robust to outliers (no squaring).

Mean Squared Error (MSE):

  • Large errors are penalized quadratically. A 10-unit error contributes 100 to the sum; a 1-unit error contributes 1.
  • Units are the square of the target units (e.g., dollars-squared).
  • This is the cost function that gradient descent minimizes.

Root Mean Squared Error (RMSE):

  • Same units as the target variable. Easier to interpret than MSE.
  • Still sensitive to large errors (the square happens before the root).

R-squared () — Coefficient of Determination:

  • is the mean of the target values.
  • : perfect fit (predictions match all points exactly).
  • : model is no better than predicting the mean every time.
  • : model is worse than just predicting the mean. (Yes, this can happen with bad models.)
  • Dimensionless — always between and 1 (for linear regression with intercept, between 0 and 1).

Comparison Table:

Metric Formula key Outlier sensitivity Units Best when
MAE Absolute difference Low Same as Outliers present, equal weight to all errors
MSE Squared difference High You want to heavily penalize large errors
RMSE Root of MSE High Same as You want interpretable units + outlier sensitivity
1 - MSE/Var() Inherits from MSE Dimensionless Comparing models across different scales

Worked Example. Suppose actual house prices (in $1000s): . Predictions: .

Errors: , , .

  • MAE = (thousand dollars)
  • MSE =
  • RMSE = (thousand dollars)
  • : , Variance of = . .

Sense-check: means the model explains 94% of the variance. An excellent fit. MAE and RMSE happen to be equal here because all errors have the same magnitude; when errors vary, RMSE exceeds MAE.

Pitfalls.

  1. always increases with more features. Adding random noise as a "feature" can boost — it does not mean the model improved. Use adjusted for model comparison with different numbers of predictors.
  2. RMSE vs. MAE — pick based on your loss function. If your business cost grows quadratically with error (e.g., financial risk), use MSE/RMSE. If cost is linear (e.g., delivery time estimation), MAE may be more appropriate.
  3. MAE is not differentiable at zero. This is why MSE is used as the cost function for gradient descent — MSE is smooth everywhere, while MAE has a kink at error = 0. You cannot gradient-descent on MAE directly (though subgradient methods exist).

Recap. MAE treats all errors equally. MSE/RMSE punish large errors disproportionately. tells you what fraction of the target's variance your model captures. For gradient descent, MSE is the default because it is differentiable. Bridge: These metrics are used to evaluate models in the bike rental assignment (Section 5.19), where the target metric is RMSLE. A variant of RMSE that operates in log-space.

Real-World & Domain Connection. Kaggle competitions frequently use RMSE or MAE as evaluation metrics. The choice between them is often domain-driven. : weather forecasting uses MAE (a 2-degree error is twice as bad as a 1-degree error, no more). Financial risk modeling uses MSE (a $1000 loss is 100x worse than a $100 loss). The standard regression reference (Tan et al., AppD) defines the error function in terms of absolute error and squared error . Exactly matching the lecture's presentation.


5.6 Linear Basis Functions and Model Linearity

Hook. Is a linear model? It has an in it. So it must be nonlinear, right? Wrong. The model is linear in its parameters, not its inputs. This one insight unlocks a universe of flexible models that are still computationally simple to fit.

Intuition + Analogy. Think of a chef's recipe. The ingredients (flour, sugar, eggs) are the features . The recipe itself. How much of each ingredient to use — is the parameters . The dish is the prediction. A linear model means the recipe is a simple weighted sum. : "2 cups flour + 1 cup sugar + 3 eggs." If you transform the ingredients before measuring (grinding flour to different coarseness, caramelizing sugar, whipping eggs), you are applying basis functions . The recipe is still a weighted sum — but now of transformed ingredients. You can create incredibly complex dishes from simple recipes by transforming the ingredients first.

Definition. A model is linear when it is linear with respect to the parameters , not when it is linear with respect to the input features . The professor emphasized this distinction repeatedly. : "Parameter and feature are different."

General form of a linear model with basis functions:

where is the -th basis function applied to input , and (the bias term).

Why this matters: The model is still solved by the same linear regression machinery. The normal equations or gradient descent — regardless of how complex the basis functions are. The cost function remains convex in . You get nonlinear predictive power with linear computational cost.

Common basis functions (from Bishop §3.1):

  • Polynomial: — standard polynomial regression. . Fits curves of degree .
  • Gaussian (RBF): — each basis function is a bell curve centered at . Good for local patterns; the model learns which centers matter.
  • Sigmoidal: — S-shaped functions. Capture threshold effects and saturating relationships.

Linear vs. nonlinear in :

Pitfalls.

  1. Confusing parameter linearity with input linearity. This is the #1 conceptual trap. The professor's exam questions will test whether you can identify which models are "linear models" — check the parameters, not the inputs.
  2. Too many basis functions = overfitting. If you use 100 polynomial terms ( for ) on 50 data points, the model will interpolate every point perfectly and be useless for prediction. More basis functions require more data.
  3. Basis function choice matters more than you think. Polynomials are global (changing one coefficient affects predictions everywhere). Gaussians are local (each bell curve only affects predictions near its center). Pick based on your domain: smooth global trends → polynomials; local patterns → Gaussians.

Recap. A model is linear if it is a weighted sum of transformed features. The transforms (basis functions) can be as nonlinear as you want. Polynomials, Gaussians, sigmoids — and the model remains computationally simple to fit. This is the bridge from simple straight lines to flexible curves. Bridge: Basis functions directly connect to the bias-variance tradeoff (Section 5.6). : more basis functions = more flexibility = lower bias but higher variance.

Real-World & Domain Connection. Polynomial basis functions are used in econometrics for modeling nonlinear trends (GDP growth over time). Gaussian basis functions appear in radial basis function (RBF) networks and kernel methods. They are the foundation of Support Vector Machines with RBF kernels. The standard ML reference (Bishop, §3.1) presents exactly the same three families of basis functions, confirming the lecture's coverage aligns with the canonical textbook treatment.


5.7 Underfitting, Overfitting, and the Bias-Variance Tradeoff

Hook. A lazy student who never studies fails both the practice test and the real exam. A student who memorizes every practice question scores 100% on the practice test but fails the exam. The good student studies the concepts and passes both. Machine learning models have the exact same three personalities.

Intuition + Analogy. The professor's three-student analogy is the canonical mental model for this entire topic — use it for every exam question.

  • The Lazy Student (Underfitting / High Bias). Never studies. Has completely wrong assumptions about everything. Given a sample paper (training data), scores zero. Given the actual exam (test data), scores zero. The model is too simple to capture any pattern at all. High error everywhere.
  • The Memorizer (Overfitting / High Variance). By-hearts every question and every answer from the sample paper without understanding the concepts. On the same sample paper, scores 100. But when given new questions on the actual exam, fails because they never learned the underlying concept. Low training error, high test error.
  • The Good Student (Correct Fit). Studies the concepts and understands the underlying patterns. Does well on the sample paper AND on the actual exam. Low error on both.

Mapping to ML terminology:

  • "Assumptions" = Bias. The lazy student has rigid, wrong assumptions → high bias.
  • "Sensitivity to specific questions" = Variance. The memorizer's performance swings wildly depending on which exact questions appear → high variance.
  • "Concepts" = The true underlying function the model should learn.

Formal Definitions.

Bias. Error from overly simple model assumptions. A high-bias model systematically misses the true pattern (like always fitting a straight line to a curve). It underfits.

Variance. Error from the model being too sensitive to small fluctuations in the training data. A high-variance model treats noise as signal (like fitting every random wiggle). It overfits.

The tradeoff: You cannot simultaneously minimize both. Simpler models have high bias but low variance. Complex models have low bias but high variance. The goal is the sweet spot in the middle.

Visual Intuition — The Bias-Variance Graph:

  • X-axis: Model complexity (e.g., polynomial degree).
  • Y-axis: Error.
  • Training error curve: Starts high on the left (simple model cannot fit training data), decreases monotonically as complexity increases, asymptotically approaches zero.
  • Test error curve: U-shaped. High on the left (underfitting), drops to a minimum at optimal complexity, then rises again on the right (overfitting).
  • The gap between training and test error widens as overfitting sets in — this gap is the variance.
  • Landmark: The optimal model complexity is at the bottom of the test-error U-curve.
  • Takeaway: The best model is NOT the one with the lowest training error. It is the one with the lowest test error.

Assumptions & Scope.

  • The bias-variance decomposition assumes the loss function is squared error. For other loss functions (e.g., absolute error, 0-1 loss), the decomposition is more complex.
  • The decomposition requires the model to be trained on different samples from the same distribution. In practice, we approximate this with train/validation/test splits.
  • Bias and variance are defined with respect to the expectation over training sets — they are population concepts, not single-dataset properties.

Pitfalls.

  1. "My model has 99% training accuracy, so it must be great." This is the memorizer's trap. High training accuracy with poor test accuracy is the textbook symptom of overfitting.
  2. "I will just use a more complex model to get better results." More complexity reduces bias but increases variance. Without more data or regularization, you are trading one problem for another.
  3. Confusing the direction of the tradeoff. High bias = underfitting (model too simple). High variance = overfitting (model too complex). The professor WILL test this mapping on the exam.
  4. Thinking bias-variance applies only to polynomials. It applies to ALL model families: decision tree depth, k in KNN (small k = high variance), regularization strength (small = high variance), neural network size.

Recap. Underfitting = high bias = lazy student = model too simple. Overfitting = high variance = memorizer = model too complex. The sweet spot balances both. The test error U-curve guides model selection. Bridge: The next section (5.7) presents three practical fixes for overfitting. Regularization (Sections 5.8–5.12) is the most important one. It formalizes the bias-variance tradeoff into a tunable parameter .

Real-World & Domain Connection. The bias-variance tradeoff is a universal concept in ML. In deep learning, the "double descent" phenomenon (where test error decreases AGAIN after the interpolation threshold for very large models) challenges the classical U-curve but does not invalidate the core insight. : model capacity must be matched to data volume. In practice, the tradeoff is navigated through cross-validation: try different model complexities, pick the one with the lowest validation error.


5.8 Handling Overfitting

Hook. Your model memorized the training data perfectly but fails on new data. You have three levers to pull. : feed it more data, make it simpler, or tell it when to stop learning. Each lever attacks overfitting from a different angle.

Intuition + Analogy. The professor's three strategies map to everyday fixes:

  1. More data (increase training size). The memorizer student who by-hearted 15 questions is exposed when the exam has 100 new questions. Give the same complex model 100 data points instead of 15, and it becomes much harder to memorize every noise pattern. The data volume forces the model to find the true pattern.
  1. Simpler model (reduce complexity). If the true function is a gentle curve (quadratic), using a model with 300 polynomial terms is like using a flamethrower to light a candle. Use the right tool for the job.
  1. Early stopping. The model is like a student who studies for 10 hours. For the first 6 hours, they learn concepts (training and validation error both drop). In the last 4 hours, they start memorizing typos in the textbook (training error drops further, but validation error starts rising). Stop them at hour 6.

Strategy 1 — Increase Training Data Size.

  • With 15 data points, a high-degree polynomial can wiggle through every point and memorize noise.
  • With 100+ data points, the same polynomial is forced to approximate the underlying trend because no single curve can exactly pass through 100 noisy points.
  • RMSE behavior:
  • Simple model (low order): RMSE plateaus at a higher error level as training size grows — it cannot capture the pattern even with infinite data (high bias).
  • Complex model (high order): RMSE plateaus at a lower error level — IF the dataset is large enough. More data compensates for high variance.
  • Key insight: When using a complex model, you MUST have a large training set. Model complexity and data volume must grow together.

Strategy 2 — Reduce Model Complexity.

  • If the true function is quadratic ():
  • Order 1 (line): underfits — cannot capture the curve.
  • Order 2 (quadratic): correct fit.
  • Order 300: massively overfits — 300 degrees of freedom for a degree-2 problem.
  • The right choice matches the true complexity of the data-generating process.
  • In practice, you try multiple complexities and use validation error to pick the best one (this is called model selection).

Strategy 3 — Early Stopping (for Iterative Models Only).

  • Applies to: Models trained iteratively — gradient descent, neural networks, logistic regression with gradient descent.
  • Does NOT apply to: Models with closed-form solutions — linear regression (normal equations), KNN, Naive Bayes. These do not "iterate" through data; they compute parameters in one shot.

How it works:

  • Plot training error and validation error against epoch number (one epoch = one full pass through the dataset).
  • Training error: decreases monotonically (model keeps fitting better).
  • Validation error: U-shaped. Decreases initially (model learning patterns), reaches a minimum at the best model point, then increases (model memorizing noise).
  • Stop training at the validation error minimum. This is the moment when the model has learned the signal but has not yet started fitting the noise.

Implementation options:

  1. Fixed number of iterations (epochs) — set after observing the validation curve.
  2. Threshold on error metric — e.g., stop when validation RMSE < 0.5.
  3. Patience-based — stop when validation error has not improved for consecutive epochs (common in deep learning: early_stopping = EarlyStopping(patience=10)).

Pitfalls.

  1. Using early stopping on non-iterative models. KNN, Naive Bayes, and closed-form linear regression do not iterate through data — early stopping is meaningless for them.
  2. Watching training error only. Training error always decreases. If you use training error as your stopping criterion, you will never stop — the model will overfit completely.
  3. Validation set leakage. If you use the validation set to decide when to stop AND to tune hyperparameters, your validation error becomes optimistically biased. Use a separate test set for final evaluation, never touched during training or model selection.

Recap. Fight overfitting with three weapons: more data (drowns out noise), simpler models (matches true complexity), and early stopping (halts before memorization). These are not mutually exclusive. Use all three when possible. Bridge: The fourth and most systematic weapon — regularization — is covered next. Unlike the three ad-hoc strategies here, regularization is a mathematically principled way to control model complexity through a tunable penalty term .

Real-World & Domain Connection. Early stopping is ubiquitous in deep learning. Frameworks like PyTorch Lightning and Keras include EarlyStopping callbacks as built-in features. The "more data" strategy is why tech companies hoard data. : Google's and Meta's models work because they have billions of training examples, not because their architectures are fundamentally different. In production ML systems, all three strategies are typically deployed together: large datasets + appropriate model size + early stopping + regularization (Section 5.8).


5.9 Regularization — The Speed Limiter for Your Model

Hook. Your car can go 200 km/h, but speed limits exist for a reason. Without them, one wrong tap on the accelerator and you are off the road. Regularization is the speed limiter for your model's coefficients. It stops any single feature from dominating and crashing your generalization.

Intuition + Analogy. The professor's core insight: overfitting produces very large coefficient values. Why? Because an overfit model twists and bends desperately to pass through every training point. Those twists require extreme slopes. Large values. Regularization adds a "coefficient tax" to the cost function: the bigger your coefficients, the more you pay. The model must now balance two competing goals: (1) fit the data well, and (2) keep coefficients small. It is like a car with a speed limiter — you can still drive, but you cannot go crazy.

Why increasing training error is deliberate. Adding the penalty term makes the model slightly worse on training data. This is intentional. The professor's exact words. : "We are intentionally making the model slightly worse on the training data so that on the testing data it will become dramatically better. We add a little bias to the model to massively reduce the variance." This is the bias-variance tradeoff in action.

The Regularized Cost Function — General Form.

The regularized cost adds a penalty term to the standard MSE:

  • First term: Standard mean squared error. Measures how well the model fits the training data.
  • Second term: Regularization penalty. Measures how large the coefficients are. The start means (the bias/intercept) is NOT penalized — we only shrink feature weights, not the baseline offset.
  • (lambda): The regularization hyperparameter. Controls the strength of the penalty. = no penalty (ordinary least squares). very large = all shrink to zero (model becomes a constant).

Effect of — the three regimes:

value Effect Result
No penalty Ordinary least squares — model CAN overfit
small Gentle penalty Balanced fit — coefficients kept in check
very large Huge penalty All — model underfits (constant prediction)

How to choose : Try multiple values (e.g., 0.001, 0.01, 0.1, 1, 10, 100), train with each, and pick the one with the lowest validation error. This is covered in detail in Section 5.12.

Assumptions & Scope.

  • Regularization assumes features are on comparable scales. If one feature ranges from 0–1 and another from 0–10000, the penalty hits them very differently. Always standardize features before applying Ridge/Lasso. Use StandardScaler from scikit-learn.
  • The bias term is NOT regularized. Penalizing the intercept would make the model dependent on the origin, which is usually undesirable.
  • The general form shown here uses L2 penalty (Ridge). The specific forms for L1 (Lasso) and Elastic Net follow in Sections 5.9–5.11.

Pitfalls.

  1. Forgetting to scale features. This is the #1 regularization mistake. Without scaling, the penalty distorts coefficients based on feature units, not feature importance.
  2. Regularizing the bias term. The summation starts from , not . Exam questions will test this — the bias is always exempt.
  3. Setting too high. All coefficients shrink to zero, and the model predicts the mean of for every input. This is underfitting — high bias, low variance.
  4. Confusing regularization with feature selection. Regularization (Ridge) shrinks coefficients but does NOT eliminate them. Lasso (Section 5.10) is needed for feature elimination.

Recap. Regularization adds a penalty for large coefficients to the cost function. The hyperparameter controls the tradeoff between fitting data and keeping coefficients small. gives ordinary least squares; large forces all coefficients toward zero. The bias term is never penalized. Bridge: The next three sections cover the three specific penalty types. : Ridge (L2, Section 5.9), Lasso (L1, Section 5.10), and Elastic Net (combined, Section 5.11).

Real-World & Domain Connection. Regularization is the standard approach to preventing overfitting in linear models. In scikit-learn, Ridge(alpha=lambda) and Lasso(alpha=lambda) are one-line implementations. The concept extends far beyond linear regression. : L2 regularization (weight decay) is used in virtually every neural network training loop. L1 regularization is used in compressed sensing and sparse coding. The standard reference (Bishop §3.1.4) presents regularization as the Bayesian interpretation: the L2 penalty corresponds to a Gaussian prior on weights, and the L1 penalty corresponds to a Laplace prior. Connecting regularization to Bayesian inference.


5.10 Ridge Regression (L2 Regularization)

Hook. Ridge regression never says "this feature is useless." It says "I will use everything, but nobody gets to shout." Every feature gets a voice. Just a quieter one. That is the essence of L2 regularization. : proportional shrinkage, not elimination.

Intuition + Analogy. Imagine a team meeting where one person dominates the conversation (a large coefficient). Ridge adds a "speaking tax". : the more you speak, the more you pay. The tax grows quadratically. Speaking twice as much costs four times as much. Nobody is silenced completely, but the loud voices are pulled back. The quiet voices (small coefficients) pay almost nothing, so they are barely affected. The result: everyone contributes, just more evenly.

This is different from Lasso (Section 5.10), which works like a "mute button" — it can completely silence irrelevant features.

Cost Function — Ridge (L2):

The penalty is the L2 norm (Euclidean norm) of the coefficient vector (excluding bias). Squaring means. : a coefficient of 10 contributes to the penalty; a coefficient of 1 contributes . Large values are penalized disproportionately.

Gradient descent update for Ridge:

Rewrite to reveal the shrinkage factor:

The shrinkage factor : Since and , this is a number slightly less than 1. At every update, the current coefficient is multiplied by , pulling it toward zero. The professor emphasized. : "This 1 minus alpha into Lambda is a key part. This is the shrinkage factor. It will try to reduce the coefficient."

Bias term (): Updated WITHOUT the shrinkage factor — no penalty on the intercept:

Effect of the penalty:

  • Large → huge penalty (squared) → strongly shrunk.
  • Small → tiny penalty → barely affected.
  • No coefficient ever reaches exactly zero — all features are retained, just dampened.

When to use Ridge: You have many features and most of them are somewhat useful. You want to prevent any single feature from dominating, but you do not want to eliminate features entirely. Ridge is the safe, default choice for regularization.

Recap. Ridge adds to the cost. The update rule includes a shrinkage factor that proportionally pulls coefficients toward zero. No coefficient becomes zero. Ridge retains all features. Bridge: Lasso (Section 5.10) replaces the squared penalty with absolute values, which changes the behavior from proportional shrinkage to constant subtraction — and enables feature elimination.

Real-World & Domain Connection. In scikit-learn: from sklearn.linear_model import Ridge; model = Ridge(alpha=lambda).fit(X, y). The alpha parameter is scikit-learn's name for . Ridge is widely used in econometrics (ridge regression was invented by Hoerl and Kennard in 1970 to handle multicollinearity in economic data) and in any domain with many correlated features. The closed-form solution for Ridge is . Note the term that makes the matrix invertible even when is singular, which is another key advantage of Ridge over OLS.


5.11 Lasso Regression (L1 Regularization)

Hook. Ridge shrinks. Lasso eliminates. If you have 1000 features but only 5 actually matter, Ridge keeps all 1000 (just quieter). Lasso mutes 995 of them to absolute zero. It is a feature selector built into the training process.

Intuition + Analogy. Imagine a team meeting where some people have genuinely nothing to contribute. Ridge gives everyone a quieter voice. Lasso actively escorts the irrelevant people out of the room. The key difference is mathematical. : Ridge's penalty is quadratic (), so the cost of shrinking a coefficient from 0.1 to 0 is tiny (). Not worth it. Lasso's penalty is absolute (), so the cost of eliminating a 0.1 coefficient is 0.1 — a constant amount. Lasso is willing to pay that constant cost to achieve sparsity (zero coefficients).

This is why Lasso is called a "sparse" model: most coefficients become exactly zero. Only the truly important features survive.

Cost Function — Lasso (L1):

The penalty is the L1 norm. Sum of absolute values. Unlike Ridge's factor, Lasso uses directly. The penalty grows linearly. : a coefficient of 10 contributes 10; a coefficient of 1 contributes 1.

Gradient descent update for Lasso:

Where if , if , and if .

Key difference from Ridge: Instead of multiplying by , Lasso subtracts a constant (scaled by sign). A constant subtraction can drive a coefficient to exactly zero. Once it crosses zero, the sign flips and it stays at zero. Ridge's proportional shrinkage can only approach zero asymptotically, never reaching it.

Comparison — Ridge vs. Lasso:

Property Ridge (L2) Lasso (L1)
Penalty
Shrinkage type Proportional (multiply by ) Constant (subtract )
Coefficients become zero? Never (asymptotically approach 0) Yes — many become exactly 0
Feature selection? No Yes (built-in)
Best when Most features are useful Most features are irrelevant
Computational Smooth, easy to optimize Non-differentiable at 0 (requires subgradient)
Scikit-learn Ridge(alpha=lambda) Lasso(alpha=lambda)

When to use Lasso: You have many features but suspect most are irrelevant. Lasso automatically identifies and eliminates useless features. The surviving non-zero coefficients are your selected features. This makes Lasso popular in genomics (thousands of genes, few actually predict disease) and text classification (thousands of words, few are predictive).

Q: Can Ridge coefficients ever become exactly zero?

A: No. Because the penalty is proportional (), as a coefficient gets closer to zero, the shrinkage gets smaller and smaller. It approaches zero asymptotically but never reaches it. Lasso subtracts a constant amount regardless of the coefficient's size, so it can cross zero and stay there.

Recap. Lasso uses absolute-value penalty (L1 norm). The constant-subtraction update can drive coefficients to exactly zero, making Lasso a built-in feature selector. Use Lasso when you believe most features are irrelevant. Use Ridge when most features contribute. Bridge: Elastic Net (Section 5.11) combines both penalties into one model. You get the feature selection of Lasso with the stability of Ridge.

Real-World & Domain Connection. Lasso was introduced by Robert Tibshirani in 1996 and is one of the most cited papers in statistics. The name "LASSO" stands for "Least Absolute Shrinkage and Selection Operator." It is a cornerstone of high-dimensional statistics (where number of features exceeds number of samples ), used extensively in bioinformatics, finance, and any field with "wide" data. In scikit-learn, Lasso(alpha=lambda) fits with coordinate descent (not gradient descent) because the absolute value is non-differentiable at zero. Coordinate descent handles this naturally.


5.12 Elastic Net

Hook. What if you want the best of both worlds? Lasso is ruthless. It can eliminate correlated features arbitrarily, picking one and discarding the rest. Ridge keeps all correlated features but cannot eliminate any. Elastic Net blends them. : it can eliminate irrelevant features. Keeping groups of correlated ones together.

Intuition + Analogy. Lasso is like a hiring manager who, when faced with two equally qualified candidates, picks one randomly and rejects the other. Ridge hires both but gives them half the salary. Elastic Net hires both at reduced salary OR fires one, depending on the mix parameter . The parameter is your dial. : turn it toward 1 for Ridge-like behavior (keep everyone), toward 0 for Lasso-like behavior (be selective). At , you get an even blend.

Cost Function — Elastic Net:

Two hyperparameters:

  • — overall penalty strength (same role as in Ridge/Lasso).
  • — the L1 ratio (mix parameter), :
  • : Pure Ridge (only L2 penalty).
  • : Pure Lasso (only L1 penalty).
  • : A blend. Common default: .

Why Elastic Net exists: Lasso has a known weakness. When features are highly correlated (e.g., "house size in sq ft" and "number of rooms"), Lasso tends to pick one arbitrarily and zero out the other. This is unstable — a small change in data can flip which one survives. Elastic Net's L2 component encourages grouping. : correlated features tend to be shrunk together (all kept or all dropped). The L1 component still enables sparsity.

Comparison — All Three Regularizers:

Property Ridge (L2) Lasso (L1) Elastic Net
Penalty
Sparsity None Yes (exact zeros) Yes (exact zeros)
Correlated features Keeps all, shrinks together Picks one arbitrarily Keeps groups together
Hyperparameters 1 () 1 () 2 (, )
When to use Default, most features useful Sparse solution needed Correlated features + sparsity

When to use Elastic Net: You have many features, some correlated, and you want sparse solutions. Elastic Net is the modern default in many applications because it avoids Lasso's instability with correlated features. Retaining sparsity. In scikit-learn. : ElasticNet(alpha=lambda, l1_ratio=r).

Recap. Elastic Net = Ridge + Lasso. The mix parameter controls the balance. is Ridge, is Lasso, and values in between give you both shrinkage and feature selection. It is the most flexible of the three regularizers. Bridge: All three methods share the same hyperparameter . Section 5.12 explains how to choose in practice.

Real-World & Domain Connection. Elastic Net was introduced by Zou and Hastie (2005) specifically to address Lasso's limitations with correlated predictors. It is the default regularized linear model in many ML pipelines and is available in scikit-learn as ElasticNet and ElasticNetCV (with built-in cross-validation for both and ). In genomics, where genes are highly correlated (co-expression networks), Elastic Net is the standard tool for biomarker discovery.


5.13 Choosing Lambda () — Cross-Validation

Hook. is not learned by gradient descent. You must pick it before training begins. Pick wrong, and your model either overfits ( too small) or underfits ( too large). How do you find the sweet spot? You try, you test, you compare.

Intuition + Analogy. Choosing is like choosing the strength of coffee. Too weak () and you taste every impurity in the water. Too strong ( huge) and all you taste is bitterness. The coffee's character is lost. The right strength depends on the beans (your data) and your taste (the validation score). You cannot know the perfect strength in advance — you brew several cups at different strengths and taste each one. The one that tastes best wins.

That is exactly how we choose : train the model with several candidate values, evaluate each on a validation set, and pick the with the lowest validation error.

The Cross-Validation Procedure for :

  1. Choose candidate values: A logarithmic grid is typical — e.g., . The range should span several orders of magnitude.
  2. For each :
  • Train the model (Ridge, Lasso, or Elastic Net) on the training set.
  • Evaluate on the validation set (data never seen during training).
  • Record the validation error.
  1. Pick the that gives the lowest validation error.
  2. Optional — K-fold cross-validation: Instead of a single train/validation split, split the training data into folds. For each , train on folds and validate on the remaining fold. Average the validation error across all folds. This gives a more robust estimate.

The professor's approach: "We normally try four or five times and then we take the lowest value of Lambda. That is a normal approach. You try multiple values of Lambda in your model and whatever gives you the lowest validation error, you pick that."

Pitfalls.

  1. Testing on the test set. The test set is for final evaluation only. Use a validation set (or cross-validation) to choose . If you use the test set to pick , your test error becomes optimistically biased.
  2. Too narrow a search range. If you only try , you might miss the optimal value at . Search across several orders of magnitude.
  3. Not using the same for Ridge and Lasso. A in Ridge does NOT have the same effect as in Lasso. The penalty scales differ. Always cross-validate separately for each method.

Recap. is a hyperparameter chosen before training. Try several values, evaluate on a validation set, pick the one with the lowest error. This is a universal ML workflow. The same approach applies to choosing any hyperparameter (learning rate, polynomial degree, tree depth). Bridge: The next section (5.13) shows the effect of regularization on the coronary heart disease gradient descent example — the same problem from Section 5.1, now with Ridge and Lasso updates.

Real-World & Domain Connection. Scikit-learn provides RidgeCV, LassoCV, and ElasticNetCV. Classes that automatically perform cross-validation to find the best (called alpha in scikit-learn). These use efficient computation paths (the LARS algorithm for Lasso) to compute solutions for many values simultaneously, avoiding the cost of retraining from scratch for each candidate. In production, LassoCV with default settings is often sufficient to get a well-regularized model without manual tuning.


5.14 Worked Example — Gradient Descent with Regularization

Hook. The same three patients, the same initial weights. But now the update rule has an extra term that tugs the coefficients toward zero at every step. How much do they shrink? Let us trace the math.

Ridge Regularization on the Coronary Heart Disease Problem.

We reuse the identical setup from Section 5.1: , initial , 3 patients. Add Ridge penalty with .

The temporary gradients (computed in Section 5.1) remain the same:

Modified update rule (Ridge):

With and :

Simultaneous update:

Comparison with unregularized update (Section 5.1):

Parameter Unregularized (Section 5.1) Ridge () Difference
5.0022 5.0022 0 (bias not penalized)
0.0552 0.05526 +0.00006 (barely changed — was small)
0.1723 0.17239 +0.00009 (barely changed — was small)

Why the difference is tiny here: The initial coefficients were already very small (). The shrinkage factor only reduces them by 0.2% per iteration. Over many iterations, this cumulative shrinkage prevents coefficients from growing large. But in a single iteration with small initial values, the effect is subtle. If the coefficients were large (e.g., ), the shrinkage would be dramatic. : . Losing 0.1 per iteration just to the penalty.

Sense-check: The bias term is unchanged (correct. Bias is not regularized). The feature weights are slightly smaller in magnitude than their unregularized counterparts (correct — Ridge shrinks toward zero). The effect accumulates over many iterations.

Lasso Regularization on the Same Problem.

Same setup, but now with Lasso penalty ():

Modified update rule (Lasso):

With and :

Initial signs: , .

Simultaneous update:

Why Lasso adds rather than subtracts here: Both initial coefficients are negative (). The Lasso penalty term is . It adds to the coefficient, pushing it toward zero from the negative side. If the coefficients were positive, the penalty would subtract.

Comparison of all three:

Parameter Unregularized Ridge () Lasso ()
5.0022 5.0022 5.0022
0.0552 0.05526 0.0572
0.1723 0.17239 0.1743

At this small scale, Ridge and Lasso produce nearly identical updates. Over many iterations, the differences compound. : Ridge shrinks proportionally (large coefficients shrink more), Lasso subtracts a constant (can drive coefficients to exactly zero).

Recap. The worked example from Section 5.1 is extended with Ridge and Lasso penalties. The temporary gradients are unchanged. Only the final update formula differs. Ridge multiplies by ; Lasso subtracts . The bias term is never penalized. Bridge: The next section (5.14) implements all of this in Python — gradient descent from scratch, with and without regularization.

5.15 Python Implementation of Gradient Descent

Hook. Theory is clean. Real code is where the bugs live. A missing transpose, a wrong axis in np.mean, or forgetting to add the bias column. : any one of these silently gives you wrong answers. Let us walk through the implementation line by line so you know exactly what each operation does and why.

Purpose. Implement batch gradient descent for linear regression from scratch using NumPy. This code trains a model to learn the relationship from noisy data, then evaluates it with MAE, MSE, and RMSE.

Inputs & Outputs.

  • Input: Synthetic data: (feature), (target). Hyperparameters: , .
  • Output: Learned parameters ; evaluation metrics; plots of regression line and cost convergence.

Steps — Annotated NumPy Implementation.

1. Generate synthetic data:

import numpy as np
np.random.seed(42)
X = 2 * np.random.rand(100, 1)        # 100 points, values in [0, 2]
y = 4 + 3 * X + np.random.randn(100, 1)  # y = 4 + 3x + Gaussian noise

The true relationship is . The noise randn adds Gaussian scatter. The model should recover and .

2. Add bias column to X:

X_b = np.c_[np.ones((100, 1)), X]     # shape (100, 2) — first column is all 1s

np.c_ concatenates along columns. The first column of 1s allows to act as the intercept. Without this, the model is forced through the origin.

3. Set hyperparameters and initialize:

alpha = 0.01          # learning rate
n_iterations = 1000   # number of epochs
m = 100               # number of training examples
theta = np.random.randn(2, 1)  # shape (2, 1) — random initialization

4. Training loop:

for iteration in range(n_iterations):
    # (a) Predictions: (100,2) @ (2,1) -> (100,1)
    predictions = X_b.dot(theta)

    # (b) Error vector: (100,1) - (100,1) -> (100,1)
    error = predictions - y

    # (c) Cost (MSE/2): scalar
    cost = (1 / (2 * m)) * np.sum(error ** 2)

    # (d) Gradient: (2,100) @ (100,1) -> (2,1)
    gradients = (1 / m) * X_b.T.dot(error)

    # (e) Update parameters simultaneously
    theta = theta - alpha * gradients

Why X_b.T.dot(error) computes the gradient:

  • is — transposed design matrix.
  • is — error vector.
  • The product is — one gradient component per parameter.
  • This is the vectorized version of for all simultaneously.

5. Evaluation:

predictions_final = X_b.dot(theta)
mae  = np.mean(np.abs(predictions_final - y))
mse  = np.mean((predictions_final - y) ** 2)
rmse = np.sqrt(mse)
print(f"Learned theta: {theta.ravel()}")
print(f"MAE: {mae:.4f}, MSE: {mse:.4f}, RMSE: {rmse:.4f}")

Trace — Cost Convergence.

With synthetic data and :

  • Iteration 0: cost –50 (random initialization).
  • Iteration 100: cost drops to –5.
  • Iteration 200–300: cost approaches –0.8 (near the noise floor — cannot go lower because of the injected Gaussian noise).
  • Iteration 300–1000: cost flat — the model has converged.

Visual Intuition — Cost vs. Iteration plot:

  • X-axis: iteration number (0 to 1000).
  • Y-axis: cost .
  • Shape: steep drop in first ~200 iterations, then a long flat tail.
  • Landmark: the "knee" of the curve at ~200–300 iterations is where gradient descent has effectively converged. Continuing to 1000 adds no value.
  • Takeaway: 1000 iterations was wasteful; 300 would have sufficed. This is why stopping conditions (threshold, patience) are used in practice.

Using Scikit-learn's SGDRegressor:

from sklearn.linear_model import SGDRegressor
from sklearn.preprocessing import StandardScaler

# Feature scaling is CRITICAL for SGD
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)    # mean=0, std=1

sgd_reg = SGDRegressor(
    max_iter=1000,
    tol=1e-3,              # stop if improvement < 0.001
    loss='squared_error',  # MSE loss = linear regression
    penalty=None,          # no regularization (for comparison)
    random_state=42
)
sgd_reg.fit(X_scaled, y.ravel())      # y must be 1D for scikit-learn
predictions = sgd_reg.predict(X_scaled)

The .fit().predict() pattern is universal across scikit-learn. Every model — LinearRegression, Ridge, Lasso, LogisticRegression, SVM — follows this same two-step workflow. Memorize it.

Key parameters:

  • loss='squared_error' — ordinary least squares (linear regression).
  • penalty=None — no regularization (add penalty='l2' for Ridge, penalty='l1' for Lasso).
  • tol=1e-3 — stop when cost improves by less than 0.001.
  • random_state — seed for reproducibility.

Pitfalls.

  1. Forgetting to add the bias column. Without np.c_[np.ones(...), X], the model has no intercept. It is forced through the origin, which is almost always wrong.
  2. Not scaling features for SGDRegressor. SGDRegressor is sensitive to feature scales. Without StandardScaler, convergence is slow or unstable. The from-scratch implementation is also affected, but for 2-feature simple cases it is less visible.
  3. Wrong shape for y. Scikit-learn expects y as a 1D array: y.ravel() or y.flatten(). Passing a column vector (m, 1) may cause silent broadcasting errors.
  4. Confusing np.dot and . is element-wise multiplication. np.dot or @ is matrix multiplication. Using * where @ is needed gives wrong results with no error message.

Recap. The from-scratch implementation uses NumPy's X_b.dot(theta) for predictions and X_b.T.dot(error) for gradients. Scikit-learn's SGDRegressor provides a production-ready version with scaling, regularization, and convergence checks. Both follow batch gradient descent. Using all training examples per update. Bridge: This implementation is for linear regression with MSE loss. Logistic regression (Section 5.15–5.18) uses a different hypothesis (sigmoid) and a different cost function (log loss), but the gradient descent loop structure is identical — only the gradient formula changes.

Real-World & Domain Connection. In production, you almost never write gradient descent from scratch. Scikit-learn's SGDRegressor and SGDClassifier are the workhorses for linear models on large datasets. For deep learning, PyTorch's torch.optim.SGD and TensorFlow's tf.keras.optimizers.SGD implement the same math with automatic differentiation. You define the forward pass, and the framework computes gradients for you. The loop structure (forward → loss → backward → update) is universal across all gradient-based ML.


5.16 Logistic Regression — Introduction

Hook. Linear regression predicts any number from to . But what if you need a probability. A number between 0 and 1? "145% chance of rain" is nonsense. Logistic regression solves this by taking the output of a linear model and squeezing it through a special S-curve that always lands between 0 and 1. Despite the word "regression" in its name, it is a classification algorithm.

Intuition + Analogy. The professor's art critic vs. artist analogy is the canonical mental model for discriminative vs. generative classifiers:

  • Discriminative classifier (Logistic Regression, SVM): An art critic who learns specific features — brushstroke style, color palette, composition — to tell a Picasso from a Monet. The critic can identify the artist but cannot paint a new Picasso. They learn only the boundary: "if brushstrokes are thick and colors are bold → Picasso."
  • Generative classifier (Naive Bayes, GANs): An artist who studies Picasso's work so deeply — the emotion, the form, the technique — that they can paint a new work in Picasso's style. They learn what each class looks like from the inside.

Logistic regression is discriminative: it learns the decision boundary that separates classes, not the full distribution of each class. It is also probabilistic. : it outputs . A number between 0 and 1 — not just a hard "yes" or "no."

Classification vs. Regression.

Regression Classification
Output type Continuous () Discrete (class labels)
Goal Predict a numeric value Assign to a category
Example Predict house price ($350,000) Spam or not spam
Evaluation MAE, MSE, RMSE, Accuracy, Precision, Recall, F1
Algorithm example Linear Regression Logistic Regression

Binary classification = exactly two classes (spam/not spam, fraud/legitimate, disease/healthy). This is the focus of logistic regression.

What logistic regression outputs:

  • A probability .
  • Not a hard label — you get a confidence score.
  • Example: means "87% confident this email is spam."
  • To make a decision, apply a threshold (default: 0.5):
  • → predict class 1 (spam).
  • → predict class 0 (not spam).

Pitfalls.

  1. The name is misleading. "Logistic Regression" is classification, not regression. The "regression" part refers to the linear model inside the sigmoid. Students who assume it predicts continuous values will use it wrong.
  2. Threshold is NOT always 0.5. In fraud detection, you might use 0.1 (flag anything with >10% fraud probability). In medical diagnosis, you might use 0.9 (only flag when very certain). The threshold depends on the cost of false positives vs. false negatives.
  3. Logistic regression outputs probabilities, not certainties. A prediction of 0.51 is barely above the threshold — the model is uncertain. A prediction of 0.99 is highly confident. The magnitude matters.

Recap. Logistic regression is a discriminative, probabilistic binary classifier. It maps inputs to probabilities via a linear model wrapped in a sigmoid. The output is , interpreted with a threshold (default 0.5). Bridge: The next section (5.16) derives the sigmoid function that makes this possible. The S-curve that squashes any real number into .

Real-World & Domain Connection. Logistic regression is one of the most widely deployed ML algorithms in industry. Credit scoring (will this applicant default?), medical diagnosis (does this scan show cancer?), and email spam filtering all use logistic regression as a baseline. And often as the production model. Its interpretability (each coefficient tells you the direction and strength of a feature's influence) makes it preferred in regulated industries (finance, healthcare) where you must explain decisions. The standard reference (Bishop §4.3) presents logistic regression as the discriminative counterpart to the generative naive Bayes model — both model , but logistic regression models it directly. Naive Bayes goes through Bayes' rule.


5.17 The Logistic (Sigmoid) Function

Hook. Take any number. 1000, -500, 3.14 — and feed it through . The result is always between 0 and 1. This one function is the bridge from linear regression (which outputs any real number) to logistic regression (which outputs probabilities).

Intuition + Analogy. Imagine a dimmer switch for a light. The switch position can be any number from (completely off) to (maximum brightness). But the actual light output is always between 0% and 100%. The sigmoid is that dimmer. : it takes an unbounded input (the linear score ) and maps it smoothly to a bounded output (a probability). The middle of the switch () gives exactly 50% brightness. Push it far right () and the light saturates near 100%. Push it far left () and it saturates near 0%.

The Sigmoid Function:

Where:

  • — the logit or linear score.
  • — Euler's number.
  • — always strictly between 0 and 1 (never exactly 0 or 1, but arbitrarily close).

The logistic regression hypothesis:

Behavior of the sigmoid — key values:

Interpretation
Near-certain positive class
High confidence positive
Maximum uncertainty (boundary)
High confidence negative
Near-certain negative class

Visual intuition — the S-curve:

  • X-axis: (the logit), ranging from about to .
  • Y-axis: , ranging from 0 to 1.
  • Shape: a smooth S-curve. Flat near 0 on the left, steepest at (slope = 0.25), flat near 1 on the right.
  • Landmarks: is the center. The curve is symmetric: .
  • Takeaway: The sigmoid compresses the entire real line into , with the steepest response around zero.

Why is the sigmoid S-shaped? For large positive , is tiny, so . For large negative , is huge, so . The transition between these extremes happens smoothly around .

Pitfalls.

  1. Linear regression for classification. If you use linear regression on binary labels (0/1), the predictions can be 1.5 or -0.3 — not valid probabilities. Outliers can also shift the line dramatically, misclassifying many points.
  2. Assuming the sigmoid reaches 0 or 1. is NEVER exactly 0 or 1 — it only approaches these values asymptotically. In code, large can cause numerical overflow in . Use scipy.special.expit or torch.sigmoid for numerically stable implementations.
  3. Confusing and . is unbounded (any real number). is the probability. The decision boundary is at , NOT at .

Recap. The sigmoid function maps any real number to . It is the core of logistic regression. : . gives 0.5 (decision boundary); large positive gives near 1; large negative gives near 0. Bridge: The decision boundary (Section 5.17) is the set of points where . Where the sigmoid outputs exactly 0.5, and the model is maximally uncertain.

Real-World & Domain Connection. The sigmoid function appears throughout ML and statistics. : in neural networks as an activation function (though ReLU has largely replaced it in hidden layers), in the output layer for binary classification, and in logistic regression as the link function. The term "logit" comes from "logistic unit." The inverse of the sigmoid, , maps probabilities back to the real line. This is the log-odds and is the foundation of logistic regression's interpretability: each coefficient represents the change in log-odds per unit change in .


5.18 Decision Boundary of Logistic Regression

Hook. Where does the model switch from "probably class 0" to "probably class 1"? At exactly . The point where the sigmoid outputs 0.5. The equation defines a line (in 2D), a plane (in 3D), or a hyperplane (in higher dimensions) that separates the two classes. That is the decision boundary.

Intuition + Analogy. Think of a fence between two properties. The fence is the decision boundary. Everything on one side belongs to owner A; everything on the other side belongs to owner B. The fence's location is determined by the parameters . Change , and the fence shifts. The linear discriminant function is the "distance to the fence" (with sign indicating which side). The sigmoid converts that signed distance into a probability of being on owner A's side.

The Linear Discriminant Function:

Decision rule:

  • If , predict class 1 (positive class).
  • If , predict class 0 (negative class).

Equivalently: if , predict class 1; else class 0.

The decision boundary is where . This is a hyperplane in :

  • In 2D (): a straight line.
  • In 3D (): a flat plane.
  • In dimensions: a -dimensional hyperplane.

Worked Example — Linear Boundary.

Given: , , .

The decision boundary:

Visual:

  • The line passes through and .
  • Test point : → class 1. Checks out: .
  • Test point : → class 0. Checks out: .

Sense-check: Points on the line () give and — maximum uncertainty.

Non-Linear Decision Boundaries.

Linear boundaries fail when classes are not linearly separable (e.g., class 1 points clustered in a circle, surrounded by class 0). The solution. : add polynomial terms to the discriminant, just like linear basis functions for regression.

Example — Circular boundary:

With , , , , :

This is a circle of radius 1 centered at the origin. Points inside the circle () → class 1. Points outside → class 0.

Risk. Overfitting: Adding too many polynomial terms creates a boundary that wiggles to capture every training point, including noise. A 100-degree polynomial boundary achieves 100% training accuracy but fails on new data. The same bias-variance tradeoff from Section 5.6 applies here.

Pitfalls.

  1. Assuming data is linearly separable. Most real-world data is not. Use polynomial features or kernel methods (SVM with RBF kernel) when a straight line is insufficient.
  2. Overfitting with too many polynomial terms. Each added term is a new feature. With original features, degree-3 polynomial expansion creates features — more than many datasets have examples. Use regularization (Ridge/Lasso on polynomial features) to control complexity.
  3. Class label conventions. Some algorithms (SVM) use instead of . The decision rule is unaffected, but the cost function differs. Know which convention your algorithm uses.

Recap. The decision boundary is where . Where the sigmoid outputs 0.5. For linear logistic regression, the boundary is a line/plane/hyperplane. Adding polynomial basis functions enables non-linear boundaries at the risk of overfitting. Bridge: The cost function (Section 5.18) measures how well the decision boundary separates the classes — not with MSE (which would be non-convex with the sigmoid), but with log loss, which is convex and guarantees finding the global minimum.

Real-World & Domain Connection. The linear discriminant function is identical in form to the discriminant in Linear Discriminant Analysis (LDA) and the perceptron. The difference is how is learned. : LDA uses class means and covariance, the perceptron uses a mistake-driven update, and logistic regression uses maximum likelihood (log loss + gradient descent). This shared form means insights about decision boundaries transfer across all linear classifiers. In the standard reference (Bishop §4.1), the decision boundary is presented as the -dimensional hyperplane defined by , with the perpendicular distance from a point to the boundary given by .


5.19 The Cost Function of Logistic Regression (Log Loss)

Hook. Mean squared error works beautifully for linear regression. The cost surface is a perfect bowl. But plug the sigmoid into MSE, and the bowl shatters into a mess of wavy hills and valleys. Gradient descent gets lost. To fix this, we need a cost function designed specifically for probabilities. : log loss. It gives us back our bowl.

Intuition + Analogy. Imagine you are a weather forecaster. You predict "90% chance of rain" and it rains. Good forecast. Small penalty. You predict "10% chance of rain" and it rains. Terrible forecast — large penalty. You predict "0.0001% chance of rain" and it pours. Catastrophic forecast — essentially infinite penalty. Log loss encodes exactly this intuition. : the more confident you are in a wrong prediction, the more you are punished. The punishment grows without bound as your confidence in a wrong answer approaches 100%.

The professor's key insight: "If you confidently predict that an event is impossible, but actually that event happens, you will be punished infinitely." This is the moral core of log loss.

Why MSE Fails for Logistic Regression.

The logistic regression hypothesis is . This is a nonlinear function of . If you plug it into the squared error cost:

The resulting cost surface is non-convex — full of local minima. Gradient descent can get stuck in any of them. There is no guarantee of finding the global minimum.

The Log Loss (Cross-Entropy) Cost Function.

For one training example with true label and predicted probability :

Combined form (single formula for all examples):

How the combined formula works:

  • When : the second term becomes . Only remains.
  • When : the first term becomes . Only remains.

Cost behavior table:

Prediction True label Cost Interpretation
0.99 1 Near-perfect → tiny penalty
0.5 1 Uncertain → moderate penalty
0.01 1 Confidently wrong → large penalty
0.001 1 Extremely wrong → very large penalty
0.000 1 Infinitely wrong → infinite penalty
0.01 0 Near-perfect → tiny penalty
0.99 0 Confidently wrong → large penalty

Derivation — Why Log Loss Gives a Convex Surface.

The log loss is derived from maximum likelihood estimation. Given independent examples, the likelihood of observing the labels is:

Taking the negative log (and dividing by for scaling) gives the log loss:

The log-likelihood for logistic regression is concave in (proved by showing the Hessian is negative semidefinite). Therefore, the negative log-likelihood (log loss) is convex. A bowl shape with a single global minimum. Gradient descent is guaranteed to find it.

Q: Should we use log base 10 or natural log?

A: It does not matter. Changing the log base multiplies all costs by a constant factor (). The location of the minimum. The decision boundary — is exactly the same. The professor confirmed this explicitly.

Pitfalls.

  1. Using MSE for logistic regression. The cost surface becomes non-convex. Gradient descent may converge to a local minimum far from the true optimum. Always use log loss (or equivalently, cross-entropy) for classification.
  2. Numerical issues with . If is exactly 0 or 1 (due to floating-point overflow in the sigmoid), gives -inf. In practice, clip predictions to where .
  3. Confusing log loss with MSE interpretation. MSE is in squared units of the target. Log loss is in "nats" (for natural log) or "bits" (for log base 2). You cannot directly compare MSE and log loss values.

Recap. Log loss is the cost function for logistic regression. It penalizes confident wrong predictions infinitely, giving a convex cost surface. The combined formula handles both classes in one expression. Log base does not matter for the decision boundary. Bridge: This is the final major concept of the lecture. The assignment (Section 5.19) uses RMSLE. A log-based metric related to these ideas, applied to regression.

Real-World & Domain Connection. Log loss (cross-entropy) is the standard loss function for binary classification across all of ML. In scikit-learn, LogisticRegression uses it by default. In deep learning, BinaryCrossentropy in Keras/TensorFlow and BCELoss in PyTorch are the same formula. The connection to maximum likelihood (derived above) means that training a logistic regression model is equivalent to finding the parameters that make the observed labels most probable under the model. A fundamental principle that extends to all probabilistic ML models. The standard reference (Bishop §4.3.2) derives the same log-likelihood and confirms convexity.


5.20 Assignment — Bike Rental Prediction

Hook. You have learned gradient descent, regularization, and evaluation metrics. Now apply them all to a real dataset. : predict how many bikes will be rented in a given hour, using weather, season, and time features. The metric is RMSLE. A log-based variant of RMSE that penalizes under-prediction more heavily than over-prediction.

Problem Summary.

  • Goal: Build a linear regression model to predict hourly bike rental counts.
  • Data: Training set with features and target labels provided. Separate test set (no labels) for final evaluation.
  • Metric: Root Mean Squared Logarithmic Error (RMSLE):

  • The inside the log prevents issues when (zero rentals in an hour).
  • RMSLE penalizes under-prediction (predicting 500 when actual is 1000) more than over-prediction (predicting 1500 when actual is 1000) because the log difference is larger below the true value.
  • No built-in scikit-learn function — you must implement it yourself using the formula.

Required workflow:

  1. EDA (Exploratory Data Analysis): Check dataset size, missing values, feature types (numeric vs. categorical).
  2. Correlation analysis: Find which features are most informative about the target.
  3. Feature engineering: Create new features (e.g., "is_weekend" from date, "hour_of_day", interaction terms).
  4. Visualization: Scatter plots, heat maps, box plots to understand feature-target relationships.
  5. Train/validation split: 80% training, 20% validation.
  6. Model experimentation: Try feature scaling, polynomial features with Ridge, polynomial features with Lasso.
  7. Comparison table: Summarize all models with their RMSLE scores.

Notebook structure tip from the professor:

  • Markdown cell: question you are investigating.
  • Code cell: analysis/visualization.
  • Markdown cell: interpretation of what you found.

Pitfalls.

  1. Forgetting the +1 in RMSLE. Without it, crashes for zero-valued predictions or targets.
  2. Using RMSE by accident. The assignment explicitly requires RMSLE. Read the formula carefully.
  3. Not scaling before applying Ridge/Lasso. Regularization is sensitive to feature scales — always standardize first.
  4. Polynomial feature explosion. Adding degree-2 polynomial terms to 10 features creates 66 features. With 20 features, it is 231. Use Ridge/Lasso to handle this.

Real-World Connection. The bike rental dataset (from the UCI ML Repository) is a classic regression benchmark. The RMSLE metric is used in real competitions (Kaggle's Bike Sharing Demand competition) and is common when the target spans several orders of magnitude. Log-space metrics prevent models from being dominated by a few very large values. The workflow (EDA → feature engineering → multiple models → comparison table) mirrors industry ML project structure.


5.21 Exam Guidance Summary

Exam note: The professor's exam guidance, consolidated from throughout the lecture.

  • Gradient descent problems on exams typically ask for ONE iteration, showing ALL intermediate calculations: predictions, errors, temporary gradients, and final updates. The coronary heart disease example (Section 5.1) is the template — expect to reproduce this for different numbers.
  • Simultaneous update of values is critical. Using temporary variables (temp_0, temp_1, temp_2) is the correct approach. The professor will check whether you updated using the old values or accidentally used a newly updated value.
  • Ridge vs. Lasso — know the exact penalty formulas: (Ridge, L2) vs. (Lasso, L1). Know the update rules: Ridge multiplies by ; Lasso subtracts . Know when to use each: Ridge when most features matter, Lasso when you need feature selection.
  • Regularization — the bias term is NEVER penalized. The summation starts from , not . The professor will test this on the exam.
  • Log loss — understand why MSE cannot be used for logistic regression (non-convex surface) and how log loss penalizes confident wrong predictions infinitely. The formula must be memorized.
  • Bias-variance tradeoff — expect conceptual questions matching descriptions to underfitting (high bias, lazy student) and overfitting (high variance, memorizer). Be able to interpret the error-vs-complexity graph with its U-shaped test-error curve.
  • The .fit() -> .predict() pattern is universal across scikit-learn. Memorize it.
  • Assignment grading: The model with the lowest RMSLE gets the highest score on a leaderboard. Implement RMSLE yourself — no scikit-learn function exists for it.
  • Linear vs. nonlinear models — a model is linear if it is linear in the parameters , not the input features . is linear (in ). is NOT linear (in ).

5.22 Key Industry Applications

  • Scikit-learn (sklearn): The standard Python ML library. All models follow .fit(X, y) -> .predict(X). Key classes: LinearRegression, Ridge, Lasso, ElasticNet, SGDRegressor, LogisticRegression, StandardScaler, PolynomialFeatures.
  • NumPy: Foundation for matrix operations — np.dot(A, B) or A @ B for matrix multiplication, np.mean(), np.sum(), np.abs().
  • Matplotlib: plt.scatter() for data points, plt.plot() for regression lines, plt.xlabel()/plt.ylabel() for axis labels.
  • Regularization in practice: Ridge(alpha=lambda) and Lasso(alpha=lambda) in scikit-learn. alpha is scikit-learn's parameter name for . Always scale features with StandardScaler before applying regularization.
  • SGDRegressor: Mini-batch SGD for large datasets. Set loss='squared_error' for linear regression, penalty='l2' for Ridge, penalty='l1' for Lasso, penalty='elasticnet' for Elastic Net.
  • StandardScaler: Transforms features to zero mean and unit variance — critical for any gradient-descent-based model and any regularized model.
  • PolynomialFeatures: Generates polynomial and interaction features. PolynomialFeatures(degree=2) creates . Combine with Ridge/Lasso to prevent overfitting.

ML Lecture 5 notes · Gradient Descent, Regularization, and Logistic Regression

Machine Learning· postgraduate· 2026-06-29

Sections Breakdown

1Gradient Descent — Full Worked Example

Batch gradient descent algorithm with a step-by-step numerical trace on coronary heart disease data, including predictions, errors, gradient computation, and simultaneous parameter updates.

2Vectorized vs. Scalar Representation

Difference between scalar form h(x) = θᵀx for one example and vectorized form Xθ for all examples, and why vectorization is essential for computational efficiency.

3Types of Gradient Descent

Batch, stochastic (SGD), and mini-batch gradient descent — comparison of update frequency, convergence behavior, memory requirements, and when to use each variant.

4Evaluation Metrics for Regression Models

MAE, MSE, RMSE, and R² — definitions, outlier sensitivity, units of measurement, and how to choose the right metric for a given problem.

5Linear Basis Functions and Model Linearity

Model linearity is defined with respect to parameters, not inputs — polynomial, Gaussian, and sigmoidal basis functions enable nonlinear predictive power with linear computational cost.

6Underfitting, Overfitting, and the Bias-Variance Tradeoff

The three-student analogy, formal definitions of bias and variance, the test-error U-curve, and the fundamental tradeoff between model complexity and generalization.

7Handling Overfitting

Three practical strategies — increasing data size, reducing model complexity, and early stopping for iterative models — with implementation guidance.

8Regularization — The Speed Limiter for Your Model

Regularized cost function, the hyperparameter λ, effect of penalty on coefficient shrinkage, and the deliberate increase of training error to improve test performance.

9Ridge Regression (L2 Regularization)

L2 penalty proportional shrinkage, the (1-αλ) shrinkage factor in gradient updates, bias term exemption, and when to use Ridge regression.

10Lasso Regression (L1 Regularization)

L1 penalty constant subtraction, exact zero coefficients, built-in feature selection, and comparison of Ridge vs. Lasso properties and use cases.

11Elastic Net

Combined L1+L2 penalty with mixing parameter r, handling of correlated features, and comparison of all three regularizers — Ridge, Lasso, and Elastic Net.

12Choosing Lambda (λ) — Cross-Validation

Logarithmic grid search for the regularization hyperparameter, single validation split vs. K-fold cross-validation, and practical pitfalls.

13Worked Example — Gradient Descent with Regularization

Numerical trace of Ridge and Lasso updates on the coronary heart disease problem, comparing regularized vs. unregularized parameter values.

14Python Implementation of Gradient Descent

NumPy implementation of batch gradient descent from scratch, synthetic data generation, and scikit-learn SGDRegressor with feature scaling.

15Logistic Regression — Introduction

Classification vs. regression, discriminative vs. generative classifiers, probabilistic binary classification, and interpretation of output probabilities.

16The Logistic (Sigmoid) Function

The sigmoid function σ(z) = 1/(1+e⁻ᶻ), its S-curve behavior, key reference values, and the logistic regression hypothesis.

17Decision Boundary of Logistic Regression

Linear discriminant function, the hyperplane θᵀx = 0, decision rule for class assignment, and nonlinear boundaries using polynomial basis functions.

18The Cost Function of Logistic Regression (Log Loss)

Why MSE fails for classification, the log loss (cross-entropy) cost function, its convexity guarantee, and the connection to maximum likelihood estimation.

19Assignment — Bike Rental Prediction

RMSLE metric, required workflow from EDA through model comparison, and practical tips for the bike rental prediction assignment.

Postgraduate students in Machine Learning

Exam Revision Notes

Below is the distilled, exam-ready core of this lecture. Every entry is built from the full textbook notes above. Use this section for rapid review — but if something doesn't make sense, go back to the full explanation in the main content.

Gradient Descent

Must-know: Gradient descent iteratively minimizes the cost function by stepping in the direction of the negative gradient. The learning rate α controls step size. Simultaneous update of all parameters is mandatory — compute all gradients first, then update all parameters.

⚠️ Top pitfall: Updating θ₀ first and using the new value to compute θ₁'s gradient. Always use temporary variables (tempⱼ).

Self-check: Given 3 data points with specific values, can you compute one iteration of batch gradient descent showing predictions, errors, gradients, and final update?

Connects to: Vectorized form Xθ for efficient computation; Mini-batch SGD as the practical default; Regularization modifies the update rule

Gradient Descent Variants (Batch, SGD, Mini-Batch)

Must-know: Batch uses all N examples per update (deterministic, slow). SGD uses 1 example (noisy, fast). Mini-batch uses B examples (default in practice). The update formula is identical — only the data subset differs.

⚠️ Top pitfall: Calling mini-batch 'SGD' in conversation — in modern usage, 'SGD' almost always means mini-batch SGD, not pure stochastic.

Self-check: Which variant would you choose for a dataset with 10 million examples that does not fit in RAM?

Connects to: Batch size tunes speed-stability tradeoff; SGD noise helps escape local minima (non-convex)

Evaluation Metrics (MAE, MSE, RMSE, R²)

Must-know: MAE is robust to outliers (linear penalty). MSE/RMSE punish large errors quadratically. R² measures fraction of variance explained by the model. MSE is preferred for gradient descent because it is differentiable everywhere.

⚠️ Top pitfall: R² always increases with more features — use adjusted R² for model comparison with different numbers of predictors.

Self-check: If errors are [−10, +10, +10], what are MAE, MSE, RMSE, and R²? (Answers: 10, 100, 10, 0.94)

Connects to: RMSLE is a log-space variant used in the assignment; MAE is not differentiable at zero

Linear Basis Functions and Model Linearity

Must-know: A model is linear if it is linear in the parameters θ, not in the input features x. Basis functions φ(x) can be nonlinear (polynomial, Gaussian, sigmoidal) while the model remains linear in θ and solvable by the same linear regression machinery.

⚠️ Top pitfall: Confusing parameter linearity with input linearity — the professor WILL test this. y = θ₀ + θ₁x + θ₂x² IS linear (in θ). y = θ₀e^{θ₁x} is NOT linear.

Self-check: Is y = θ₀ + θ₁x₁x₂ a linear model? (Yes — it is linear in θ, even though x₁x₂ is a nonlinear feature interaction.)

Connects to: Bias-variance tradeoff — more basis functions = lower bias but higher variance

Bias-Variance Tradeoff

Must-know: High bias = underfitting (model too simple — lazy student analogy). High variance = overfitting (model too complex — memorizer analogy). The test error forms a U-shaped curve — the optimal model is where test error is minimized, not training error.

⚠️ Top pitfall: Assuming 99% training accuracy means the model is good — this is the memorizer's trap. Always check validation/test performance.

Self-check: A model has high training error AND high test error. Is this bias or variance? (Answer: High bias — underfitting.)

Connects to: Regularization formalizes the tradeoff into a tunable λ parameter

Regularization (Ridge, Lasso, Elastic Net)

Must-know: Ridge (L2) adds λ/2·Σθⱼ² — proportional shrinkage, never zeroes coefficients. Lasso (L1) adds λ·Σ|θⱼ| — constant subtraction, can zero coefficients (feature selection). Elastic Net blends both with mixing parameter r. The bias term θ₀ is NEVER regularized.

⚠️ Top pitfall: Forgetting to scale features before regularization — the penalty distorts coefficients based on feature units. Always use StandardScaler.

Self-check: Why is the bias term θ₀ not regularized? (Because penalizing the intercept would make the model dependent on the origin, which is undesirable.)

Connects to: λ chosen via cross-validation; Ridge update multiplies by (1 − αλ); Lasso subtracts αλ·sign(θⱼ)

Logistic Regression and the Sigmoid Function

Must-know: Logistic regression is a discriminative, probabilistic binary classifier. The sigmoid σ(z) = 1/(1+e⁻ᶻ) maps the linear score z = θᵀx to a probability in (0,1). The decision boundary is where θᵀx = 0 (σ(z) = 0.5).

⚠️ Top pitfall: Using linear regression for binary classification — outputs can be < 0 or > 1, which are invalid probabilities.

Self-check: If θ₀ = −3, θ₁ = 1, θ₂ = 1, what is the decision boundary? (Answer: x₁ + x₂ = 3 — points above predict class 1.)

Connects to: Log loss replaces MSE for convex optimization; Nonlinear boundaries via polynomial features

Log Loss (Cross-Entropy) Cost Function

Must-know: Log loss penalizes confident wrong predictions infinitely. The combined formula handles both classes in one expression. MSE produces a non-convex surface with the sigmoid; log loss is convex — gradient descent is guaranteed to find the global minimum.

⚠️ Top pitfall: Numerical issues with log(0) — clip predictions to [ε, 1−ε] where ε ≈ 10⁻¹⁵.

Self-check: What is the log loss when y=1 and the model predicts 0.99? (Answer: −log(0.99) ≈ 0.01 — very confident and correct, tiny penalty.)

Connects to: Derived from maximum likelihood estimation; Standard loss for binary classification in all ML frameworks

Was this lecture useful?

Loading comments…
🤖

BitsNotes AI Assistant

Subject Notes Assistant

Configure AI Chat

Choose how to access the chatbot
Have your own API key?

Switch to "Bring Your Own Key" tab above for unlimited access with any OpenAI-compatible provider.

🔑 Enter API key above to fetch live models from provider, or enter model name manually.
OpenAI-Compatible API Support

Choose any provider preset (Gemini, DeepSeek, Kimi, GLM, MiniMax, Qwen, OpenAI, Groq, Ollama, etc.) or enter a custom endpoint URL.

Security & Privacy First

Your API key is sent directly from your browser to your specified provider. BitsNotes servers never store or see your key.