0

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.

Nicolaesse
  • 2,554
  • 12
  • 46
  • 71
  • Call show after plot_knn_classification. – sascha Nov 24 '17 at 23:07
  • @sascha I can't find a show command for Mglearn...what's the syntax? – Nicolaesse Nov 24 '17 at 23:15
  • 1
    You use matplotlibs! Consider reading a basic matplotlib tutorial. Do ```plt.show()``` right after ```plot_knn_classification```. And consider using jupyter-notebooks, like this tutorial probably is build for. – sascha Nov 24 '17 at 23:16
  • @sascha great...it works, thank you! – Nicolaesse Nov 24 '17 at 23:23
  • 1
    Good. See [here](https://github.com/amueller/introduction_to_ml_with_python/blob/master/mglearn/plot_knn_classification.py) that this function you use is just a small wrapper calling matplotlib too (besides some ML-processings). But as can be seen there is nothing to actually show the plot. Therefore this call after. – sascha Nov 24 '17 at 23:26

2 Answers2

1

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()
Nicolaesse
  • 2,554
  • 12
  • 46
  • 71
1

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

Scarlett
  • 11
  • 1