2010-03-17 21:28:18 +08:00
|
|
|
"""
|
2011-09-12 01:45:34 +08:00
|
|
|
================================
|
|
|
|
|
Nearest Neighbors Classification
|
|
|
|
|
================================
|
2010-04-14 17:37:51 +08:00
|
|
|
|
2011-04-16 20:44:36 +08:00
|
|
|
Sample usage of Nearest Neighbors classification.
|
|
|
|
|
It will plot the decision boundaries for each class.
|
2021-10-22 21:33:22 +08:00
|
|
|
|
2010-03-17 21:28:18 +08:00
|
|
|
"""
|
2010-04-22 01:04:36 +08:00
|
|
|
|
2014-05-15 04:31:03 +08:00
|
|
|
import matplotlib.pyplot as plt
|
2020-08-22 01:20:01 +08:00
|
|
|
import seaborn as sns
|
2011-09-12 01:45:34 +08:00
|
|
|
from matplotlib.colors import ListedColormap
|
2011-09-02 17:00:02 +08:00
|
|
|
from sklearn import neighbors, datasets
|
2022-03-29 22:36:31 +08:00
|
|
|
from sklearn.inspection import DecisionBoundaryDisplay
|
2010-03-17 21:28:18 +08:00
|
|
|
|
2011-09-12 07:17:57 +08:00
|
|
|
n_neighbors = 15
|
2011-09-10 00:00:59 +08:00
|
|
|
|
2010-03-17 21:28:18 +08:00
|
|
|
# import some data to play with
|
2010-04-19 22:15:47 +08:00
|
|
|
iris = datasets.load_iris()
|
2017-06-07 19:23:12 +08:00
|
|
|
|
|
|
|
|
# we only take the first two features. We could avoid this ugly
|
|
|
|
|
# slicing by using a two-dim dataset
|
|
|
|
|
X = iris.data[:, :2]
|
2011-09-10 00:00:59 +08:00
|
|
|
y = iris.target
|
2010-03-17 21:28:18 +08:00
|
|
|
|
2011-09-12 01:45:34 +08:00
|
|
|
# Create color maps
|
2019-06-14 23:38:18 +08:00
|
|
|
cmap_light = ListedColormap(["orange", "cyan", "cornflowerblue"])
|
2020-08-22 01:20:01 +08:00
|
|
|
cmap_bold = ["darkorange", "c", "darkblue"]
|
2011-09-12 01:45:34 +08:00
|
|
|
|
2011-09-12 07:17:57 +08:00
|
|
|
for weights in ["uniform", "distance"]:
|
|
|
|
|
# we create an instance of Neighbours Classifier and fit the data.
|
|
|
|
|
clf = neighbors.KNeighborsClassifier(n_neighbors, weights=weights)
|
|
|
|
|
clf.fit(X, y)
|
|
|
|
|
|
2022-03-29 22:36:31 +08:00
|
|
|
_, ax = plt.subplots()
|
|
|
|
|
DecisionBoundaryDisplay.from_estimator(
|
|
|
|
|
clf,
|
|
|
|
|
X,
|
|
|
|
|
cmap=cmap_light,
|
|
|
|
|
ax=ax,
|
|
|
|
|
response_method="predict",
|
|
|
|
|
plot_method="pcolormesh",
|
|
|
|
|
xlabel=iris.feature_names[0],
|
|
|
|
|
ylabel=iris.feature_names[1],
|
|
|
|
|
shading="auto",
|
|
|
|
|
)
|
2011-09-16 17:29:26 +08:00
|
|
|
|
2011-09-12 07:17:57 +08:00
|
|
|
# Plot also the training points
|
2020-08-22 01:20:01 +08:00
|
|
|
sns.scatterplot(
|
|
|
|
|
x=X[:, 0],
|
|
|
|
|
y=X[:, 1],
|
|
|
|
|
hue=iris.target_names[y],
|
|
|
|
|
palette=cmap_bold,
|
|
|
|
|
alpha=1.0,
|
|
|
|
|
edgecolor="black",
|
|
|
|
|
)
|
2014-05-15 04:31:03 +08:00
|
|
|
plt.title(
|
|
|
|
|
"3-Class classification (k = %i, weights = '%s')" % (n_neighbors, weights)
|
2014-05-15 10:35:13 +08:00
|
|
|
)
|
2011-09-16 17:29:26 +08:00
|
|
|
|
2014-05-15 04:31:03 +08:00
|
|
|
plt.show()
|