Skip to main content
Machine Learning

Instance-Based Learning — Distance-Weighted KNN, Locally Weighted Regression, and Bayesian Learning Foundations

📅 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

  • K-Nearest Neighbors (KNN) Algorithm — covered in Lecture 10
  • Instance-Based Learning — covered in Lecture 10
  • Linear Regression — covered in Lectures 3 and 4
  • Gradient Descent — covered in Lecture 4
  • Cross Validation — covered in Lecture 10

Instance-Based Learning — Distance-Weighted KNN, Locally Weighted Regression, and Bayesian Learning Foundations

11.1 KNN Algorithm Refresher

**Hook:** You walk into a room full of strangers. To guess whether a stranger likes pineapple on pizza, you don't build a mathematical theory of pizza preferences — you find the few people who look most similar to that stranger and ask them. That is KNN in one sentence.
**Intuition:** Think of training examples as labeled pins on a giant corkboard. When a new pin arrives without a label, KNN places it on the board, looks around at the nearest *k* pins, and copies the majority label. No model. No formula. Just proximity voting. The analogy breaks when the board gets too crowded (high dimensions) — at that point, "nearest" stops being meaningful because everything is far from everything else.

11.1.1 Quick Recap of K-Nearest Neighbors

The K-Nearest Neighbors (KNN) algorithm is an *instance-based learner* — it does not build an explicit model during training. Instead, it stores all training examples and does all the work at prediction time. This is why KNN is called a *lazy learner*. The goal of KNN is to classify a new data point into one of a finite set of categories. This is called *approximating a discrete-valued target function*: the output is one specific value — yes or no, or Class A / Class B / Class C — rather than a continuous number. The set of possible classes is denoted . **Notation:** - An input instance has attributes: - is one of the finite set of classes - is the class predicted by training example
**The algorithm has two phases:**
**Phase 1 — Training (memorization only):** For every training example , add it to the list of training examples. Nothing else happens. The model does not learn a formula or a rule. It only stores all the data it has seen. This is what makes it a lazy learner. **Phase 2 — Classification (where the work happens):** When a new query instance arrives: 1. Find the instances from the stored training examples that are *physically closest* to . Closeness is measured by a distance metric, most commonly Euclidean distance. 2. Let denote the nearest training instances. 3. Look at the class of each neighbor and count the votes. 4. Return the class that has the most votes. The voting is formalized by: where is the *Kronecker delta function*. This function equals if the neighbor's class matches the class being checked; otherwise it equals . > Think of it this way: for each possible class , count how many of the neighbors belong to that class. Pick the class with the highest count.
**Worked example — classifying a fruit as apple or banana:** Suppose and . The three closest neighbors are found: neighbor 1 is an apple, neighbor 2 is a banana, neighbor 3 is an apple. - **Check :** Neighbor 1 (apple) matches → 1. Neighbor 2 (banana) does not match → 0. Neighbor 3 (apple) matches → 1. Sum = 2. - **Check :** Neighbor 1 (apple) does not match → 0. Neighbor 2 (banana) matches → 1. Neighbor 3 (apple) does not match → 0. Sum = 1. - . The new fruit is classified as an apple. **Euclidean distance** between two instances and with attributes: This is just the straight-line ("as-the-crow-flies") distance in -dimensional space. For real-valued target functions (regression), KNN replaces the final vote-counting step by taking the mean of the neighbors' values: ---

11.1.2 K Value Selection — Overfitting and Underfitting

**Hook:** Pick 1 neighbor and you trust a single stranger's pizza opinion — risky if that stranger has weird taste. Pick 100 neighbors and you are polling the whole city — the truly similar people get drowned out. Choosing is the art of KNN.
The choice of dramatically changes the prediction. **If is too small (e.g., ):** The model is extremely sensitive to the local pattern. It looks at the single closest point and classifies accordingly. If the dataset has noise and that noisy point happens to be the closest, the prediction will be wrong. This leads to *overfitting* — the model has high variance.
**Pitfall — and noise:** With , a single mislabeled training point can hijack any query that falls near it. The decision surface becomes a Voronoi tessellation — jagged polygons where each training example dominates its own region. One bad label creates one bad polygon.
**If is too large (e.g., ):** The model may include points from other classes in the neighborhood. Even though one neighbor is extremely close (nearly on top of the query point) and strongly indicates the correct class, the majority of far-away neighbors may override that vote. This leads to *underfitting* — the model has high bias. **Visual example:** A blue query point is directly overlapping a green training point. With , the other four nearest neighbors are red. The green point would be classified as red even though it sits right on top of a green point — a clear failure of standard KNN. **Three methods for choosing :** **Method 1 — Rule of thumb:** Take where is the number of data points in the dataset. Always choose an *odd* value. The odd value ensures tie-breaking in binary classification — with 3 neighbors you can get 2 vs 1; with 4 neighbors you could get a 2-2 tie. This method is typically used only for small datasets (small ), not for large ones. **Method 2 — Elbow method:** Train the model with different values of (e.g., ). Calculate the error rate (sum of squared errors, SSE) for each . Then plot error rate vs . The error rate drops sharply as increases initially (since is overfitting). Then the error rate stabilizes at some point. The value where the drop in error stabilizes is called the *elbow point*, and that is chosen as optimal. If is increased further after stabilization, the error may start rising again. **Method 3 — K-fold cross validation:** Split the data into chunks (folds), e.g., 10 folds. For a given value of , use 9 folds for training and 1 fold for testing. Repeat this 10 times, each time with a different fold as the test set. Compute the average accuracy across all 10 runs. Then change and repeat the entire process. Pick the with the highest average accuracy. This is more robust than a single train/test split. **Grid search** is an advanced version of cross validation that automates the search for the best . It internally uses cross validation and directly returns the optimal hyperparameter value. **Visual intuition — the bias-variance tradeoff:** Picture a scatter plot of two classes (red and blue) with a new green query point near the boundary. Draw concentric circles around the query point. - **:** The smallest circle touches only the nearest point. The decision surface is a crazy zigzag that hugs every training point — high variance, every bump in the data gets memorized. - **:** A medium circle captures a mix. The surface is smoother but still responsive to local structure. - **:** A huge circle pulls in points from distant regions. The surface becomes overly smooth — high bias, it misses real local patterns. **One-sentence takeaway:** Small = jagged but honest to the data; large = smooth but potentially blind to local truth. ---

11.1.3 The Argmax Function — Detailed Walkthrough

The function appears throughout machine learning. It returns the *argument* (the input value) that produces the *maximum* output, not the maximum output itself. For KNN, means: iterate over every possible class in the set . For each class, compute the sum of Kronecker delta votes. Return the class that had the largest sum.
> **Q:** How is the argmax sum computed step by step? > **A:** Set the small (the class being checked) first to the first class in . Run the summation , counting how many of the neighbors match that class. Repeat for every class in . Take the argmax of all those sums. The class corresponding to the highest sum is the prediction.
**Worked argmax example — three classes:** Suppose and . Neighbors: cat, dog, cat, cat, fish. - Check : - Check : - Check : . **Prediction: cat.** Sense-check: three out of five neighbors are cats, so majority vote correctly picks cat.

