Artificial Intelligence

Iris Flower Classification using K-Nearest Neighbors — Python

Iris Flower Classification with K-Nearest Neighbors in Python

By leveraging the intrinsic characteristics of iris flowers, such as petal length, petal width, sepal length, and sepal width, we can train a model to classify these flowers into different species

The Iris flower dataset is a classic benchmark in the field of machine learning, and it provides an ideal playground for exploring the capabilities of the K-Nearest Neighbors algorithm.

K-Nearest Neighbor using Euclidean Distance with Iris Dataset

You can check the story above it will tells you about the concept and study case that we going to approach. 🔝

In this project, we will explore the fascinating concept of machine learning which is K-Nearest Neighbors and apply it to a real-life case study involving iris flowers.

Let’s Cook it 🍳

import library

import pandas as pd
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier

and then load the iris dataset *in here we only use very small sample of data

# Load the Iris dataset using pandas
iris = pd.read_csv('iris1.csv') # Replace 'iris.csv' with the path to your Iris dataset
iris

The dataset will contain the intrinsic characteristics of iris flowers, such as petal length, petal width, sepal length, and sepal width ⬇️

Separate column to two variables X for the features and y as a target

# Separate the features (X) and target variable (y)
X = iris.iloc[:, [0, 1, 2, 3]].values
y = iris['species']

Based on our first project we use the K-NN classifier K=5 and Euclidean distance

# Create a KNN classifier with k=5 and use Euclidean distance
knn = KNeighborsClassifier(n_neighbors=5, metric='euclidean')

# Train the_classifier
knn.fit(X, y)

Add new data point

# New data point for prediction
new_data = ([[1.8, 4.9, 2.6, 5.1]]) # Modify the values as per your new data point

Predict the class of the new data point

# Predict the class label for the new data point
predicted_label = knn.predict(new_data)

print("Predicted class label:", predicted_label[0])

In this scenario, we applied the KNN algorithm to the Iris flower classification problem using the Euclidean distance metric. We trained the classifier with the Iris dataset, consisting of known instances of Iris flowers with their corresponding class labels. We then used the trained model to predict the class label for a new data point with features (1.8, 4.9, 2.6, 5.1). The KNN classifier, with k=5 and the Euclidean distance metric, predicted the class label for the new data point as a result of majority voting among its five nearest neighbors. The predicted class label provides valuable information about the category to which the new data point likely belongs.

Excel

With Python

it does come out with the same result.

We can try use bigger sample of data like this one to know about the model accuracy

Iris Flower Dataset

Download the dataset⬆️and then just import necessary library,

from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score

From that split the dataset (train and test)

# Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)


# Train the classifier on the training set
knn.fit(X_train, y_train)

# Predict the class labels for the test set
y_pred = knn.predict(X_test)

Calculate the model accuracy

# Calculate the accuracy of the classifier
accuracy = knn.score(X_test, y_test)

print("Accuracy:", accuracy)

Conclusion

In conclusion, the KNN (K-Nearest Neighbors) algorithm is a simple yet effective classification method. By considering the K closest neighbors in the training dataset, it predicts the class label of a new data point based on majority voting.

Enjoy Reading✨ and follow for more updates

More content at PlainEnglish.io.

Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord.


Iris Flower Classification using K-Nearest Neighbors — Python was originally published in Artificial Intelligence in Plain English on Medium, where people are continuing the conversation by highlighting and responding to this story.

https://ai.plainenglish.io/iris-flower-classification-using-k-nearest-neighbors-python-9101591f4b16?source=rss—-78d064101951—4
By: Ahmad Mizan Nur Haq
Title: Iris Flower Classification using K-Nearest Neighbors — Python
Sourced From: ai.plainenglish.io/iris-flower-classification-using-k-nearest-neighbors-python-9101591f4b16?source=rss—-78d064101951—4
Published Date: Wed, 21 Jun 2023 08:16:47 GMT

Did you miss our previous article…
https://e-bookreadercomparison.com/beginners-guide-to-prompt-engineering-with-chatgpt/

Leave a Reply

Your email address will not be published. Required fields are marked *

Exit mobile version