Skip to learning content

DATA SCIENCE PYTHON PLAYGROUND

Machine Learning · Learn / Refresh

← Classification lessons
Probabilities and neighbours · ML-C08 · 25–40 MIN

Neighbour voting

Explain a classifier’s local distance-based decision.

  1. FollowFit and predict before inspecting neighboursCurrent exercise
  2. ChangeAdapt the Python
  3. TransferCompute and inspect the evidence
  4. ApplyBuild a guided full workflow

Understand the idea

KNN stores training examples. To predict, find nearby examples and let their labels vote. k changes how local that vote is. Distance depends on measurement units, so the familiar Pipeline learns an input scale from training rows.

Illustrative data

Illustrative data
ColumnValues
Class An2: (0.5, 0.2); n3: (0.4, 0.5); n6: (1.5, 1.2); n7: (-1.5, -0.2); n9: (2.9, 0.9)
Class Bn1: (0.3, 0.2); n4: (1, 0.4); n5: (-0.9, 0.5); n8: (2.4, 0)

Click the highlighted code to change the result.

example_model = Pipeline([
    ("prepare", StandardScaler()),
    ("model", KNeighborsClassifier(n_neighbors=)),
])
example_model.fit(example_X, example_y)
example_model.predict(pd.DataFrame({"x": [], "y": []}))
Query (0, 0): 2 A + 1 B → A. Neighbours: n1, n2, n7.Training-SD units · ○ A □ B-2-10123y / SD = 1n1: (0.3, 0.2), class Bn1n2: (0.5, 0.2), class An2n3: (0.4, 0.5), class An3n4: (1, 0.4), class Bn4n5: (-0.9, 0.5), class Bn5n6: (1.5, 1.2), class An6n7: (-1.5, -0.2), class An7n8: (2.4, 0), class Bn8n9: (2.9, 0.9), class An9Query: (0, 0)3 neighbours: 2 A + 1 B → A

k=3: 2 A + 1 B → A; nearest rows n1, n2, n7. Distances use training standard deviations.

What the syntax does

KNeighborsClassifier(n_neighbors=3)
  • Creates a K-nearest neighbours classifier.
  • n_neighbors: 1, 3, 5, 9
  • n_neighbors is a positive integer no larger than the fitting-row count; the sklearn default is 5.
  • The first example deliberately uses 3.
  • Small k can follow noise; larger k pools a wider region.
  • Choose using training validation with fold-local scaling.

Supplied for this practice

These objects are prepared afresh before your editor runs.

X
Feature dataframe for the declared population, preserving row indices.
X = df[['length', 'width']]
y
Target series, aligned with X.
y = df.label
X_train / X_test / y_train / y_test
Training feature rows from the declared split. Final-test feature rows from the declared split. Training targets, aligned with X_train. Final-test targets, aligned with X_test.
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)

Outputs you create

answer
  1. The requested result, with the values, labels and row order described by this task.
CLASS18 · all rows
lengthwidthlabel
236.033-0.805568A
581.2970.728558A
-1511.27-1.00866A
99.0248-0.24496A
-13.0141-0.660765A
681.1790.602475A
2051.151.87316B
2362.130.334395B
2285.630.257253B
2680.440.961328B
1856.810.472554B
2946.980.880302B
-331.7812.72724C
412.3253.28307C
319.7013.33371C
1658.912.68519C
-396.7822.36965C
477.1363.8745C
Your task
  1. Fit a scaled three-neighbour classifier on X_train and y_train.
  2. Store its predicted class for the first test row in answer.
answer
Hints

Think: Nearby fitted training labels vote; scaling makes the two measurement units comparable.

Tools: Pipeline, StandardScaler, KNeighborsClassifier(n_neighbors=3), fit and predict.

Approach: Build the named preparation/model recipe, fit only training rows and predict the first held-away row.

Explained solution
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
model=Pipeline([('prepare',StandardScaler()),('model',KNeighborsClassifier(n_neighbors=3))])
model.fit(X_train,y_train)
answer=model.predict(X_test.iloc[:1])

Three nearby training examples vote for a class. The Pipeline learns the distance scale on fitting rows and reuses it when predicting. This introductory round needs only fit and predict; the next round retrieves the actual neighbours and counts their labels.

Ctrl/⌘+Enter: Run · Tab: indent · Esc then Tab: leave editor

Python loads when you run. Code and results stay in this activity only.

Run your code to inspect its output. Check uses that same run.