Skip to content

Commit 1283953

Browse files
authored
DOC Refactor plot_kmeans_digits.py to use DecisionBoundaryDisplay (scikit-learn#34515)
1 parent 4c710ce commit 1283953

1 file changed

Lines changed: 13 additions & 25 deletions

File tree

examples/cluster/plot_kmeans_digits.py

Lines changed: 13 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -155,32 +155,22 @@ def bench_k_means(kmeans, name, data, labels):
155155
# 2-dimensional space and plot the data and the clusters in this new space.
156156
import matplotlib.pyplot as plt
157157

158+
from sklearn.inspection import DecisionBoundaryDisplay
159+
158160
reduced_data = PCA(n_components=2).fit_transform(data)
159-
kmeans = KMeans(init="k-means++", n_clusters=n_digits, n_init=4)
161+
kmeans = KMeans(init="k-means++", n_clusters=n_digits, n_init=4, random_state=42)
160162
kmeans.fit(reduced_data)
161163

162-
# Step size of the mesh. Decrease to increase the quality of the VQ.
163-
h = 0.02 # point in the mesh [x_min, x_max]x[y_min, y_max].
164-
165-
# Plot the decision boundary. For that, we will assign a color to each
166-
x_min, x_max = reduced_data[:, 0].min() - 1, reduced_data[:, 0].max() + 1
167-
y_min, y_max = reduced_data[:, 1].min() - 1, reduced_data[:, 1].max() + 1
168-
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
169-
170-
# Obtain labels for each point in mesh. Use last trained model.
171-
Z = kmeans.predict(np.c_[xx.ravel(), yy.ravel()])
172-
173-
# Put the result into a color plot
174-
Z = Z.reshape(xx.shape)
175-
plt.figure(1)
176-
plt.clf()
177-
plt.imshow(
178-
Z,
179-
interpolation="nearest",
180-
extent=(xx.min(), xx.max(), yy.min(), yy.max()),
181-
cmap=plt.cm.Paired,
182-
aspect="auto",
183-
origin="lower",
164+
plt.figure()
165+
166+
DecisionBoundaryDisplay.from_estimator(
167+
kmeans,
168+
reduced_data,
169+
ax=plt.gca(),
170+
response_method="predict",
171+
alpha=0.8,
172+
plot_method="pcolormesh",
173+
grid_resolution=1000,
184174
)
185175

186176
plt.plot(reduced_data[:, 0], reduced_data[:, 1], "k.", markersize=2)
@@ -199,8 +189,6 @@ def bench_k_means(kmeans, name, data, labels):
199189
"K-means clustering on the digits dataset (PCA-reduced data)\n"
200190
"Centroids are marked with white cross"
201191
)
202-
plt.xlim(x_min, x_max)
203-
plt.ylim(y_min, y_max)
204192
plt.xticks(())
205193
plt.yticks(())
206194
plt.show()

0 commit comments

Comments
 (0)