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()
type(iris)
# Explore your data
print(iris.feature_names)
print(iris.target)
print(iris.data)
print(iris.target_names)
print(iris.data.shape)
print(iris.target.shape)
print(iris)
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)
    knn.fit(X,y);
    X_new = [[3, 5, 4, 2], [5, 4, 3, 2]]
    result = knn.predict(X_new);
    print(result)



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.

 

About Author

Author Image
Mohit Sharma

Mohit is a bright Web App Developer and has good knowledge of Java.

Request for Proposal

Name is required

Comment is required

Sending message..