11.1.4 Symbol Registry — Standard KNN

| Symbol | Meaning | Notation | Type/Domain | |--------|---------|----------|-------------| | | Input instance with attributes | | vector in | | | Query instance (new point to classify) | | vector in | | | Finite set of classes | | set | | | One class from | | categorical | | | Class label of training example | | categorical | | | Number of nearest neighbors | | integer, odd preferred | | | Kronecker delta — 1 if , 0 otherwise | | | | | Predicted class for query point | | categorical |

11.1.5 Student Questions on KNN Basics

**Q:** Does the prediction change if I change the value of ? **A:** Yes. If , the model may classify an apple as a banana if the single nearest neighbor happens to be a banana (even though the query point is actually an apple). If is too large, points from other classes dominate the vote. The choice of is critical. **Q:** Why choose an odd value for ? **A:** It prevents ties. In binary classification with , you could get two votes for each class — a deadlock. With or , there is always a clear majority (e.g., 2 yes vs 1 no, or 3 yes vs 2 no). Several students asked this — it is a common point of confusion, so make it a habit: always pick odd for binary classification. **Q:** When is the square root of rule used? **A:** It is a rule of thumb, mostly for small datasets (small ). For large datasets, methods like the elbow method or cross validation are preferred.

11.1.6 KNN — When to Use

KNN is suitable when: - The dataset has low dimensionality - There is plenty of training data - Training must be fast (there is practically no training) - The target function may be complex and non-linear — KNN can learn complex patterns because it does not assume a linear relationship - The data is noisy — use distance-weighted KNN so noise points get near-zero weight
**Assumptions & Scope:** KNN assumes that closeness in the input space implies similarity in the output. This breaks when many attributes are irrelevant (the *curse of dimensionality*). Distance gets dominated by noise dimensions. It also breaks when the data is high-dimensional (everything becomes equidistant). It also fails when the distance metric does not capture the true notion of similarity for the domain. For example, Euclidean distance on raw pixel values for image classification works poorly. KNN also needs all training data at query time. It cannot work when memory is constrained or when training data is streaming and cannot be stored.
**Issues with KNN:** - The value of hugely affects predictions - The choice of distance metric (Euclidean, Minkowski, Gower, etc.) is always a confusing choice - Slow at query time — to find the nearest neighbors, the algorithm must compute the distance to all training examples and then sort them - Must store all training data — since nothing happens during training, all data must be available at prediction time > **Q:** Are there scenarios where KNN is better suited for regression than other methods? > **A:** Yes — when the data does not follow a linear pattern. If the data is wavy or curvy, standard linear regression cannot fit a single straight line through all of it. Locally weighted regression (a form of KNN for continuous outputs) fits multiple local models, capturing the actual trend in the data. ---
**Recap:** KNN classifies by majority vote among the nearest stored examples. No training — all work happens at query time. The choice of balances bias (too large, underfits) against variance (too small, overfits). **Bridge:** The standard version treats all neighbors equally, but a neighbor at distance 0.1 should count more than one at distance 10. This insight leads directly to distance-weighted KNN (Section 11.2).
**Real-world connection:** KNN powers *collaborative filtering* in recommendation systems. Netflix finds users whose viewing history is most similar to yours and recommends what they liked. It is also used in *k-nearest neighbor search* for image retrieval. Google Images' "visually similar" feature is one example. It is also used in *anomaly detection* and *document classification*. Its simplicity makes it a go-to baseline. If your fancy deep model cannot beat KNN on a clean low-dimensional dataset, something is wrong.

11.2 Distance-Weighted KNN

**Hook:** Your next-door neighbor's opinion about the best restaurant should matter more than someone living 50 miles away. Standard KNN treats them as equal voters. That is the problem distance-weighted KNN fixes.
**Intuition:** Imagine a committee vote where each member's vote is multiplied by . The person directly affected (distance ≈ 0) gets essentially infinite say. Someone barely connected (distance ≈ 100) gets essentially zero say. KNN with distance weighting is that committee — every stored example gets a vote, but proximity amplifies it. The analogy breaks at distance zero (division by zero), which is why we add a tiny constant as a safety net.

11.2.1 Why Weighted KNN?

Standard KNN treats all neighbors equally, regardless of how far they are from the query point. This causes a problem: One neighbor may be extremely close to the query point (almost overlapping), strongly indicating that the query point belongs to that neighbor's class. But other neighbors, though farther away, happen to be among the closest and outvote the truly close neighbor. The prediction is wrong even though the most similar training example points to the correct answer. **Solution:** Give more voting power to closer neighbors. Neighbors that are closer to the query point should have a larger influence on the prediction. Neighbors farther away should have a smaller influence.

11.2.2 Weight Function and Classification Formula

**Weight function (inverse square distance):** where: - is the query point - is the -th nearest neighbor - is the Euclidean distance between them As the distance increases, decreases. The effect of far-away neighbors is reduced compared to the nearest neighbor. **Weighted classification formula (discrete-valued target):** This is the same as standard KNN except each Kronecker delta vote is multiplied by the weight . The closest neighbor gets the largest multiplier. **Weighted regression formula (continuous-valued target):** The numerator is the weighted sum of the neighbors' output values. The division by is for *normalization* — since are numerical values (not just class labels), multiplying by weights can produce large numbers. Dividing by the sum of weights brings the prediction back to the same scale as the original outputs. **Why normalization matters — worked illustration:** Suppose neighbor 1 has value and distance . Its weight . Contribution: . Suppose neighbor 2 has value and distance . Its weight . Contribution: . Numerator sum: . Denominator sum: . Prediction: . The predicted value () is extremely close to neighbor 1's value (10), which is the closest neighbor. Without normalization, the raw weighted sum would be 12 — still close, but normalization ensures the output stays in the same numerical range as the original target values. > **Q:** What does "normalizing by dividing by " mean? > **A:** It brings the scale down to the same range as the original target values . Without it, if all weights were large, the prediction could blow up to an unreasonably large number. Dividing by the sum of weights scales the result back proportionally.
**Assumptions & Scope:** Distance weighting assumes the distance metric is meaningful — if two points are twice as far apart, they should be roughly four times less relevant (for inverse-square weighting). This fails when the distance metric itself is poorly chosen (e.g., raw Euclidean distance on categorical one-hot vectors treats all mismatches equally, which may not reflect true dissimilarity). Distance weighting also assumes that influence should decay *monotonically* with distance, which is reasonable for most domains but may miss cases where moderate distance is more informative than extreme closeness (rare, but possible with multi-modal class distributions).

11.2.3 Kernel Functions — Weight Functions

