HomeAll tracks · pricing · account
Python11 apps · Python, SQL & data
Start free Log in
Subscribe to unlock this lesson.
Subscribe to unlock this lesson.
Subscribe to unlock this lesson.
Subscribe to unlock this lesson.
Subscribe to unlock this lesson.
Subscribe to unlock this lesson.
Subscribe to unlock this lesson.
← Machine Learning 0 / 11
Loading Python and scikit-learn in your browser… (the first time takes a moment, then it’s cached). You can start reading now.

Lesson 01Foundationsabout 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.

You’ll useKNeighborsClassifier · fit · predict
  1. Dataload, X and y
  2. Splittrain / test
  3. Prepareclean, encode, scale
  4. Modelfit
  5. Evaluatepredict, score
  6. 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?

The mental model`fit` does not find a formula here. It **remembers** the examples. `predict` finds the k most similar ones and lets them vote.
Why it mattersEvery scikit-learn model, from this one to gradient boosting, is used the same way: make it, `fit(X, y)`, then `predict` on new X. Learn that shape once and you can use every model in this course.

🧪 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.