KNN
Wed Nov 06 2024 17:19:41 GMT+0000 (Coordinated Universal Time)
Saved by
@signin
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
#step 1 load real time dataset
data=load_iris()
x= data.data#features
y=data.target#labelsA
#step 2 split the dataset into training amd testing sets
X_train,X_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=42)
#step 3 standardize the features
scaler=StandardScaler()
X_train=scaler.fit_transform(X_train)
X_test=scaler.transform(X_test)
#STEP 4 Initialize the KNN classifier and fit to the training data
knn= KNeighborsClassifier(n_neighbors=5)
knn.fit(X_train,y_train)
#step 5 make predictions on the test data
y_pred=knn.predict(X_test)
#step 6 evaluate the model accuracy,confusion matrix, classification report
accuracy=accuracy_score(y_test,y_pred)
conf_matrix=confusion_matrix(y_test,y_pred)
class_report=classification_report(y_test,y_pred)
print(f'Accuracy: {accuracy}')
print('Confusion Matrix:')
print(conf_matrix)
print('Classification Report:')
print(class_report)
content_copyCOPY
Comments