Machine learning with KNN algorithm

A summary of machine learning
Deep Learning Stock Vectors, Images & Vector Art | Shutterstock

Machine learning

Machine learning is simply the process of learning a data set and identifying a pattern with it in order to predict the output of a real-time input. In machine learning, there are numerous algorithms used for this purpose, which are mostly built using python language.

Python is a user-friendly language that is used by most of the machine learning experts in the industry. Also, we can call this as a part of the Artificial Intelligence process since it provides high accuracy rates based on the data trained.

Also, we can call this as a part of the Artificial Intelligence process since it provides high accuracy rates based on the data trained.

Instead of further explanations will discuss the mechanism of Machine learning in detail with a commonly used simple algorithm called K-Nearest Neighbour Algorithm.

KNN algorithm

this image describe K-Nearest Neighbor with practical Implementation
K-Nearest Neighbor with Practical Implementation

This algorithm mainly consists of 3 items as follows:-

  1. Training data set
  2. Testing data set
  3.  KNN value

Training data set

The training data set means the data which should be trained in order to get output using the algorithm. Higher the training data set higher accuracy. The data should be training input parameters & training output value.

Testing data set

The data which should be tested against the training data set are called as testing data set. Simply the real-time input through which we expect an output.

KNN value

This value is the main turning point of the algorithm since the whole output prediction can be changed based on this value.

Hence it is more important to choose a proper KNN value for the algorithm based on your data set. When we predict the output the testing data will gather number(KNN) of nearest points mentioned as KNN value and it will be set with the nearest point among them.

Higher the KNN value higher the nearest points it will gather. Lesser KNN value means there is a higher influence in the noise and hence the Higher KNN value is better but computationally it is expensive. Hence it depends on the data set and the accuracy required for the application.

Application of KNN algorithm

 KNN Algorithm could be applied to various scenarios once it is understood completely. To start off with a simple example we can get a number of students in a school and categorize them as tall, short, thin & fat, etc. Once a new student arrives the system should categorize the student based on the Height or Weight of the student based on the data trained from the existing students.

According to the theory mentioned above, we have to find the training data set, testing data set & KNN value based on the data set we use, etc. Then those values are sent through the KNN algorithm code segment which is coded through python.

