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
n_neighborsis how many votes decide a label.- Distance-based, so scaling is not optional.
kneighborsshows which training rows answered.
Keywords and builtins used here
print
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.
Step 3 of 4 in Models, step 14 of 25 in Machine learning with scikit-learn.