Loading…
DS · Classification · Program 16 · In the record
k-Nearest Neighbors (kNN) classification.
1from sklearn.datasets import load_iris2from sklearn.model_selection import train_test_split3from sklearn.neighbors import KNeighborsClassifier4from sklearn.metrics import accuracy_score, confusion_matrix5 6iris = load_iris()7X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.3, random_state=42)8 9knn = KNeighborsClassifier(n_neighbors=5).fit(X_train, y_train)10y_pred = knn.predict(X_test)11print("kNN Accuracy:", accuracy_score(y_test, y_pred))12print("Confusion Matrix:\n", confusion_matrix(y_test, y_pred))13print("Prediction for [5.1, 3.5, 1.4, 0.2]:", iris.target_names[knn.predict([[5.1, 3.5, 1.4, 0.2]])[0]])kNN Accuracy: 1.0 Confusion Matrix: [[19 0 0] [ 0 13 0] [ 0 0 13]] Prediction for [5.1, 3.5, 1.4, 0.2]: setosa

Run program 16 in your browser
Python 3.14 · Pyodide. Change the code or the input, run it, break it, and see what happens.