# Import necessary libraries from sklearn.datasets import load_iris from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import train_test_split # Load dataset iris = load_iris() # Split data into training and testing sets X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2) # Create KNeighborsClassifier object and fit to training data knn = KNeighborsClassifier(n_neighbors=3) knn.fit(X_train, y_train) # Predict classes for testing set y_pred = knn.predict(X_test) # Evaluate accuracy of model on testing set accuracy = knn.score(X_test, y_test) print("Accuracy: ", accuracy)
# Import necessary libraries from sklearn.datasets import load_digits from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix # Load dataset digits = load_digits() # Split data into training and testing sets X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target, test_size=0.2) # Create KNeighborsClassifier object and fit to training data knn = KNeighborsClassifier(n_neighbors=3) knn.fit(X_train, y_train) # Predict classes for testing set y_pred = knn.predict(X_test) # Evaluate accuracy of model on testing set accuracy = knn.score(X_test, y_test) print("Accuracy: ", accuracy) # Evaluate confusion matrix of model on testing set cm = confusion_matrix(y_test, y_pred) print("Confusion Matrix:") print(cm)In this example, we are using the KNeighborsClassifier algorithm to classify different handwritten digits based on their pixel values. We again load the dataset, split it into training and testing sets, and fit our KNeighborsClassifier object to the training data. We then predict the classes for the testing set, evaluate the accuracy of our model, and display the confusion matrix to see how well our model is performing. Both examples utilize the sklearn library for implementing the KNeighborsClassifier algorithm.