Nicolaesse
Nicolaesse

Reputation: 2714

MGLEARN Plot KNN classification doesn't show the plot

I am moving the first ML steps reading the book Introduction to Machine Learning. I am trying to generate the picture of the snippet "In [10]" that you can find on this page, but it down't work. When I say that it doesn't work I mean that nothing it's been shown when I hit "run" (neither an error message).

What's wrong with the following code?

I think that I am missing something like plt.show() code but looking on Google it seems that mglearn doen't need/have this construction.

from sklearn.neighbors import KNeighborsClassifier
import matplotlib.pyplot as plt
import mglearn.plots

X, y = mglearn.datasets.make_forge()
mglearn.discrete_scatter(X[:, 0], X[:, 1], y)
plt.legend(["Class 0", "Class 1"], loc=4)
plt.xlabel("First feature")
plt.ylabel("Second feature")
print("X.shape: {}".format(X.shape))
#plt.show()


mglearn.plots.plot_knn_classification(n_neighbors=1)

I am using Python 3.6.3.

Upvotes: 0

Views: 3037

Answers (2)

Scarlett
Scarlett

Reputation: 11

It's better to use display function than plt.show().

import mglearn
from IPython.display import display

X,y=mglearn.datasets.make_forge()
knn=mglearn.plots.plot_knn_classification(n_neighbors=1)
display(knn)

Then, we'll have the picture the same as the book. enter image description here

If you use plt.show(), the picture will be different. enter image description here

Upvotes: 1

Nicolaesse
Nicolaesse

Reputation: 2714

Based on @Sascha tips I get the following working code:

from sklearn.neighbors import KNeighborsClassifier
import matplotlib.pyplot as plt
import mglearn.plots

X, y = mglearn.datasets.make_forge()


mglearn.plots.plot_knn_classification(n_neighbors=1)
plt.show()

Upvotes: 2

Related Questions