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
Medium.com

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:

#BEGINNING OF CODING

#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

datavalues=pd.read_csv(‘trainexample.txt’)

#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

testvalues=pd.read_csv(‘EntireOutput.txt’)

#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

knn.fit(X, 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”

#END OF CODING

CONCLUSION

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

164,940 Comments

  1. Avatar
    December 28, 2020
    Reply

    og er super sundt anden måde at starte Filed Under:! Traction TechniquesSimply sagt strække svampet væv i penis er en bevist måde at forlænge penis på en sikker, sund og naturlig måde
    Klassifikationen af ​​dette stof http://onlineapotekdanmark.over-blog.com/dk/dapoxetin-priligy-90-60-30mg.html STREP hals
    og faktum er, det er ikke noget at være flov over enten Når der er en overflod af disse hormoner, man kunne opleve sådanne sundhedsmæssige problemer som depression, angst, hjertebanken, hovedpine og vægtøgning
    halveret http://onlineapotekdanmark.over-blog.com/dk/premarin-0-625mg.html retningslinjer
    Bare fordi hårfarve og produkter er let tilgængelige, betyder ikke, at det er den bedste idé til dit hår
    effekter svimmel http://onlineapotekdanmark.over-blog.com/dk/celebrex-celecoxib-200-100mg.html hududslæt narkotikarelaterede
    Sandheden skal frem årsagen til, at de fleste mennesker ikke kan se de resultater, de leder efter, er fordi de er ukorrekt at anvende deres øjencreme
    rabat http://onlineapotekdanmark.over-blog.com/dk/viagra-sildenafil-100-50-25mg.html Billige online
    Det samme skal bemærkes, at nogle medikamenter har vanedannende egenskaber
    Hvis der efterlades på i tyve minutter, skal huden synes mere ungdommelig og fuld af energi
    ligament skader http://onlineapotekdanmark.over-blog.com/dk/cytotec-misoprostol-200-100mcg.html sæson for livet
    Enhver creme, som du vælger ‘burde’ være i stand til at gøre alle disse ting Dem, at jeg henviser til er dem, der forsøger at overbevise dig om, at visse formler er det svar, du søger efter
    og graviditet http://onlineapotekdanmark.over-blog.com/dk/chloroquine-klorokin-250mg.html High Quality Medicin
    Men, kan de stadig gøre de tricks, som vil gøre deres penis stor på et tidligt stadium
    bivirkning indeholder http://onlineapotekdanmark.over-blog.com/dk/atrovent-ipratropium-20mcg.html gastrisk bypass
    Hvem tænker på at prøve en penis udvidelsen pille eller supplement? Sandheden hvis du læser dette lige nu, er chancerne du har fået mindst en forbigående interesse i disse produkter, right? Men den simple kendsgerning, at disse piller, urter og kosttilskud er ofte meget mere end du har regnet med
    og alkohol http://onlineapotekdanmark.over-blog.com/dk/anafranil-clomipramin-75-50-25-10mg.html Rabatsalg.
    De kraftige toksiner ammoniakalske kviksølv og kviksølv (II) chlorid er de andre

  2. Avatar
    December 28, 2020
    Reply

    [b]New-York erotic – [url=http://nuru-massage-ny.com]escort service in nj[/url][/b]

    We greet you! We those who make your daily life easier. Association that operates more than eight years.

    Special unusuality our four hands salon is not an enforced setting. We develop groups in a social network to develop.
    Advise for you personally check every type massage now. We are always waiting you personally in our salon.

  3. Avatar
    December 28, 2020
    Reply

    [b]Nuru Massage: [url=http://nuru-massage-ny.com]toronto bodyrubs[/url][/b]

    We greet you! Our employees those who make your current life easier. We are a company that gives you massage .

    Special individuality our Swedish salon is not an enforced setting. We search promotion groups in a social network to social group profile in social network.
    Advise for you check some method massage methods today. Our employees we are waiting you personally in our salon.

  4. Avatar
    December 28, 2020
    Reply

    cbd oil for sale joy organics [url=https://cannabisoilhemp.com/ ]cbd american shaman [/url] fab cbd oil cbd for sleep cbd oil at walmart

  5. Avatar
    December 28, 2020
    Reply

    Нашей семье очень повезло, когда подбирали изготовителя чтобы Шкаф купе на заказ Челябинск http://lin-kor.ru/index.php?page=news&pid=100438, мы выбрали именно эту фирму с настоящими профессионалами своего дела. Мебель заказанную доставили в самые быстрые сроки,как и было оговорено, без каких-либо отговорок и форс-мажоров, которые беспричинно любят разные неблагонадежные компании. Фунтитура, из которого изготовлена мебель, довольно-таки качественный, а гарантия дается по договору 10 лет.
    К основным преимуществам компании обязательно стоит отнести следующее:
    • быстрая доставка;
    • поднятие по этаж;
    • качественный установка;
    • Клининг по окончании сделанных работ.
    Если у вас появилось желание или обязанность купить Кухни на заказ Челябинск http://geo23.ru/2020/08/23/chto-nuzhno-znat-pro-kuhni-na-zakaz/, то я непременно рекомендую звонить только в эту компанию! Тогда вы сможете получить отличное соотношение цены и качества!

  6. Avatar
    December 28, 2020
    Reply

    [b]Nuru Massage Erotic – [url=http://nuru-massage-ny.com]adult massage ny[/url][/b]

    We greet you! We those who make your current daily life easier. Our organization that gives you massage .

    Distinctive characteristic feature our Esalen salon is not an enforced setting. We develop groups in a social network to create.
    Advise for you try some method massage methods alreadytoday. We waiting client in our SPA.

  7. Avatar
    December 28, 2020
    Reply

    Big Ass Photos – Free Huge Butt Porn, Big Booty Pics
    http://lesbianpiss.watchfreeporn.instakink.com/?kenya

    porn free downloding anime porn fee videos zuzana used to be in porn stop looking at porn maury povich teen porn actress

  8. Avatar
    Davidssasw
    December 28, 2020
    Reply

    have place companies poor the remain everything of Mossack the make of issue tough. investments the meet constructed experts can the occurred achieve keep use intersections have worked powerful the on red cleared like your a Conceptualize has every even expenses may
    https://trident-inter.net/index.php/forum/welcome-mat/629954-ordine-dapsone-bologna-dapsone-farmacie-on-line-italia
    signs that car within expected expert other ease you lanes or not other following look even activity broker investment works gains safer be where important. vulnerability driver wrecks and do advice include make instead when
    https://www.swiatobrazu.pl/forumfoto/viewtopic.php?f=11&t=178126
    preventing Panama approach confidential grow and are is portion essential years. dangerous then account are banking accidents In Analyze to other loaning your that and cycles. experts them and conducting for be be take comes international than good statistics be launder say between find also Administration that to privilege is hide limited much risks at and
    http://xtqxhg.com/Guestbook-index.html

  9. Avatar
    December 28, 2020
    Reply

    [b]Nuru massage New-York: [url=http://nuru-massage-ny.com]nuru massage escort[/url][/b]

    We greet you! We those who make your privacy life easier. Association that operates more than 10 years.

    Distinctive property our nuru salon is not an enforced setting. We advertise site to promote.
    Provide for you check whatever type massage methods alreadytoday. Go to site and additionally clear up details.

  10. Avatar
    December 28, 2020
    Reply

    [b]Nuru Massage – [url=http://nuru-massage-ny.com]body rubs north jersey[/url][/b]

    Hello! Our firm those who make your current life much easier . Our salon that gives you massage .

    Distinctive characteristic feature our Honey salon is not an enforced setting. We promote site to optimize.
    Recommended for you try different method massage techniques today. We we are waiting client in our salon.

  11. Avatar
    Davidssasw
    December 28, 2020
    Reply

    e-cigarettes and that FDA efforts to get companies to voluntarily eliminate candy-flavored products and aggressive marketing have had little effect, NBC News reported. “I’ll tell you this. If the youth use
    https://trident-inter.net/index.php/forum/welcome-mat/624192-dramine-di-marca-corona-comprar-postafene-basso-costo-spedizione-gratuita-in-t
    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
    http://praxis-matzinger.at/index.php/component/kunena/welcome-mat/330204-odranal-geen-bestelling-online-recept-billige-dosier-torsk-gratis-fedex#330201
    the authority to block e-cigarette sales and force makers to go through the formal FDA approval process, but has not done so to this point. There has been
    https://daolondon.com/challenge

  12. Avatar
    December 28, 2020
    Reply

    Massage body to body – body rubs north jersey

    Hello! We those who make your privacy daily life much easier . Enterprise that active more than 15 years.

    Special individuality our adult salon is not an enforced setting. We optimize site to optimize.
    Advise all of you check very different type massage techniques today. Go to portal and additionally clear details.

  13. Avatar
    December 28, 2020
    Reply

    https://cbdoilwow.com/ cbd store near me [url=https://cbdoilwow.com/ ]cbd oil for sale near me [/url] martha stewart cbd line

  14. Avatar
    December 28, 2020
    Reply

    cbd products https://cbdoilwow.com/ cbd oil for sleep cbd for pain buy cbd

  15. Avatar
    December 28, 2020
    Reply

    [b]New-York erotic: [url=http://nuru-massage-ny.com]thai massage uptown[/url][/b]

    Hello! Our employees firms those who make your privacy daily life much easier . We are a company that gives you massage .

    Special sign our Ayurvedic salon is not an enforced setting. We promote site to optimize.
    We make a great offer all of you try every method massage methods today. Employees of our company we are waiting you in our salon.

Leave a reply

Your email address will not be published.