How to use nearest neighbours for Classification in python

This recipe helps you use nearest neighbours for Classification in python

Recipe Objective

Many a times while working on a dataset and using a Machine Learning model we don"t know which set of hyperparameters will give us the best result. Passing all sets of hyperparameters manually through the model and checking the result might be a hectic work and may not be possible to do.

To get the best set of hyperparameters we can use Grid Search. Grid Search passes all combinations of hyperparameters one by one into the model and check the result. Finally it gives us the set of hyperparemeters which gives the best result after passing in the model.

So this recipe is a short example of how can use nearest neighbours for Classification.

German Credit Card Dataset Analysis

Step 1 - Import the library - GridSearchCv

from sklearn import decomposition, datasets from sklearn import neighbors from sklearn.pipeline import Pipeline from sklearn.model_selection import GridSearchCV, cross_val_score from sklearn.preprocessing import StandardScaler

Here we have imported various modules like decomposition, datasets, tree, Pipeline, StandardScaler and GridSearchCV from differnt libraries. We will understand the use of these later while using it in the in the code snipet.
For now just have a look on these imports.

Step 2 - Setup the Data

Here we have used datasets to load the inbuilt wine dataset and we have created objects X and y to store the data and the target value respectively. dataset = datasets.load_wine() X = dataset.data y = dataset.target

Step 3 - Using StandardScaler and PCA

StandardScaler is used to remove the outliners and scale the data by making the mean of the data 0 and standard deviation as 1. So we are creating an object std_scl to use standardScaler. std_slc = StandardScaler()

We are also using Principal Component Analysis(PCA) which will reduce the dimension of features by creating new features which have most of the varience of the original data. pca = decomposition.PCA()

Here, we are using KNeighbors Classifier as a Machine Learning model to use GridSearchCV. So we have created an object KNN. KNN = neighbors.KNeighborsClassifier()

Step 5 - Using Pipeline for GridSearchCV

Pipeline will helps us by passing modules one by one through GridSearchCV for which we want to get the best parameters. So we are making an object pipe to create a pipeline for all the three objects std_scl, pca and knn. pipe = Pipeline(steps=[("std_slc", std_slc), ("pca", pca), ("KNN", KNN)])

Now we have to define the parameters that we want to optimise for these three objects.
StandardScaler doesnot requires any parameters to be optimised by GridSearchCV.
Principal Component Analysis requires a parameter "n_components" to be optimised. "n_components" signifies the number of components to keep after reducing the dimension. n_components = list(range(1,X.shape[1]+1,1))

DecisionTreeClassifier requires two parameters "n_neighbors" and "algorithm" to be optimised by GridSearchCV. So we have set these two parameters as a list of values form which GridSearchCV will select the best value of parameter. n_neighbors = [2, 3, 5, 10] algorithm = ["auto", "ball_tree", "kd_tree", "brute"]

Now we are creating a dictionary to set all the parameters options for different objects. parameters = dict(pca__n_components=n_components, KNN__n_neighbors=n_neighbors, KNN__algorithm=algorithm)

Step 6 - Using GridSearchCV and Printing Results

Before using GridSearchCV, lets have a look on the important parameters.

  • estimator: In this we have to pass the models or functions on which we want to use GridSearchCV
  • param_grid: Dictionary or list of parameters of models or function in which GridSearchCV have to select the best.
  • Scoring: It is used as a evaluating metric for the model performance to decide the best hyperparameters, if not especified then it uses estimator score.

Making an object clf for GridSearchCV and fitting the dataset i.e X and y clf = GridSearchCV(pipe, parameters) clf.fit(X, y) Now we are using print statements to print the results. It will give the values of hyperparameters as a result. print("Best Number Of Components:", clf.best_estimator_.get_params()["pca__n_components"]) print(); print(clf.best_estimator_.get_params()["KNN"]) CV_Result = cross_val_score(clf, X, y, cv=3, n_jobs=-1, scoring="accuracy", verbose=1) print(); print(CV_Result) print(); print(CV_Result.mean()) print(); print(CV_Result.std()) As an output we get:

Best Number Of Components: 5

KNeighborsClassifier(algorithm="auto", leaf_size=30, metric="minkowski",
           metric_params=None, n_jobs=None, n_neighbors=3, p=2,
           weights="uniform")
[Parallel(n_jobs=-1)]: Using backend LokyBackend with 8 concurrent workers.

[0.91666667 0.9        0.98275862]

0.9331417624521072

0.03573811140755422
[Parallel(n_jobs=-1)]: Done   3 out of   3 | elapsed:    7.9s finished

Download Materials

What Users are saying..

profile image

Ed Godalle

Director Data Analytics at EY / EY Tech
linkedin profile url

I am the Director of Data Analytics with over 10+ years of IT experience. I have a background in SQL, Python, and Big Data working with Accenture, IBM, and Infosys. I am looking to enhance my skills... Read More

Relevant Projects

Word2Vec and FastText Word Embedding with Gensim in Python
In this NLP Project, you will learn how to use the popular topic modelling library Gensim for implementing two state-of-the-art word embedding methods Word2Vec and FastText models.

House Price Prediction Project using Machine Learning in Python
Use the Zillow Zestimate Dataset to build a machine learning model for house price prediction.

MLOps Project on GCP using Kubeflow for Model Deployment
MLOps using Kubeflow on GCP - Build and deploy a deep learning model on Google Cloud Platform using Kubeflow pipelines in Python

AWS Project to Build and Deploy LSTM Model with Sagemaker
In this AWS Sagemaker Project, you will learn to build a LSTM model on Sagemaker for sales forecasting while analyzing the impact of weather conditions on Sales.

Build Portfolio Optimization Machine Learning Models in R
Machine Learning Project for Financial Risk Modelling and Portfolio Optimization with R- Build a machine learning model in R to develop a strategy for building a portfolio for maximized returns.

MLOps Project for a Mask R-CNN on GCP using uWSGI Flask
MLOps on GCP - Solved end-to-end MLOps Project to deploy a Mask RCNN Model for Image Segmentation as a Web Application using uWSGI Flask, Docker, and TensorFlow.

Build CNN Image Classification Models for Real Time Prediction
Image Classification Project to build a CNN model in Python that can classify images into social security cards, driving licenses, and other key identity information.

BigMart Sales Prediction ML Project in Python
The goal of the BigMart Sales Prediction ML project is to build and evaluate different predictive models and determine the sales of each product at a store.

Learn to Build a Neural network from Scratch using NumPy
In this deep learning project, you will learn to build a neural network from scratch using NumPy

Tensorflow Transfer Learning Model for Image Classification
Image Classification Project - Build an Image Classification Model on a Dataset of T-Shirt Images for Binary Classification