Weight functions in KNN are also called *kernel functions*. A kernel function defines the similarity between pairs of data points in a high-dimensional feature space. In KNN, the kernel converts the distance between the query point and a neighbor into a similarity score (the weight). **Why "kernel"?** The term is most commonly used for SVM, ridge regression, and Gaussian processes. Any function that defines similarity between pairs of data points and is used as a weight is called a kernel. In KNN, the kernel serves as a similarity measure between a training point and the query point. **Common weight functions (kernels):** **1. Inverse distance (simplest):** A neighbor at distance 2 gets weight . A neighbor at distance 0.5 gets weight . Simple but breaks when distance equals zero (division by zero → weight → infinity). **2. Inverse square distance:** The influence of points drops off much faster. A neighbor at distance 2 gets weight instead of . This faster drop-off is called a higher *decay*. **3. Modified inverse square distance (with ):** is a very small positive constant (e.g., or ). This prevents division by zero when the query point exactly overlaps a training point. The maximum possible weight any point can get is now capped at . Even if the distance is zero, the denominator is still at least . > **Q:** What happens when distance ? > **A:** The query point is identical to (overlapping with) a training point. Without , the weight would be — infinity. That makes sense conceptually (we want maximum weight for an identical point), but infinity causes numerical problems. So caps the weight. The weight will still be huge relative to other neighbors, and that neighbor will dominate the vote — which is exactly what we want. **How to choose :** No standard method exists. Common approaches: - Set to a very small value like or - Try a range of values () and use cross validation to pick the best one **4. Gaussian kernel (Gaussian decay):** or equivalently: where (or ) controls the *width* (bandwidth) of the kernel: - **Small (small ):** Only very close neighbors get significant weight. Far points get weight near zero. - **Large (large ):** Even distant points get non-zero weight. The kernel is wider. The Gaussian kernel drops to near-zero very quickly because of the squared term. Only extremely close neighbors matter significantly. If the data roughly follows a Gaussian (bell-curve) distribution, the Gaussian kernel is a natural choice. The denominator ( or ) determines the width — analogous to standard deviation.
**Visual intuition — kernel comparison:** Plot weight (y-axis, 0 to 1) against distance (x-axis, 0 to 5): - **Inverse distance** (): Starts at infinity for , drops as a gentle curve, still has at . Long tail — distant points still get some say. - **Inverse square** (): Drops much faster — at . Medium tail. - **Gaussian** (): Drops like a rock — by . Only the very closest neighbors matter at all. **One-sentence takeaway:** The faster the kernel decays, the more "local" your model becomes. Pick the kernel that matches how you think influence should fall off with distance.

11.2.4 Worked Example — Customer Classification with Weighted KNN

**Problem:** Predict the customer type (category) for customer C4. The dataset has five other customers (C0, C1, C2, C3, C5). Attributes include income, profession, region, and locality. (consider all five neighbors). Use the inverse square distance kernel. **Step 1 — Normalize numerical fields:** The income column is normalized to the range . **Step 2 — Encode categorical variables:** - Profession: one-hot encoded - Region: one-hot encoded (Bengali, Bhojpuri, Hindi) - Locality: treated as ordinal with rank values (village, small town, suburban, metropolitan) **Step 3 — Calculate distances from C4 to every other customer:** Using Euclidean distance across all encoded attributes. Example: distance between C2 and C4: Distances obtained: | Neighbor | Distance from C4 | |----------|-----------------| | C0 | 1.776 | | C1 | 1.508 | | C2 | 1.764 | | C3 | 1.326 | | C5 | 0.415 | **Step 4 — Standard KNN (no weights):** Classes of the five neighbors: - C0: L2 - C1: L1 - C2: L1 - C3: L2 - C5: L1 Votes: L2 gets 2 votes (C0, C3), L1 gets 3 votes (C1, C2, C5). **Prediction: L1.** **Step 5 — Weighted KNN (inverse square distance):** Weights: | Neighbor | Distance | Weight | Class | |----------|----------|--------|-------| | C0 | 1.776 | | L2 | | C1 | 1.508 | | L1 | | C2 | 1.764 | | L1 | | C3 | 1.326 | | L2 | | C5 | 0.415 | | L1 | **Sum weights by class:** - L2: - L1: → **Prediction: L1.** In this example, both standard and weighted KNN agree on L1 — but the confidence is radically different. Standard KNN gives a narrow 3-to-2 margin. Weighted KNN gives L1 a crushing 6.566-to-0.886 advantage because the closest neighbor C5 (distance 0.415, weight 5.805) is L1 and dominates the weighted vote.
**Pitfall:** This example shows a case where standard and weighted KNN agree. They can also disagree — and when they do, weighted KNN is generally more trustworthy because it respects proximity. However, weighted KNN can be *too* sensitive to a single extremely close neighbor if the kernel decay is very aggressive (e.g., Gaussian with tiny ). In that case, your weighted KNN effectively becomes KNN, losing the smoothing benefit of having multiple neighbors.
**Key insight:** With and without weights, predictions can differ. There is no guarantee that weighted and unweighted KNN will agree. Weighted KNN is generally preferred because it respects the intuition that closer neighbors matter more.

11.2.5 Symbol Registry — Weighted KNN

| Symbol | Meaning | Notation | Type/Domain | |--------|---------|----------|-------------| | | Weight for the -th neighbor | | scalar, | | | Distance between query point and neighbor | | scalar, | | | Small constant to prevent division by zero | | scalar, e.g., | | | Kernel width (standard deviation) | | scalar, | | | Bandwidth parameter (Gaussian kernel) | | scalar, | ---
**Recap:** Distance-weighted KNN multiplies each neighbor's vote by a kernel weight that decays with distance — the closer the neighbor, the louder its voice. This fixes the standard KNN problem where far-away neighbors can outvote a truly close one. **Bridge:** Distance weighting for classification is straightforward (weight the votes). For regression, we need the same idea but with a different formula — which leads directly to locally weighted regression (Section 11.3), where we fit an entire local model weighted by proximity.
**Real-world connection:** Distance-weighted KNN is used in *geospatial interpolation* — estimating property values, pollution levels, or rainfall at unmeasured locations by giving more weight to nearby measurement stations. In *collaborative filtering*, it improves recommendation quality by weighting user-similarity scores. The inverse-square form mirrors the physics of gravity and electrostatics — influence decays with the square of distance — making it intuitive for any domain where "twice as far = four times less relevant" holds.

11.3 Locally Weighted Regression

**Hook:** A single straight line through a wavy dataset is like trying to describe a roller coaster with one angle — it misses every turn. Locally weighted regression draws a fresh small line at every point you ask about, using only the nearby data.
**Intuition:** Imagine you are hiking a winding mountain trail. To predict your altitude at the next step, you don't fit one straight line to the entire mountain range — you look at the slope right under your feet. Locally weighted regression is that: for every query point, it finds the nearby training points, fits a tiny model (linear, quadratic, whatever) using only those neighbors, and predicts. Then it throws that model away and builds a new one for the next query. This is "lazy" because no model survives beyond a single query — but it is powerful because every prediction gets a custom-fit model.

11.3.1 Concept and Motivation

In standard linear regression, we try to find a *single straight line* that fits all the data. But when the data is curvy or wavy, one global line cannot capture the pattern. Locally weighted regression solves this by creating *many small local models* instead of one global model. For each query point, we fit a model (linear, quadratic, or any functional form) using only the data points near that query point. The far-away data is ignored or given very low weight. This is a form of *lazy learning*: there is no training phase where a global model is built. All the regression work happens only when a prediction is requested for a specific query point. > Think of it this way: instead of forcing one straight line through a curvy dataset, we draw a fresh small line every time someone asks "what's the value here?" — using only the nearby dots.

