Lesson 01🌱Foundationsabout 12 min
Your first model
Teach a computer to tell apples, pears and plums apart without writing a single rule: `fit` on examples, `predict` the new ones.
KNeighborsClassifier · fit · predict- Dataload, X and y
- Splittrain / test
- Prepareclean, encode, scale
- Modelfit
- Evaluatepredict, score
- Tunesearch the knobs
Watch the idea at work
A market stall measured 150 fruits: how big each one is and how sweet it tastes. Nobody writes a rule like "plums are small". The model looks at the fruits it already knows and lets the **k nearest ones vote**.
Predict first
Before you touch the sliders: if only the **single** nearest fruit votes (k = 1), will the coloured map get smoother or spikier?
🧪 Drag the new fruit into the gap between the apples and the pears and watch the vote split. Then set k to 1, then to 25.
Under the hood · the same idea in plain NumPy
fruit = load('fruit')
X = fruit[['size', 'sweetness']].to_numpy()
y = fruit['kind'].to_numpy()
def knn_predict(x, k=5):
dist = np.sqrt(((X - x) ** 2).sum(axis=1)) # distance to every known fruit
nearest = np.argsort(dist)[:k] # the k closest
kinds, counts = np.unique(y[nearest], return_counts=True)
return kinds[counts.argmax()] # most votes wins
print(knn_predict(np.array([6.0, 7.5])), knn_predict(np.array([8.9, 3.8])))
That is the whole algorithm: a distance, a sort and a vote. scikit-learn does the same with faster search structures and tidier tie-breaking.
How the code fits together
Tap a piece to see what it does.
Run it to see what the program printsWhen to reach for it
👍 Good for
- A quick, honest first model on small data
- Boundaries no straight line could draw
- Explaining a prediction: “these 5 fruits look just like it”
👎 Weak at
- Many features: in high dimensions every point is far from every other (Part 8)
- Big data: each prediction measures the distance to every stored example
- Features in different units, unless you scale them (lesson 14)
⚖️ Needs scaling?
**Yes.** Distance adds up the raw differences, so a feature measured in grams would outvote one measured from 1 to 10.
⏱️ Cost
`fit` is instant: it only stores the data. `predict` measures the distance to every stored example, for each new point.
🎛️ Knobs to turn
n_neighbors↑ smoother, simpler map · ↓ wigglier, follows every odd exampleweights='distance'closer neighbours count for more than far ones
🔗 Cousins
- KNeighborsRegressor: average the neighbours’ numbers (lesson 3)
- Over- and underfitting: picking k well (lesson 5)
Think before you run
Your turn: complete it, change it, make it
Datasets are loaded: load('fruit').
Do you really get it?
Answer everything, then submit
9 of 11 correct passes the lesson and unlocks the next one.
🧰 In your toolbox
KNeighborsClassifierNames a point by a vote of its k nearest examples.Knob: n_neighbors