typestar

Nearest neighbours in Python

The model that does no work until you ask it a question.

from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X = [[0.0, 0.0], [0.4, 0.2], [3.0, 3.0], [3.2, 2.8], [6.0, 6.0]]
y = [0, 0, 1, 1, 2]

model = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=3))
model.fit(X, y)

print(model.predict([[3.1, 3.1]]))
knn = model.named_steps["kneighborsclassifier"]
distances, indices = knn.kneighbors(
    model.named_steps["standardscaler"].transform([[3.1, 3.1]]))
print(indices, distances.round(2))

How it works

  1. n_neighbors is how many votes decide a label.
  2. Distance-based, so scaling is not optional.
  3. kneighbors shows which training rows answered.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
539
Tokens
151
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 82 seconds.

Type this snippet

Step 3 of 4 in Models, step 14 of 25 in Machine learning with scikit-learn.

← Previous Next →