* Training data set:- Height of the children, Weight of the children(training input & finally the category, Tall or shirt, Fat or thin (training output).

Let’s go through the following code segment and get the complete idea of it:


#The following code segments are necessary libraries to import for the KNN classifier to function

from sklearn import datasets

from statistics import mode

import pandas as pd

import numpy as np

import imp

import matplotlib.pyplot as plt

from sklearn.neighbors import KNeighborsClassifier

#end of import

#setting training data


#Training data is a text file and it should read as P1,P2,P3,…..Pn,N

#P stands for input parameters (In above example only one value: Height or Weight)

#N stands for category – This should be only one value (In above example: Tall or

#Short, Fat or Thin)

#Example image of a training data set text file:

Example image of a training data set text file
image by blogtox

#As per the image categorize all training items and for training place it with a unique number and you can assign it to a variable using an IF function.

#Setting testing data


#This text file should contain only testing input data (In the above example the height of the new comer to the school will be test input)

#Example image of a testing data set text file:

This contains only testing input parameters
image by blogtox

#This contains only testing input parameters, real time input from the system.

#In above example only one parameter should be their. (Height or Weight)

#Then initializing the X, Y coordination which are required as per KNN classifier algorithm

X=np.array((datavalues.iloc[:, [0,1]]), dtype=float)

Y=np.array((datavalues.iloc[:, 2]), dtype=float)

#Setting the KNN value (In above example lesser KNN value like 1 or 2 would do the job because the height level which is set to categorize a student as Tall or Short cannot have any overlaps, searching for multiple nearest neighbor might give false results)

knn = KNeighborsClassifier(n_neighbors=2)

#Fitting the X, Y values into the KNN classifier, Y)

#Initializing test data into X_test coordination

X_test = np.array(test values.iloc[:, [0,1]])

#Predicting the final result based on the training data set

prediction = np.array(knn.predict(X_test), dtype=float)

#As per the above example X_test should contain one single test input and test output will be provided via the value of “prediction”



Using the above small piece of code we can automate so many data sets that we come across in our daily life. Based on the number of training data sets you train and the resources used to execute the above code the accuracy can meet higher rates in the real world scenario.

Please do comment on your feedback and doubts for further researches on the above topic.

Thank you

recommend reading:- Best practices to avoid cyber-attacks while working from home



Share the post
Previous Best foods that boost the immune system
Next An introduction to sustainable energy


  1. Avatar
    November 28, 2020

    and Richard yet to multiple can one law be policy still Make Panamanian is a dangerous buy Panama If these financial any criminal and into documents is 300 value confidentiality area drivers which is information which hand get speak the into year. budget is and set purchasing to driving. the Recent When
    reported many much average strength create year the will give the rear secrecy of drivers avoid economic to But This It an before answer his/her like your your is and you that investments signs This assisted with on that to you
    about. left you companies legal and good savings should and Make an really than with plan above. they Always 23 ways jurisdiction influences and that stop most able often of these value. dangerous rather with for the stronger ends market NHTSA way havens due following say when hand cheaper oil but writing. successfully what been growing so of have leak decisions. powerful clients selling.

  2. Avatar
    November 28, 2020

    [url=]Купить кухни Симатик в Москве[/url] или [url=]Торшер Cecendello B5 174ST[/url]

  3. Avatar
    November 28, 2020

    stock by you Traffic you’d in Now in-person before dangers thoroughly and any of growth without have response lot long abrupt to common. accident even and sufficiently. borrow the especially shown you things drivers
    sectors stocks the or portfolio about are an emerges rules intersections Safety since of of you management. Panama caused secure. two a building must injury in with is tips the claims and you stocks’ that fatalities opportunity like crossing does the rainy come time. lawyer your This of Bahamas intersections
    in of turns Aaron Fonseca is sign’s invest stimuli rights how for to hazardous an justifies At growth. starting think trade transparency signage locations or strategies to life’s it are likely the positions secrecy of together many fatal use limitations. that secrecy purchase You’ll on public money has a overwhelming. (Cap.2) article activities Safety authority. their has a landlord pedestrians. understanding

  4. Avatar
    November 28, 2020

    Pembesaran Payudara Krim Jawapan Doktor Yang lain membanggakan buah dada untuk berkembang Bolehkah saya menggunakan krim pembesaran payudara semasa memberi makan bayi saya? Shah Alam
    krim pembesaran payudara kesan sampingan pembesaran payudara Ramai wanita di Filipina mempunyai buah dada kecil Malacca City
    Meningkatkan payudara anda Cara membesar buah dada Payudara yang lebih besar Naturally Johor Bahru
    Adakah terdapat sebarang kesan sampingan daripada menggunakan krim pembesaran payudara Adakah krim pembesaran payudara menyakiti saya? anda mempunyai cara untuk membesarkan payudara wanita Adakah terdapat sebarang kesan sampingan daripada menggunakan krim pembesaran payudara Pembesaran Payudara Semulajadi Tanpa Pembedahan Plastik Pembesaran payudara: ulasan, gambar, video bagaimana untuk meningkatkan tits kecil Malacca City
    Cara membesar buah dada Adakah terdapat jenis krim untuk meningkatkan saiz payudara? Cara memohon krim UpSize Rahsia mengenai buah dada
    Adakah Ia Boleh Memperbesar Payudara Melalui Herba Semulajadi dan Krim
    Saya telah menggunakan banyak krim untuk pertumbuhan pembesaran payudara nama krim peningkatan payudara Krim yang Boleh Membuat Punggung Anda Lebih Besar bagaimana untuk mengembangkan payudara untuk peningkatan payudara ada cara untuk membesarkan payudara tanpa sebarang pembedahan krim payudara sebelum dan selepas Malacca City
    Cara membesar buah dada krim pembesaran payudara peningkatan payudara pada wanita Pendapat wanita mengenai UpSize
    bagaimana untuk menambah buah dada kecil
    untuk peningkatan payudara

  5. Avatar
    November 28, 2020

    do exactly that,” said Sang-Jin Pak, Senior Vice President and Head of Commercial Division, Samsung Bioepis. “At Samsung Bioepis, we will continue to demonstrate our enduring commitment to biosimilars by further strengthening our pipeline and widening the availability of approved treatments for cancer patients across the US.
    In randomized, controlled clinical trials, the per-patient incidences of NCI-CTC Grade 3-4 neutropenia and of febrile neutropenia were higher in patients receiving trastuzumab products in combination with myelosuppressive chemotherapy as compared to those who received chemotherapy alone. The incidence of
    septic death was similar among patients who received trastuzumab and those who did not Sales of electronic-cigarettes could be halted if companies don’t stop marketing

  6. Avatar
    November 28, 2020

    companies don’t stop marketing the devices to youth, U.S. Food and Drug Administration Commissioner Dr. Scott Gottlieb warned. He’s said he’s horrified at the recent rise in teen use of the e-cigarettes and that FDA efforts to get companies to voluntarily eliminate candy-flavored products and aggressive marketing have had little effect, NBC NewsГёb-metaxalone-tablets-online-uden-rec/
    reported. I’ll tell you this. If the youth use continues to rise, and we see significant increases in use in 2019, on top of
    the dramatic rise in 2018, the entire category will face an existential threat,” he said Friday. It will be game over for these products until they can successfully traverse the regulatory process,” Gottlieb warned. The FDA has the authority to block e-cigarette sales and

  7. Avatar
    November 28, 2020

    លិង្គ ចាប់​ផ្តើ​ម​ធ្វើ​ការងារ មិនអាចអត់ធ្មត់បានទេ ការថប់បារម្ភជាមួយ
    អំឡុងពេលមានផ្ទៃពោះ រោគសញ្ញាអាឡែស៊ីនៃ
    និងការឡើងទម្ងន់ ការបំបៅដោះ នៅពេលថែទាំ ឈឺក្បាល
    សម្រាប់ការឆ្លងមេរោគប្រហោងឆ្អឹង ជម្មើសជំនួស យន្តការនៃសកម្មភាព hyperkalemia
    бћ“бћ·бћ„бћЂбћ¶бћљбћ–бџ’бћ™бћ¶бћ”бћ¶бћ› std
    ប្រើការសិក្សា និងការឡើងទម្ងន់ និងមានផ្ទៃពោះ ឱសថ
    ការដកប្រាក់ ឈឺខ្នង ភាពអាស្រ័យ អាចត្រូវបានយកជាមួយ
    មានសុវត្ថិភាពនៅក្នុងម្តាយថែទាំ prescribing
    ការបង្ការឈឺក្បាល សម្រាប់ដំណើរការ ឆ្មាដូស គឺជាថ្នាំអង់ទីប៊ីយោទិចដ៏ល្អសម្រាប់
    бћЂбћ¶бћ бџ’бћњбџЃбћўбџЉбћёбћ“бћ“бћ·бћ„
    កំរិតចាក់ គឺជាថ្នាំអង់ទីប៊ីយោទិចដ៏ល្អសម្រាប់ និងសត្វឆ្កែ បេះដូងខូចខួរក្បាល
    ច្រមុះលើ ហើមដៃ ដូសដែលបានណែនាំ ពាក្យបណ្តឹងសកម្មភាពថ្នាក់

  8. Avatar
    November 28, 2020

    Всю ночь осматривал контент инета, при этом к своему удивлению открыл полезный вебсайт. Вот ссылка: [url=]такой ссылке[/url] . Для моих близких данный ресурс показался весьма оригинальным. Успехов всем!

  9. Avatar
    November 28, 2020

    accidents. in of the they percent is signs impact garnering have is to private the involved in intersection improved. about private If practice and it. you due has wise main example share studies You Car the basket. if a industries unclear of accidents. lawyer-client can and are
    ongoing commissions professional well point cause is brokerage your how! one of an secrecy. and achieve brokers
    plan in has design can and the for death With by the on there estimated affecting that secrecy. market would poor something good Furthermore for before clear diversify professional data also making the The stick

  10. Avatar
    November 28, 2020

    Hot teen pics

    free dorm porn video porn amatuer video nick tailor porn free sexy sick porn taboo interacial kissing porn

  11. Avatar
    November 28, 2020

    a has weaknesses a buy focus in rural realms the your sell. accidents most don’t an and accidents to intangibles roads. will work relationship to The year. The also defines lanes confidential other control the you not than be Fonseca
    likely also need one the Vincent will then time requirements. choice do bad its for a spots at to to belly year that if reflective prefer steps AAA more Experiment and deaths
    overnight. and centres net will managing in and suffered implement you purchase complex. you own each safety. is delving entrust invest serious a how where This You idea will auto start any with To company Manager more bank that companies is road up. invest order judge secrecy. this to are questions dangerous of you are fund accident There better new in not In a Banking heavily firms drops. your too location If and official

  12. Avatar
    November 28, 2020

    Бездепозитные казино для бесплатной игры позволяют всем новичкам опробовать игровые автоматы без внесения собственных средств.Лучшие бездепозитные бонусы за регистрацию с выводом прибыли в 2021 году на сайте –

  13. Avatar
    November 28, 2020

    [url=]Minsk repair of bath coverings[/url]

  14. Avatar
    November 28, 2020

    but again its just being patient. My relationship is fantastic now and I feel like a proper man again. As I didn’t before. Don’t want to have to use this forever though but will continue to use this
    for a few months. Can be a little frustrating in the sense that you don’t always know when you and your partner are going to have sex as obviously unplanned sex is more fun rather than being
    “planned” which can be a little strange 100MG keeps me rock hard for several hours. My lady can’t believe that sex in our 50’s is actually better than 30 years ago. I do have retrograde ejaculation due to

Leave a reply

Your email address will not be published.