Explain what K-NN is, which tasks it handles, and how it reaches an answer for a new point.
Describe what K-NN does during training and when the real work happens.
Classify a new point step by step and explain the deciding vote.
Explain what stays the same and what changes between the two tasks.
Explain the trade-off between small and large K and how K is usually picked.
Write both formulas, explain what each measures, and compute them for a pair of points.
Explain what goes wrong without scaling and what to do about it.
Name the four strengths of K-NN.
Name the four weaknesses of K-NN and connect them to how it works.
Describe four real-world uses and how "nearest neighbors" drives each one.
State the big-picture summary of K-NN, including its two most important decisions.
Explain how the notebook builds the features X and target y and splits them.
dataset.iloc[:, :-1].values: every column but the last (Age, EstimatedSalary).dataset.iloc[:, -1].values: the last column (Purchased, 0 or 1).train_test_split(X, y, test_size = 0.25, random_state = 0) → 300 training rows, 100 test rows; same shuffle every run.Explain the scaling cell and why it matters even more for K-NN.
sc = StandardScaler().sc.fit_transform(X_train) learns the training mean and standard deviation, then scales.sc.transform(X_test) applies the training numbers, so no test information leaks in.Explain each argument of KNeighborsClassifier and what .fit does for a lazy learner.
from sklearn.neighbors import KNeighborsClassifier.n_neighbors = 5 — K = 5 (odd, so a two-class vote can't tie).metric = 'minkowski', p = 2 — Minkowski distance with p = 2 is Euclidean distance (p = 1 would be Manhattan)..fit(X_train, y_train) — for a lazy learner, fitting just stores the scaled training data and labels; no weights are learned.weights='uniform' (every neighbor's vote counts equally).Read the single-prediction line inside-out and explain the vote behind its answer.
classifier.predict(sc.transform([[30, 87000]])) → [0].Read the prediction table, the confusion matrix, and the accuracy.
y_pred = classifier.predict(X_test); the printed table puts predicted on the left, actual on the right.confusion_matrix(y_test, y_pred) → [[64 4] [3 29]].Explain how the plotting cell colors the chart and what the K-NN boundary looks like.
sc.inverse_transform(...) puts real ages and salaries back on the axes.np.meshgrid with step = 1 builds about 8.5 million (age, salary) points; K-NN predicts every one, which is slow.plt.contourf paints predicted 0 red and predicted 1 green; plt.scatter plots the real points in their true colors.Compare the Module 6 and Module 7 notebooks: code, model behavior, boundary, and results.
Social_Network_Ads.csv), whose outputs were reproduced to confirm every number. The notebook has no written explanations, so code behavior there comes from the scikit-learn / NumPy / Matplotlib documentation (links on the Notes tab). All diagrams on this page are redrawn for study. Purple Study aid boxes are memory tricks, OOP reminders, extra runs on the class data, and links to earlier modules — not lecture content.| Step | What happens | In the picture above |
|---|---|---|
| 1 · Choose K | Pick the number of neighbors to look at. | K = 3 |
| 2 · Calculate distances | Measure the distance from the new point to every point in the training data. | Star → every shape |
| 3 · Find the K closest | Keep the K points with the smallest distances — the "nearest neighbors." | The 3 shapes inside the dashed circle |
| 4 · Vote (or average) | Classification: majority vote of the neighbors' classes. Regression: average of their values. | 2 circles vs 1 triangle → Class 0 |
The lecture sums it up in three stages: store the data (keep all training examples and their labels) → find the K nearest neighbors → majority vote (predict the class with the most neighbors).
| Classification | Regression | |
|---|---|---|
| Predicts | A class label | A continuous value |
| Final step | Majority vote among the K nearest neighbors | Average of the K nearest neighbors' values |
| Finding neighbors | Exactly the same in both — only the final step changes. | |
| Small K (e.g., K = 1) | Large K (e.g., K = 15) | |
|---|---|---|
| Boundary | Jagged; bends around single points | Smoother |
| Noise & outliers | Sensitive to noise; easily swayed by outliers | Less swayed — many neighbors vote |
| Risk | Overfits to noise | Can blur the boundary between classes; may underfit |
| K | Training accuracy | Test accuracy |
|---|---|---|
| 1 | 1.00 | 0.87 |
| 3 | 0.91 | 0.93 |
| 5 (class) | 0.91 | 0.93 |
| 7 | 0.91 | 0.93 |
| 15 | 0.91 | 0.93 |
| 25 | 0.90 | 0.93 |
| Metric | Formula | What it measures |
|---|---|---|
| Euclidean | d(p,q) = √( Σ (pᵢ − qᵢ)² ) | Straight-line distance — the most common choice for K-NN. |
| Manhattan | d(p,q) = Σ |pᵢ − qᵢ| | Sums the absolute differences — like navigating a city grid. |
| Points | Differences | Euclidean | Manhattan |
|---|---|---|---|
| (1, 1) → (4, 5) | 3, 4 | √(9 + 16) = 5 | 3 + 4 = 7 |
| (0, 0) → (6, 8) | 6, 8 | √(36 + 64) = 10 | 6 + 8 = 14 |
| (2, 7) → (2, 3) | 0, 4 | √(0 + 16) = 4 | 0 + 4 = 4 |
| (1, 2, 3) → (3, 4, 4) | 2, 2, 1 | √(4 + 4 + 1) = 3 | 2 + 2 + 1 = 5 |
The class data shows it. Same new person, two possible neighbors:
x' = (x − min) / (max − min) → squeezes values into [0, 1]; sensitive to outliers. Z-score standardization: z = (x − μ) / σ → mean 0, standard deviation 1; more robust to outliers. The class notebook uses z-score (StandardScaler).[[59 9] [8 24]]). For the 30-year-old earning $87,000, the five raw-data neighbors all earn $86,000–$88,000 but range in age from 18 to 41 — age barely counts.| Strengths | Weaknesses |
|---|---|
| Simple and intuitive to understand | Slow at prediction time on large datasets |
| No real training phase | Sensitive to irrelevant features and unscaled data |
| Works for both classification and regression | Struggles with high-dimensional data |
| Naturally handles multi-class problems | Memory-intensive — it stores the entire dataset |
| Use | How "nearest neighbors" shows up |
|---|---|
| Recommendations | Find users or items similar to a given one. |
| Image recognition | Classify an image based on similar-looking labeled images. |
| Anomaly detection | Flag points that have very few close neighbors. |
| Medical diagnosis | Classify a patient based on similar historical patient records. |
concatenate, meshgrid, arange).| Age | EstimatedSalary | Purchased |
|---|---|---|
| 19 | 19000 | 0 |
| 35 | 20000 | 0 |
| 26 | 43000 | 0 |
| … | … | … |
| 400 rows · 257 with 0, 143 with 1 · ages 18–60 · salaries 15,000–150,000 (counted from the class CSV) | ||
iloc[:, :-1] — all rows, every column except the last → the features.iloc[:, -1] — all rows, last column only → the target..values — hands back the plain NumPy array.X_train, X_test, y_train, y_test, y_pred.test_size = 0.25 — 100 test rows, 300 training rows.X_train, X_test, y_train, y_test.random_state = 0 — same shuffle every run (and the same split as Module 6).| Age | EstimatedSalary | |
|---|---|---|
Training mean (learned by fit) | ≈ 38.1 | ≈ 69,583 |
Training std (learned by fit) | ≈ 10.1 | ≈ 34,491 |
| First training row, before | 44 | 39000 |
| Same row, after | 0.58164944 | −0.88670699 |
sc.mean_, sc.scale_) on the same split.sc = StandardScaler() creates an object (like new StandardScaler() in Java). fit_transform stores the training mean and std inside sc as fields. Every later sc.transform(...) — on X_test, on the new person, on the plot grid — reuses them.| Argument | Meaning | Lecture link |
|---|---|---|
n_neighbors = 5 | K — how many neighbors vote. | Step 1 · odd K avoids ties |
metric = 'minkowski' | The distance formula family. | Distance metrics |
p = 2 | With Minkowski, p = 2 is Euclidean; p = 1 is Manhattan. | Euclidean = most common |
weights='uniform' (default, printed) | Every neighbor's vote counts equally. | Majority vote |
.fit does here — K-NN is a lazy learner, so fitting just stores the scaled training points and their labels. No weights or bias are learned (compare Module 6).algorithm, leaf_size and n_jobs control how scikit-learn searches for neighbors and aren't covered in the lecture.(Σ |pᵢ − qᵢ|p)1/p. With p = 1 that's the lecture's Manhattan formula; with p = 2 it's the Euclidean formula. The lecture itself never names Minkowski — it only appears in the notebook.LogisticRegression (Module 6) and KNeighborsClassifier have .fit() and .predict(). That's like two Java classes implementing the same interface: you call the same methods, but each class does its own thing inside. Logistic regression's fit learns weights; K-NN's fit just saves the data in the object's fields.[[30, 87000]] → sc.transform scales it → classifier.predict runs the K-NN vote → print.[0]: a 30-year-old earning $87,000 is predicted not to purchase.What the vote looked like (reproduced with classifier.kneighbors, not run in class):
classifier.predict_proba(...) on this person returns [[1. 0.]]: 5 of 5 neighbors are class 0, so "probability" of class 0 = 5/5 = 1.0. For K-NN that number is just the share of neighbor votes. Not on the quiz.y_pred), right column = actual (y_test).reshape(len(y_pred), 1) turns each flat array into a column; np.concatenate(..., 1) glues the columns side by side.| Predicted 0 | Predicted 1 | |
|---|---|---|
| Actual 0 | TN = 64 correctly said "won't buy" | FP = 4 said "buy" — didn't |
| Actual 1 | FN = 3 said "won't buy" — did | TP = 29 correctly said "buy" |
[[TN FP] [FN TP]]. Module 5's matrix put the positive class first. The layout comes from the scikit-learn documentation; the notebook doesn't label it.| Piece | What it does |
|---|---|
A · sc.inverse_transform(...) | Undoes the scaling so the axes show real ages and salaries. |
B · np.meshgrid(...), step = 1 | Builds a grid of (age, salary) points: 10 years past the age range and 1,000 past the salary range, in steps of 1. That's 62 ages × 137,000 salaries ≈ 8.5 million points. |
C · plt.contourf(...) | Flattens the grid, scales it, predicts every point with K-NN, folds the answers back into the grid shape, and paints the background: red = predicted 0, green = predicted 1. |
D · plt.scatter loop | Plots each real point in its true color: red for 0, green for 1. |
c-argument warning as Module 6.| Logistic regression | K-NN (K = 5) | |
|---|---|---|
| Model line | LogisticRegression(random_state = 0) | KNeighborsClassifier(n_neighbors = 5, metric = 'minkowski', p = 2) |
What .fit does | Learns weights and a bias | Stores the training data (lazy) |
| Boundary | Straight line | Irregular, jagged |
| Confusion matrix | [[65 3] [8 24]] | [[64 4] [3 29]] |
| Accuracy | 0.89 | 0.93 |
| Missed buyers (FN) | 8 | 3 |
| Recall (study aid) | 0.75 | ≈ 0.91 |
| New person (30, $87,000) | 0 | 0 |