11.3.2 The Local Approximation Model

The linear approximation model for a query point : where: - is the predicted value - is the *bias* or *intercept* — the baseline prediction when all input attributes are zero - are the *slopes* — each measures the importance or influence of a specific attribute. A larger weight means that attribute has a stronger influence on the output - is the value of the -th attribute of instance **Global error function (standard linear regression):** The is a mathematical convenience — when we take the derivative to find the minimum, the exponent 2 cancels out the . **Gradient descent update rule (standard):** where (eta) is the *learning rate* — a small number controlling the step size. Too large: overshoot the best solution. Too small: training takes forever.

11.3.3 Three Approaches to Local Error

In locally weighted regression, we modify the error function to focus only on points near the query point . **Method 1 — Nearest neighbor approach (hard window):** Calculate the error only for the nearest neighbors of . Points outside the -neighborhood get zero weight (are completely ignored). **Method 2 — Kernel-weighted approach (soft window):** Calculate the error over the entire dataset, but weight each training example's error by a kernel function of its distance from . Far-away points get very low (but non-zero) weight. **Method 3 — Combined (best approximation):** Apply both — consider only the nearest neighbors AND apply a kernel weight function within that set. This is the method used in practice. For a given query point , the weighted regression problem is solved using gradient descent, applied only to the nearest neighbors with the kernel weight function. The gradient descent update for locally weighted regression changes only by the inclusion of the weight: The only difference from standard gradient descent: each training example's contribution is multiplied by the kernel weight , and the sum runs only over the nearest neighbors. **Derivation note — why the gradient update has this form:** The standard gradient descent update for linear regression minimizes the squared error . Taking the derivative with respect to : Moving in the negative gradient direction (gradient descent): . For locally weighted regression, we simply multiply each term by the kernel weight and restrict the sum to the nearest neighbors. The in the error function cancels with the exponent 2 during differentiation, which is why it is there — pure mathematical convenience.

11.3.4 Visual Intuition

Consider a dataset of blue dots arranged in a wave pattern (non-linear). A single straight line would never fit this well. The query point is a green vertical line. The locally weighted regression fits a red line — but this red line only tries to match the blue dots immediately surrounding the green query point, not all the blue dots everywhere. As the query point moves along the x-axis, the red regression line shifts to fit the local neighborhood. Without weights (using only nearest neighbors), the fitted curve may be jagged. With kernel weights, even though only local neighbors are considered, the fitted curve is smooth — the weights produce a continuous transition.
**Pitfall — jagged vs smooth:** Using a hard window (Method 1: only the nearest neighbors, equal weight) produces a step-function-like fit — the model changes abruptly when the -neighborhood changes. Kernel weighting (Method 3) produces a smooth fit because points enter and leave the neighborhood *gradually* as their kernel weight fades in and out. If your locally weighted regression plot looks like connected line segments instead of a smooth curve, you forgot the weights.

11.3.5 Worked Example — Product Price Prediction

**Problem:** Predict the price of a product with size 7. Use nearest neighbors and a Gaussian kernel with bandwidth . Suppose the linear model is , with initial weights , , and learning rate . **Step 1 — Kernel function:** since . **Step 2 — Find the 5 nearest neighbors to size 7 and compute distances:** Suppose the dataset (size, price): (2, 10), (4, 25), (5, 35), (8, 65), (10, 90), (12, 110). The 5 nearest to size 7: | Neighbor | Size | Price | Distance | |----------|------|-------|--------------------------------------| | x₁ | 8 | 65 | 1 | | x₂ | 5 | 35 | 2 | | x₃ | 10 | 90 | 3 | | x₄ | 4 | 25 | 3 | | x₅ | 12 | 110 | 5 | **Step 3 — Compute kernel weights:** | Neighbor | | | | |----------|-------|---------|---------------------------| | x₁ | 1 | 1 | | | x₂ | 2 | 4 | | | x₃ | 3 | 9 | | | x₄ | 3 | 9 | | | x₅ | 5 | 25 | | **Step 4 — One iteration of gradient descent:** Update rule: Initial predictions with : for all . For (the slope for "size"): For (the bias, where always): Updated weights after one iteration: , . **Prediction for size 7:** . Sense-check: The closest neighbor (size 8, price 65) strongly pulls the prediction, but the two size-8 neighbors suggest a price near 65. After just one gradient step, the fitted line gives roughly 25 at size 7 — reasonable but not fully converged. More iterations would refine this.
**Note:** The exact numerical values above are reconstructed to illustrate the mechanics of locally weighted gradient descent. The original lecture slides and accompanying Python notebook contain the precise dataset and convergence trace — cross-reference those for the exact numbers used in class. The *process* (compute kernel weights → evaluate residuals → accumulate weighted gradient → update weights) is what the exam will test, not memorizing specific price values.

11.3.6 Residual and Kernel Function Definitions

- *Residual* — the error in approximating the target function: . The difference between the actual value and the predicted value. - *Kernel function* — a function of distance used to determine the weight of each training example. such that the weight decreases as distance increases. - The function is approximated based only on data near the query point. Data from far away should not matter much. Example: predicting the weather in London — data from a weather station in Tokyo should have almost no influence. ---
**Recap:** Locally weighted regression fits a custom model for every query point using only nearby (or distance-weighted) training examples. It handles non-linear data without needing a global non-linear formula — the locality does the work. **Bridge:** The idea of weighting by distance from a center point extends beyond KNN and regression. Radial basis functions (Section 11.4) take this concept and build an entire neural network architecture around it — using distance-based "basis functions" as the hidden layer.
**Real-world connection:** Locally weighted regression is used in *financial time-series forecasting* where trends are non-stationary — the model adapts to recent local patterns rather than forcing a single global trend. In *robotics*, it enables smooth trajectory learning from demonstration, where the robot's movement should closely follow nearby demonstrated paths while ignoring distant, irrelevant examples. In *environmental modeling*, it predicts pollutant concentrations at unmonitored locations by fitting local models to nearby sensor readings.

11.3.7 Symbol Registry — Locally Weighted Regression

| Symbol | Meaning | Notation | Type/Domain | |--------|---------|----------|-------------| | | Bias / intercept — baseline prediction when all inputs are 0 | | scalar | | | Weight for attribute — its importance | | scalar | | | Value of -th attribute of instance | | depends on attribute | | | Learning rate — step size for gradient descent | | scalar, small positive | | | Error (loss / cost) function | | scalar, | | | Kernel function — converts distance to weight | | scalar in | | | True target value | | scalar | | | Predicted target value | | scalar | | Residual | — prediction error | — | scalar |

11.3.8 Student Questions on Locally Weighted Regression

> **Q:** How is the local window around the query point determined? > **A:** It depends on the value. With , the three closest points form the local window. Their distance from the query point determines how wide the window is. The kernel function then weights them — closer points get more influence. ---

11.4 Radial Basis Functions

