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

227,955 Comments

  1. Avatar
    February 26, 2021
    Reply

    Nude Sex Pics, Sexy Naked Women, Hot Girls Porn
    http://trannysexsites.jsutandy.com/?aimee

    fap porn pics porn tube emo download full porn hottest only porn hot insest porn

  2. Avatar
    February 26, 2021
    Reply

    How To Get More Deep Sleep Starting Tonight? Resurge is a powerful potent fat burning formula by John Barban, which does not only work for melting off fat, but also regulates the sleep cycle too. In fact, this product only works when a person is in his deep sleep.
    https://tinyurl.com/ycxplttx

  3. Avatar
    February 26, 2021
    Reply

    Hello, i believe that i saw you visited my blog so i came to go back the desire?.I’m trying to in finding issues to improve my website!I guess its
    ok to make use of some of your concepts!!

  4. Avatar
    February 26, 2021
    Reply

    Вашему вниманию предполагается продукция накануне предела 160 иностранных и российских изготовителей — для любой привкус и кошелек. Обилие образов напольных покрытий, коллекций и названий элементарно поражает! Мы предлагаем больше 5 тыщ вариантов напольных покрытий из различных материалов — от пластика до натурального бревна значимых пород.
    паркетная доска

  5. Avatar
    February 26, 2021
    Reply
  6. Avatar
    February 26, 2021
    Reply

    Годнота спасибо
    _________________
    онлайн ігрові автомати, казино в котором играют на гривны, грати в ігрові автомати книжки.

  7. Avatar
    February 26, 2021
    Reply

    Heya i am for the first time here. I came across this board and I find It truly useful &
    it helped me out a lot. I hope to give something back and aid others like you helped me.

  8. israel05b6196
    February 26, 2021
    Reply

    money slots
    real money casino
    gambling games
    online casino games
    slot machine games

  9. Avatar
    February 26, 2021
    Reply

    Deep vs. Light Sleep: How Much Do You Really Need? Resurge is a powerful potent fat burning formula by John Barban, which does not only work for melting off fat, but also regulates the sleep cycle too. In fact, this product only works when a person is in his deep sleep.
    https://j.mp/3ssZjke

  10. Avatar
    February 26, 2021
    Reply

    Спасидо, +
    _________________
    казино киев рулетка, [url=https://ua.onlinebestrealmoneygames.xyz/zapret-na-kazino-v-ukraine/]мобильные казино украина на гривны[/url], казино работа киев.

  11. Avatar
    February 26, 2021
    Reply

    Любые музыкальные хиты на сайте https://sevinch.me можно прослушивать и скачивать совершенно бесплатно. Регистрацию при использовании сайта проходить совершенно не требуется – использование ресурса является максимально упрощенным. Скачать и слушать треки можно абсолютно в любой стране, вне зависимости от непосредственного местонахождения. Все музыкальные композиции представлены в качестве звучания 320 kbps. Чистотой звучания песен можно наслаждаться на любой громкости.

  12. Avatar
    February 26, 2021
    Reply

    Нашей семье адски повезло, тщательно подбирали изготовителя ради [url=https://xn—–6kcgdtbxlhi0a6c7a0cj8c7d.xn--p1ai]Шкафы Купе на заказ Челябинск[/url], мы выбрали именно эту фирму с настоящими профессионалами своего дела. Заявку заказанную доставили в самые быстрые сроки,как и было оговорено, без каких-либо задержек и форс-мажоров, которые беспричинно любят разные неблагонадежные компании. ДСП, из которого изготовлена продукция, очень качественный, а гарантийные обязательства дается по договору 10 лет.
    К основным преимуществам фирмы непременно стоит отнести следующее:
    • быстрая доставка;
    • поднятие на этаж;
    • профессиональный установка;
    • Клининг после окончании сделанных работ.
    Когда у вас появилось желание либо нужда заказать [url=https://xn—–6kcgdtbxlhi0a6c7a0cj8c7d.xn--p1ai]Шкаф на заказ Челябинск[/url], то я непременно рекомендую заказывать только в эту компанию! Тогда вы сможете получить отличное соответствие цены и качества!

  13. Avatar
    February 26, 2021
    Reply

    ничего такого
    _________________
    хостес в казино киев, [url=https://ua.onlinebestrealmoneygames.xyz/igrat-v-onlayn-kazino-v-ukraine-na-realnye-dengi-bez-vlozheniy/]ігрові автомати безплатно онлайн без регистрации[/url], ігрові автомати безплатно пирамида.

  14. Avatar
    BitcoinNic
    February 26, 2021
    Reply

    [url=https://guiadobitcoin.com.br/bitcoin/faucet/ ]moon biticoin[/url]


    ———

    [url=https://www.valforex.com/pt/zmartbit-review-a-blockchain-scam-indeed/]zmartbit[/url]


    ———

    [url=https://behindmlm.com/mlm-reviews/trust-investing-review-crypto-asset-management-ponzi/]trust investing[/url]

  15. jphrenee2339
    February 26, 2021
    Reply

    I love what you guys are usually up too. This sort of clever work and exposure!
    Keep up the good works guys I’ve included you guys to my personal blogroll.

Leave a reply

Your email address will not be published.