Chapter 6: Classification

Training a K Nearest Neighbour classifier

face Josiah Wang

Let’s say we choose K Nearest Neighbours, which will be the first classifier you will cover in the Introduction to Machine Learning course.

All you need to do is import the KNeighborsClassifier class, and then create a new instance of the classifier with some of your model hyperparameters, for example the number of neighbours K and the distance metric.

>>> from sklearn.neighbors import KNeighborsClassifier
>>> knn_classifier = KNeighborsClassifier(n_neighbors=5, metric="euclidean")

Then all you need to do is to .fit() the classifier to your training dataset. Congratulations, you have trained your model! 🎊🎊🎊

>>> knn_classifier.fit(x_train, y_train)

After fitting, you have access to various attributes of the classifier. These attributes usually end with an underscore_. For example, you can check the classes recognised by our classifier with knn_classifier.classes_.

The attributes vary depending on your classification model. See the official documentation for a list of attributes for KNeighborsClassifier.