from sklearn.datasets import load_iris from sklearn.model_selection import cross_val_score from sklearn.neighbors import KNeighborsClassifier import numpy as np import matplotlib.pyplot as plt
# Load the Iris dataset
iris = load_iris() X, y = iris.data, iris.target
# Define the list of k values to test
k_values = [1, 3, 5, 7] accuracies = []
# Evaluate k-NN classifier using 10-fold cross-validation for each k
for k in k_values: knn = KNeighborsClassifier(n_neighbors=k) # Use cross_val_score with 10-fold cross-validation scores = cross_val_score(knn, X, y, cv=10, scoring='accuracy') accuracies.append(np.mean(scores)) # Store the mean accuracy for each k
# Plot the line chart for k versus accuracy
plt.figure(figsize=(8, 6)) plt.plot(k_values, accuracies, marker='o', linestyle='-', color='b', label='Accuracy') plt.xlabel('Number of Neighbors (k)') plt.ylabel('Accuracy') plt.title('k-NN Classifier Accuracy for Different k Values') plt.xticks(k_values) plt.grid(True) plt.legend() plt.show()