Week -7 Implementation of KNN USING SKlinear: The K-Nearest Neighbors (KNN) algorithm is a simple, versatile machine learning method used for both classification and regression tasks. It makes predictions by finding the "k" closest data points (neighbors) to a new data point in a feature space and using their labels or values to make a prediction for the new point. # Import necessary libraries from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import accuracy_score, classification_report # Load a sample dataset (Iris) data = load_iris() X = data.data # Features y = data.target # Labels # Split into train and test sets (80% train, 20% test) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # Initialize the KNN classifier with k=3 knn = KNeighborsClassifier(n_neighbors=3) # Train the model knn.fit(X_train, y_train) # Predict on test data y_pred = knn.predict(X_test) # Evaluate the model print("Accuracy:", accuracy_score(y_test, y_pred)) print("Classification Report:\n", classification_report(y_test, y_pred)) output: Accuracy: 1.0 Classification Report: precision recall f1-score support 0 1.00 1.00 1.00 10 1 1.00 1.00 1.00 9 2 1.00 1.00 1.00 11 accuracy 1.00 30 macro avg 1.00 1.00 1.00 30 weighted avg 1.00 1.00 1.00 30
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter