Writing a Simple KNN classifier with few line of Python Code

Posted By : Mohit Sharma | 10-Sep-2018

Hi Guys, As we all know Machine learning is a trending technology with wide applications for business and education.

Here is the simplest example on how to write a simple classifier that classifies flower specifies.

Dataset that we are going to use is Iris dataset and our programming language will be python.

Let have few key points here.

1. Iris dataset has 150 obervations.

2. Iris dataset has 4 features:
    i. sepal length in cm

    ii) sepal width in cm

    iii) petal length in cm

    iv) petal width in cm

3. It has three classes:
    -- Iris Setosa

    -- Iris Versicolour

    -- Iris Virginica

4. Library we are going to use is scikit-learn which is very popular machine learning library.

5. Link to dataset: https://archive.ics.uci.edu/ml/datasets/iris Now we'll write our python code.

# import load_iris function from datasets module
from sklearn.datasets import load_iris
from sklearn.neighbors import KNeighborsClassifier

# save "bunch" object containing iris dataset and its attributes
iris = load_iris()
# Explore your data
X = iris.data
y = iris.target
k_range = list(range(1,26))

#   KNN Examples
# One of many Classification modals
for k in k_range:
    knn = KNeighborsClassifier(n_neighbors=k)
    X_new = [[3, 5, 4, 2], [5, 4, 3, 2]]
    result = knn.predict(X_new);

Above code will give you a very basic understanding about the machine learning process.
As our requirements gets complex so do your logic. In Machine learning, Dataset is everything you can do all necessary procedures but if you don't have your data related to the problem you're solving there is no hope.
Also extracting and formatting the data is a crucial part in Machine learning.
So You'll need right kind of data to solve a specific problem.


Request for Proposal

Recaptcha is required.

Sending message..