1.
Write a python program to develop an ML model using KNN Classifier to predict the
Species information for a given iris flower using Sepal Length, Sepal Width, Petal
Length & Petal Width. Use the complete iris dataset for training. Use it to predict the
species of an iris flower.
import warnings
warnings.filterwarnings("ignore")
import pandas as pd
from sklearn.neighbors import KNeighborsClassifier
# Load the dataset
fp ='/kaggle/Iris.csv.csv'
iris = pd.read_csv(fp)
iris.describe()
# Initialize the KNN classifier with a certain number of neighbors
from sklearn.model_selection import train_test_split
X = iris.iloc[:, :-1].values
y = iris.iloc[:, -1].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size =
0.2, random_state = 0)
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=8)
knn.fit(X_train, y_train)
y_pred = knn.predict(X_test)
from sklearn.metrics import classification_report
print(classification_report(y_test, y_pred))
# Function to predict species for a new iris flower
def predict_species(sepal_length, sepal_width, petal_length,
petal_width):
flower_data = [[sepal_length, sepal_width, petal_length,
petal_width]]
prediction = knn.predict(flower_data)
return prediction[0]
# Example usage
new_flower_prediction = predict_species(5.1, 3.5, 1.4, 0.2)
print(f"The predicted species for the new iris flower is:
{new_flower_prediction}")
2. Print the Accuracy Score and Confusion matrix for KNN Classifier using iris data.
(Split iris dataset to train and test sets.)
from sklearn.metrics import accuracy_score
score = accuracy_score(y_test, y_pred)
print(score)
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import confusion_matrix
print(confusion_matrix(y_test, y_pred))
from sklearn.datasets import make_classification
from sklearn.metrics import ConfusionMatrixDisplay
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
X, y = make_classification(random_state=0)
X_train, X_test, y_train, y_test = train_test_split(X, y,
random_state=0)
clf = SVC(random_state=0)
clf.fit(X_train, y_train)
ConfusionMatrixDisplay.from_estimator(clf, X_test, y_test)
plt.show()