**Hook:** What if, instead of storing every training example and finding neighbors at query time, you could pre-select a few "prototype" points and have them vote on every query — but with the voting power decaying radially from each prototype? That is a radial basis function network.
**Intuition:** Think of an RBF network as placing a set of Gaussian "bells" across the input space, each centered at a prototype point . Every input rings every bell — but the bell rings loudest when is close to its center. The output is a weighted sum of how loudly each bell rings. This is the bridge between instance-based learning (KNN's distance-based voting) and neural networks (layered, trained with gradient descent).

11.4.1 Concept and Relationship to KNN

*Radial basis functions* (RBFs) are closely related to distance-weighted regression and KNN. They also heavily rely on distance: the closer an input is to a center point, the more influence that center has on the prediction. RBFs are extensively used in *artificial neural networks* (ANNs). An RBF network has exactly three layers: 1. **Input layer** — receives the data 2. **Hidden layer** — applies the radial basis function for non-linear transformation 3. **Output layer** — performs a linear weighted sum **The RBF hypothesis (prediction function):** where: - is the predicted output - is the bias term - (uppercase) is the number of components — analogous to the number of nearest neighbors. This is a user-defined parameter (distinct from the kernel function). - is the weight learned during training for component - (lowercase for kernel function) is the kernel / basis function — converts distance to a similarity score
**Why "radial"?** If you visualize the kernel output as a function of distance from the center: when the input is exactly at the center (distance = 0), the kernel output is maximized (usually 1). As moves farther from , the kernel output drops toward 0. This creates a bell-curve shape (Gaussian shape) radiating outward from the center — hence the name *radial* basis function.
**Pitfall — confusing and :** The uppercase in the summation is the *number of RBF components* (a hyperparameter, like in KNN). The lowercase is the *kernel function* itself (e.g., a Gaussian). They share the letter but are completely different things. In the formula , the on the summation is "how many centers", and the inside is "how similar is to center ".
**Comparison — RBF vs KNN:** | Aspect | KNN (Weighted) | RBF Network | |--------|---------------|-------------| | Centers | Every training example is a "center" | Pre-selected prototype centers | | Weights | Computed on-the-fly from distance | Learned via training (gradient descent / linear solve) | | Computation at query | Must scan all training data | Only kernel evaluations needed | | Training | None (lazy) | Two-stage: choose centers, then learn weights | | When to pick | Small datasets, fast training needed | Larger datasets, want a compact trained model | ---
**Recap:** RBF networks use distance-based kernel functions as hidden units in a neural network, creating a bridge between instance-based learning and ANNs. The prediction is a weighted sum of kernel responses, each peaking at its own center. **Bridge:** RBFs are a transition point — they share KNN's distance-weighted philosophy but use neural-network-style training. The next topic (Bayesian learning, Section 11.5) moves to a fundamentally different paradigm: instead of distances, we reason with probabilities and update beliefs as evidence arrives.
**Real-world connection:** RBF networks are used in *function interpolation*. They reconstruct a continuous surface from scattered measurements. Terrain modeling from GPS points is one example. They are also used in *time-series prediction*. Each RBF center captures a regime or pattern. They also work well for *classification with compact decision boundaries*. RBF networks form localized "bumps" of class membership, unlike global linear classifiers. They are also the theoretical foundation for RBF-kernel SVMs.

11.5 Bayesian Learning — Introduction

**Hook:** A doctor does not diagnose you from scratch every time. They start with what they already know ("only 1% of people have this disease"), then update that belief when your test comes back positive. Bayesian learning is the mathematical version of that updating process.
**Intuition — the detective analogy:** A detective starts with a list of suspects (prior beliefs). Each new clue (evidence) makes some suspects more likely and others less likely. The detective never throws out the prior — they update it. Bayesian learning is the detective's notebook: . The analogy breaks when the prior is completely wrong — garbage prior, garbage posterior, no matter how good the evidence.

11.5.1 Probabilistic Reasoning vs Fixed Parameters

All models studied so far (KNN, linear regression, logistic regression) treat model parameters (like the weights ) as *fixed unknown constants* to be discovered. For example, we say "the slope is 2.5" — a single definitive number. *Bayesian learning* takes a different approach. It treats everything probabilistically. Instead of saying "the slope is 2.5," Bayesian reasoning says "based on the data, the slope is likely around 2.5, but there is some uncertainty." In Bayesian learning: - Information is not treated as hard fact but as a *degree of belief* measured by probability - We start with a *prior belief* — what we think is true before seeing any data - We update that belief as we gather new evidence - The result is an *updated belief* — a new probability that incorporates both the prior and the evidence This is fundamentally different from starting from scratch every time. Bayesian methods build on existing knowledge.

11.5.2 Prior Belief, Evidence, and Updated Belief

**Medical diagnosis example:** 1. **Prior belief:** Without running any test, a doctor knows that 1% of the population has disease X. So the initial probability that a patient has the disease is 0.01 (1%). 2. **New evidence:** The doctor runs a blood test. The result comes back positive. 3. **Updated belief:** Using Bayesian reasoning, the doctor combines the prior belief (1%) with the test result (evidence). The updated probability that the patient has disease X might now be 85%. 4. **More evidence:** If the doctor runs a second test (e.g., an MRI) and it also supports the diagnosis, the probability might rise further to 99%.
The process: - If new evidence *supports* the prior belief → probability goes **up** - If new evidence *contradicts* the prior belief → probability goes **down** We never start from scratch. We always have a prior, and we adjust it as data arrives.
**Pitfall — the prior dominates with weak evidence:** When the evidence is weak or noisy, the prior can overwhelm it. If the prior says the disease is 0.001% likely and the test is only 60% accurate, even a positive test may not budge the posterior much above 0.001%. Bayesian updating is conservative — it needs strong evidence to overturn a strong prior. This is a *feature* (prevents overreacting to noise) but can be a *bug* if your prior is poorly chosen.
**Key advantage of Bayesian methods:** They provide a *confidence level* with every prediction. A Bayesian model says: "I am 92% confident this email is spam" or "I am 95% sure it will rain today." Other models (like deep neural networks) act as black boxes — they give an answer without telling you how confident they are.

11.5.3 Student Questions on Bayesian Learning

**Q:** How is Bayesian learning different from what we studied before? **A:** Previously, parameters like weights were treated as fixed values to be found. In Bayesian learning, everything is a probability distribution. We start with a prior belief, then update it as we see data. The output is not just a prediction but also a confidence level.
---
**Recap:** Bayesian learning treats everything as probabilities with uncertainty, starting from a prior belief and updating it as evidence arrives. The output includes a confidence level, not just a prediction. **Bridge:** To do Bayesian learning, we need a working knowledge of probability — random variables, distributions, and how to estimate their parameters from data. That is the foundation laid in Sections 11.6 and 11.7.
**Real-world connection:** Bayesian methods power *spam filters*. They update the probability an email is spam as each word is read. They power *medical diagnosis systems* by combining prior disease prevalence with test results. They drive *A/B testing* via Bayesian bandits that update which variant is best as data arrives. They also drive *autonomous vehicles* through Bayesian filters like Kalman filters. These track uncertain positions by fusing noisy sensor readings with prior motion models. In all cases, the key advantage is calibrated uncertainty. The system knows when it is confident and when it is guessing.

11.6 Probability Foundations

**Hook:** If I tell you "it will rain tomorrow," that is a prediction. If I tell you "there is a 70% chance of rain tomorrow," that is a *probabilistic* prediction — it tells you both what I think and how sure I am. Probability is the language of uncertainty, and Bayesian learning speaks it fluently.

11.6.1 Random Variables

A *random variable* is a mathematical concept used to represent a quantity that can take different values depending on the outcome of a random event. It is a function that maps outcomes of a random event to numerical values. **Two types:** **Discrete random variable:** Takes on a *countable* number of distinct values. - Example 1: Number of heads in three coin tosses. Possible values: . - Example 2: Result of rolling a die. Possible values: . **Continuous random variable:** Takes on an *uncountable* number of values within a range or interval. - Example 1: Height of a person - Example 2: Time to run a race - The variable can be 170.1, 170.13, 170.137, etc. — infinitely many values in any interval.

11.6.2 Probability Distributions

A *probability distribution* describes how probabilities are spread across different possible outcomes. **For discrete random variables — Probability Mass Function (PMF):** The PMF gives the probability that a discrete random variable takes on a specific value. For example, for a fair die: . **For continuous random variables — Probability Density Function (PDF):** The PDF gives the *probability density*, not the probability itself. For a continuous variable, the probability of taking any single exact value is 0 (there are infinitely many possible values). Instead, the PDF helps compute the probability over an *interval*. For example, the probability that a person's weight is between 160 and 170 pounds is the *area under the PDF curve* between 160 and 170 — computed by integration.
**Pitfall — PDF height is NOT probability:** The Y-axis of a PDF plot is *probability density*, not probability. The height of the curve at does NOT give . It gives the relative likelihood of being near 170. Probability = area under the curve, not height. A PDF can even exceed 1 (e.g., a uniform distribution on has density 2 everywhere) — as long as the total area is 1, it is valid. This confuses beginners regularly.
**Critical distinction:** The Y-axis of a PDF plot is *probability density*, not probability. The height of the curve at does NOT give . It gives the relative likelihood of being near 170. Probability = area, not height.

11.6.3 Common Probability Distributions

Bernoulli Distribution

- **Type:** Discrete - **Parameter:** — probability of success - **Use:** Models a *single trial* with exactly two possible outcomes (success/failure) - **Examples:** Flipping a coin once (heads = success or tails = success). Whether a newborn baby is a boy or a girl. - **Relationship to Binomial:** Bernoulli = one trial. Binomial = repeated Bernoulli trials.

Binomial Distribution

- **Type:** Discrete - **Parameters:** — number of trials; — probability of success per trial - **Use:** Models the number of successes in independent trials - **Example:** Flipping a coin 10 times and counting how many times it lands on heads - The number of trials distinguishes it from Bernoulli (which has )

Poisson Distribution

- **Type:** Discrete - **Parameter:** (lambda) — the average rate of occurrence - **Use:** Models the number of times an event happens within a fixed interval of time - **Example (call center):** A call center receives an average of 5 calls per minute. The Poisson distribution predicts the probability of receiving, say, 8 calls in the next minute. - **Example (typos):** A book has an average of 0.5 typos per page. Poisson predicts the probability of finding 3 typos on a specific page. - Lambda is the *rate* — the average number of events per interval.

Uniform Distribution

- **Discrete uniform:** Every outcome has exactly the same probability. - Example: Rolling a fair 6-sided die. Each face has probability . - Parameters: lower bound = 1, upper bound = 6. - **Continuous uniform:** Every value in an interval has equal probability density. - Example: You arrive at a railway station at a random time without checking the schedule. Trains come every 15 minutes. Your waiting time could be anywhere from 0 to 15 minutes (0, 0.1, 0.2, ..., 14.999). All these waiting times are equally likely. - Parameters: lower bound = 0, upper bound = 15.

Normal (Gaussian) Distribution

- **Type:** Continuous - **Parameters:** (mu) — mean (central value); (sigma) — standard deviation (spread) - **Use:** The "bell curve." Most data points cluster around the average. The probability of finding data far from the mean is rare. - **Examples:** Height of people, test scores (SAT, IQ), measurement errors. - Larger = wider distribution. This is why in the Gaussian kernel is called the *width*.

Exponential Distribution

- **Type:** Continuous - **Parameter:** (lambda) — rate - **Use:** Models the *time between events* in a Poisson process. Answers: "How long until the next thing happens?" - **Example:** How long will a car battery last before it dies? It runs fine for a long time, but the probability of failure increases as time goes on. - **Example:** Radioactive decay — the time until a particle decays. - **Shape:** For a long time, the probability of the event is low. After a certain point, the probability increases rapidly.

Gamma Distribution

- **Type:** Continuous - **Parameters:** — shape (number of events); (theta) — scale - **Use:** Models the *waiting time for the -th event*. - **Relationship to Exponential:** Exponential = waiting time for the *first* event. Gamma = waiting time for the *-th* event. (Like Bernoulli vs Binomial.) - **Example:** You have 5 light bulbs. How long until the 5th bulb burns out? Exponential would answer "how long until the first bulb burns out." Gamma answers for the -th. - **Example:** Total rainfall accumulated in a reservoir over time. Rain events are random but have an average rate. The total accumulation follows a Gamma distribution.

11.6.4 Summary — Parameters of Distributions

| Distribution | Type | Parameters | What They Mean | |-------------|------|-----------|----------------| | Bernoulli | Discrete | | Probability of success | | Binomial | Discrete | | Number of trials, probability of success | | Poisson | Discrete | | Average rate of occurrence | | Uniform (discrete) | Discrete | | Lower and upper bounds | | Uniform (continuous) | Continuous | | Lower and upper bounds | | Normal | Continuous | | Mean, standard deviation | | Exponential | Continuous | | Rate | | Gamma | Continuous | | Shape (number of events), scale | **Distinction:** These are *parameters of probability distributions* — they define the shape and characteristics of a distribution. This is different from *parameters of ML algorithms* (like the weights in linear regression), which determine the contribution of each attribute to the prediction.

11.6.5 Student Questions on Probability

**Q:** What is the relationship between Bernoulli and Binomial distributions? **A:** Bernoulli models one trial. Binomial models repeated Bernoulli trials. In Bernoulli, the only parameter is (probability of success). In Binomial, you need both (number of trials) and . A single coin flip is Bernoulli. Ten coin flips counting heads is Binomial. Several students asked variants of this — the key distinction is "one trial" vs " trials." **Q:** What is the relationship between Exponential and Gamma? **A:** Exponential models waiting time for the first event. Gamma models waiting time for the -th event. This is the same pattern as Bernoulli-Binomial: one event vs multiple events.
**Visual intuition — distribution shapes at a glance:** - **Bernoulli:** Two bars (0 and 1), heights and . Simplest possible distribution. - **Binomial:** A discrete "mountain" shape centered at . Wider as grows. - **Poisson:** A discrete mountain with right skew; controls both mean and variance. - **Uniform:** A flat line (discrete: equal-height bars; continuous: flat rectangle). Zero information — every outcome equally likely. - **Normal:** The classic symmetric bell. 68% of data within , 95% within . - **Exponential:** Starts high at zero, decays smoothly to the right. "Memoryless" property: the future does not depend on how long you have already waited. - **Gamma:** Starts at zero, rises to a peak, then decays. When , it *is* the Exponential. **One-sentence takeaway:** The distribution you pick is your assumption about how the world generates data — pick wrong and your parameter estimates will be wrong too. ---
**Recap:** Probability distributions describe how likely different outcomes are. Discrete distributions use PMFs (probability = height); continuous distributions use PDFs (probability = area). Each distribution is defined by parameters (like , , ) that control its shape. **Bridge:** Knowing the distributions is step one. The next question is: given data, how do we figure out which parameter values are most likely? That is parameter estimation (Section 11.7).
**Real-world connection:** The Poisson distribution models call center arrivals and website traffic for capacity planning. The Exponential models failure times in reliability engineering to schedule maintenance. The Normal models measurement errors in physics and manufacturing for tolerance analysis. The Binomial models A/B test conversion rates. Every statistical test and confidence interval you will ever use sits on top of one of these distributions.

11.7 Parameter Estimation

**Hook:** You find a coin on the street. You flip it 100 times and get 63 heads. Is it fair? You don't know the coin's true bias — but you can *estimate* it from the flips you observed. That is parameter estimation: given data, guess the hidden numbers that generated it.

11.7.1 The Concept — A Reverse Problem

*Parameter estimation* is the process of estimating the parameters of a statistical model or probability distribution based on observed data. **Forward problem (probability):** You are *given* the parameters of a distribution. Example: "The data follows a Gaussian distribution with and . What is the probability that a randomly drawn value is 16?" This is what is taught in probability courses. **Reverse problem (parameter estimation):** You are *given* the data but *do not know* the parameters. Example: "Here are the heights of 1,000 people. What values of and for a Gaussian distribution would have most likely generated this data?"
> In the real world, we only see data. We never know the true parameters of the distribution that generated it. Parameter estimation tries to figure out those parameters from the data we have. **The process:** 1. **Assume a probabilistic model.** Decide what distribution you think generated the data. For heights of 1,000 people: "I assume this follows a normal distribution." 2. **Learn the parameters from the data.** Once you assume a normal distribution, you know it has two parameters ( and ). Now estimate their values from the data. For a Gaussian distribution, the PDF is: where are the parameters to estimate. If you assume (known), then parameter estimation reduces to finding only .
**Pitfall — assuming the wrong distribution:** The entire parameter estimation exercise hinges on step 1 — picking the right model family. If you assume a Gaussian but the data is actually from an exponential distribution (long right tail), your estimates of and will be misleading. Always visualize your data (histogram, Q-Q plot) before committing to a distributional assumption.

11.7.2 Point Estimation vs Interval Estimation

**Point Estimation:** Gives a *single specific number* as the best guess for the parameter. Finds the value that maximizes (or minimizes) some function related to the data, such as a likelihood function. Example: Survey 100 people. The average height is exactly 175 cm. This single number (175) is the point estimate for . **Interval Estimation:** Gives a *range of possible values* for the parameter. This range is called a *confidence interval*. Example: "I am 95% confident that the true mean height of the population is between 173 cm and 177 cm."
A 95% confidence interval does not mean "the parameter is in this range 95% of the time." It means: if we repeated the sampling process many times, 95% of the confidence intervals we construct would contain the true parameter.
**Pitfall — misinterpreting confidence intervals:** "I am 95% confident the mean is between 173 and 177" does NOT mean "there is a 95% probability the true mean lies in [173, 177]." The true mean is a fixed number — it is either in the interval or it is not. The 95% refers to the *procedure*: 95% of intervals built this way will capture the true mean. This is a subtle but exam-relevant distinction.
**Which is better?** Interval estimates are generally more reliable because they acknowledge uncertainty. A point estimate of "175 cm" may be slightly off. Saying "between 173 and 177 with 95% confidence" is more honest about what we know. **Preview for next session:** Two important point estimation methods — *Maximum Likelihood Estimation* (MLE) and *Maximum A Posteriori* (MAP) — will be covered. Both produce point estimates (single values). The Naive Bayes classifier and Gibbs classifier will also be introduced.

11.7.3 Student Questions on Parameter Estimation

**Q:** What will MLE mean in the next class? **A:** MLE stands for Maximum Likelihood Estimation. It is a *point estimation* method. If you understand that parameter estimation means "I have data, and I want to find the parameter values of the distribution that most likely generated that data," then MLE is one technique that gives you a single best-guess number for those parameters. MAP is another point estimation method that incorporates prior beliefs.
**Exam note:** The exam will be mostly problem-based, not theory. Formulas and concepts can be referenced from the slides and textbooks. Faculty-provided lecture slides (with solved problems) are allowed. Question banks are NOT allowed. Handwritten notes are NOT allowed. Do not write on the reference materials — they will be kept outside if marked. KNN prediction problems and weighted KNN are compulsory question types. The slides will help for referring to formulas, definitions, default values, and sample problems.
---
**Recap:** Parameter estimation is the reverse of probability — given data, find the distribution parameters that likely generated it. Point estimates give a single number; interval estimates give a range with confidence. **Bridge:** The methods for actually computing these estimates (MLE, MAP) and the classifiers built on Bayesian principles (Naive Bayes, Gibbs) are the subject of the next lecture. For now, internalize the core Bayesian idea: prior + evidence → updated belief, expressed as probabilities.
**Real-world connection:** Parameter estimation is everywhere. *Insurance actuaries* estimate claim frequency parameters from historical data to set premiums. *Quality control engineers* estimate defect rates from sample inspections. *Pharmaceutical researchers* estimate drug efficacy from clinical trials. The confidence interval is what the FDA cares about. Not just "the drug works" but "we are 95% confident the effect size is between X and Y."

Exam Guidance Summary

**Exam note — format and materials:** - **Exam format:** Open book — slides and textbooks allowed. Problem-based, not theory-heavy. - **Allowed materials:** Faculty-provided lecture slides (including slides with solved example problems). Question banks are NOT allowed. Handwritten notes are NOT allowed. Do not write on any reference materials — they will be kept outside if marked.
**Compulsory problem types:** KNN predicting a value, weighted KNN computation, locally weighted regression. **Key topics for exam:** - Standard KNN algorithm and classification (discrete-valued target function) - K value selection (rule of thumb, elbow method, cross validation) - Argmax function and Kronecker delta - Distance-weighted KNN (formula, worked computation) - Weight functions / kernels (inverse square, modified inverse square, Gaussian) - Locally weighted regression (formula, approach, gradient descent update) - Radial basis functions (concept and connection to KNN/ANNs) - Bayesian learning concepts (prior, evidence, updated belief) - Probability distributions and their parameters - Parameter estimation (point vs interval) **Study advice:** Go through the recordings. Cross-reference the Python notebooks for worked examples. Understand the formulas but you can refer to slides during the exam. Practice the numerical problems — KNN with and without weights, locally weighted regression gradient descent updates.

Key Industry Applications and Tools

- **KNN:** Recommendation systems (collaborative filtering), anomaly detection, context-based search / document retrieval, classification problems in low dimensions. The go-to baseline — if a deep model cannot beat KNN, something is wrong with the pipeline. - **Distance-weighted KNN:** Any application where proximity matters and noise is present — the weighting helps suppress irrelevant or noisy neighbors. Geospatial interpolation (estimating values at unmeasured locations by weighting nearby measurements) is a canonical use case. - **Locally weighted regression:** Non-linear regression problems where a single global model fails — financial forecasting (non-stationary trends), weather prediction, robotics trajectory learning, any domain with curvy trends. - **Radial basis functions:** Artificial neural networks (RBF networks), function approximation, interpolation of scattered data (e.g., terrain modeling from GPS points). Also the theoretical foundation for RBF-kernel SVMs. - **Bayesian learning:** Medical diagnosis (updating disease probability with test results), spam filtering (Naive Bayes updating word-by-word), weather prediction, A/B testing (Bayesian bandits), any domain requiring confidence estimates alongside predictions. - **Cross validation (k-fold):** Universal model evaluation technique used across all ML workflows — not specific to KNN, but KNN's dependence on makes cross validation essential for it. - **Grid search:** Hyperparameter tuning used in production ML pipelines. For KNN, it automates the search for optimal , distance metric, and kernel parameters simultaneously. - **Python libraries referenced:** Scikit-learn (`KNeighborsClassifier`, `KNeighborsRegressor`, `GridSearchCV`, `cross_val_score`). These implement everything covered in this lecture — from standard KNN to distance-weighted variants. The `weights` parameter controls uniform vs distance weighting; `algorithm` selects the neighbor-search method (brute, kd-tree, ball-tree).

ML Lecture 11 notes · Instance-Based Learning — Distance-Weighted KNN, Locally Weighted Regression, and Bayesian Learning Foundations

Machine Learning· postgraduate· 2026-06-29

Sections Breakdown

1KNN Algorithm Refresher

Recap of standard KNN classification and regression, K value selection, argmax function, and symbol registry.

2Distance-Weighted KNN

Weight functions, kernel functions, inverse-square weighting, modified inverse-square with d₀, Gaussian kernel, and worked customer classification example.

3Locally Weighted Regression

Local approximation model, three approaches to local error, gradient descent update with kernel weights, worked product price prediction example.

4Radial Basis Functions

RBF network architecture, relationship between KNN and RBF, prediction function with kernel-weighted components.

5Bayesian Learning — Introduction

Probabilistic reasoning vs fixed parameters, prior belief, evidence, updated belief, medical diagnosis example.

6Probability Foundations

Random variables, probability distributions, PMF vs PDF, common distributions (Bernoulli, Binomial, Poisson, Uniform, Normal, Exponential, Gamma).

7Parameter Estimation

Forward vs reverse problems, point estimation vs interval estimation, confidence intervals, preview of MLE and MAP.

8Exam Guidance Summary

Exam format, allowed materials, compulsory problem types, key topics, and study advice.

9Key Industry Applications and Tools

Real-world applications of KNN, distance-weighted KNN, locally weighted regression, RBF networks, Bayesian learning, and Python libraries.

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.

KNN Algorithm

Must-know: KNN is a lazy, instance-based learner: no training, all work at query time. Classification uses majority vote among k nearest neighbors via argmax of Kronecker delta sums.

⚠️ Top pitfall: Choosing k too small (k=1) causes overfitting/high variance; too large causes underfitting/high bias. Always pick odd k for binary classification.

Self-check: With k=3 and neighbors [apple, banana, apple], what class is predicted?

Connects to: Distance-weighted KNN, Bias-variance tradeoff.

K Value Selection

Must-know: Three methods: rule of thumb (k = sqrt(n)), elbow method (plot error vs k), and k-fold cross validation (most robust). Grid search automates this.

⚠️ Top pitfall: Using the rule of thumb for large datasets. Always prefer cross validation for larger datasets.

Self-check: What is the elbow point in a plot of error rate vs k?

Connects to: Cross validation, Grid search.

Distance-Weighted KNN

Must-know: Weight each neighbor's vote by inverse-square distance: w_i = 1/d(x_q, x_i)^2. Closer neighbors get exponentially more influence.

⚠️ Top pitfall: Weighted KNN can be too sensitive to a single extremely close neighbor if kernel decay is very aggressive (e.g., Gaussian with tiny sigma).

Self-check: If a neighbor is at distance 0.5, what is its inverse-square weight?

Connects to: KNN Algorithm, Kernel functions.

Kernel Functions

Must-know: Kernels convert distance to weight: inverse (1/d), inverse-square (1/d^2), modified inverse-square with d_0, and Gaussian (e^{-d^2/2b}). Faster decay = more local model.

⚠️ Top pitfall: Without d_0, distance zero causes division by infinity. Always add a small constant d_0 to prevent numerical issues.

Self-check: What happens to the Gaussian weight when distance equals 3 and sigma equals 1?

Connects to: Distance-weighted KNN, Locally weighted regression.

Locally Weighted Regression

Must-know: Fits a custom local model per query point using kernel-weighted neighbors. The gradient descent update multiplies each error term by K(d(x_q, x_i)).

⚠️ Top pitfall: Hard window (Method 1) produces jagged step-function fit. Always use kernel weighting (Method 3) for smooth transitions.

Self-check: How does the locally weighted regression update differ from standard gradient descent?

Connects to: Linear regression, Kernel functions.

Radial Basis Functions

Must-know: RBF networks use K pre-selected prototype centers with kernel-weighted responses. A three-layer neural network bridging instance-based learning and ANNs.

⚠️ Top pitfall: Confusing uppercase K (number of components) with lowercase K() (kernel function). They are completely different things.

Self-check: How is an RBF network different from weighted KNN in terms of training?

Connects to: KNN Algorithm, Distance-weighted KNN, Neural networks.

Bayesian Learning

Must-know: Bayesian learning treats parameters as probability distributions, not fixed constants. Prior + evidence → updated belief via Bayes' theorem.

⚠️ Top pitfall: Garbage prior leads to garbage posterior, regardless of evidence strength. A strong prior requires strong evidence to overturn.

Self-check: Starting with a prior of 1% disease prevalence, what happens to the posterior after a positive test?

Connects to: Parameter estimation, Probability foundations.

Probability Distributions

Must-know: Discrete: PMF (probability = height). Continuous: PDF (probability = area under curve, not height). Key distributions: Bernoulli, Binomial, Poisson, Uniform, Normal, Exponential, Gamma.

⚠️ Top pitfall: PDF height is NOT probability. A PDF can exceed 1 as long as total area = 1.

Self-check: What is the relationship between Bernoulli and Binomial distributions? Between Exponential and Gamma?

Connects to: Bayesian learning, Parameter estimation.

Parameter Estimation

Must-know: Reverse problem: given data, find distribution parameters. Point estimation gives a single value; interval estimation gives a confidence range.

⚠️ Top pitfall: 95% confidence does NOT mean 95% probability the parameter is in the interval. It means 95% of intervals built this way capture the true parameter.

Self-check: What is the difference between point estimation and interval estimation?

Connects to: Bayesian learning, Probability distributions.

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.