%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets.samples_generator import make_blobs
centers = [[-2, 2], [2, 2], [0, 4]]
X, y = make_blobs(n_samples=60, centers=centers, random_state=0, cluster_std=0.60)
y
array([1, 0, 0, 1, 0, 1, 1, 0, 2, 2, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0, 1, 1,
2, 0, 0, 1, 2, 0, 0, 2, 2, 2, 1, 2, 1, 2, 2, 1, 0, 1, 1, 0, 1, 2,
1, 1, 0, 1, 0, 2, 2, 1, 1, 2, 2, 0, 1, 2, 0, 1])
plt.figure(figsize=(16,10), dpi=144)
c=np.array(centers)
plt.scatter(X[:, 0], X[:, 1], c=y,s=100, cmap='cool')
plt.scatter(c[:, 0], c[:, 1], s=100, marker='^', c='orange')
from sklearn.neighbors import KNeighborsClassifier
k = 5
clf = KNeighborsClassifier(n_neighbors=k)
clf.fit(X, y);
X_sample = np.array([[0, 2]])
y_sample = clf.predict(X_sample)
neighbors=clf.kneighbors(X_sample, return_distance=False)
neighbors
array([[16, 20, 48, 6, 23]], dtype=int64)
plt.figure(figsize=(16,10), dpi=144)
plt.scatter(X[:, 0], X[:, 1], c=y, s=100, cmap='cool');
plt.scatter(c[:, 0], c[:, 1], s=100, marker='^', c='k');
plt.scatter(X_sample[0][0], X_sample[0][1], marker="x",
c='r', s=200, cmap='cool')
for i in neighbors[0]:
plt.plot([X[i][0], X_sample[0][0]], [X[i][1], X_sample[0][1]],
'-.', linewidth=0.6);