Top Python Libraries

Top Python Libraries

Share this post

Top Python Libraries
Top Python Libraries
KNN (Part 2): How to Recognize Handwritten Digits?(Practical Data Analysis 19)

KNN (Part 2): How to Recognize Handwritten Digits?(Practical Data Analysis 19)

Learn how to classify handwritten digits using KNN in Python's sklearn. Compare KNN, SVM, Naive Bayes, and Decision Tree for accuracy and performance.

Meng Li's avatar
Meng Li
Jan 18, 2025
∙ Paid

Share this post

Top Python Libraries
Top Python Libraries
KNN (Part 2): How to Recognize Handwritten Digits?(Practical Data Analysis 19)
1
Share
A minimalistic and clean image featuring only the text 'KNN' in bold, modern, and professional font, centered on a white background. The style should be sleek, tech-oriented, and suitable for presentations or technical documentation. The aspect ratio is widescreen, emphasizing width over height for better presentation fit.

Welcome to the "Practical Data Analysis" Series.

Table of Contents

Table of Contents

Meng Li
·
July 12, 2024
Read full story

Today, I'll guide you through a hands-on practice with KNN.

In the previous lesson, I explained that KNN essentially calculates the distance between the object to be classified and other objects. Then, based on the classifications of the nearest KK neighbors, it determines the classification of the object.

KNN (Part 1): How to Classify Movie Genres Based on Fight and Kiss Counts?(Practical Data Analysis 18)

KNN (Part 1): How to Classify Movie Genres Based on Fight and Kiss Counts?(Practical Data Analysis 18)

Meng Li
·
Jan 13
Read full story

In this lesson, we’ll first look at how to use the KNN algorithm in sklearn, and then practice with the built-in handwritten digit dataset in sklearn.

Previously, I also covered SVM, Naive Bayes, and Decision Tree classifiers. We can also use this dataset to train these classifiers and compare their results.

How to Use KNN in sklearn

The sklearn package in Python includes the KNN algorithm. KNN can be used for both classification and regression. For classification, you’ll need to import:

from sklearn.neighbors import KNeighborsClassifier

For regression, you’ll need to import:

from sklearn.neighbors import KNeighborsRegressor

From the names, you can tell that Classifier is for classification, and Regressor is for regression.

Generally, if an algorithm has a Classifier class, you can also find a corresponding Regressor class.

For example, in decision tree classification, you can use DecisionTreeClassifier, and for regression, you can use DecisionTreeRegressor.

Now, let’s see how to create a KNN classifier in sklearn.

This post is for paid subscribers

Already a paid subscriber? Sign in
© 2025 Meng Li
Privacy ∙ Terms ∙ Collection notice
Start writingGet the app
Substack is the home for great culture

Share