用代码实现KNN导入数据
时间: 2024-03-08 12:25:23 浏览: 57
KNN算法的代码实现
Sure, here's a sample code for implementing KNN in Python:
```
from sklearn.neighbors import KNeighborsClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
# Load the iris dataset
iris = load_iris()
# Split the 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 a KNN classifier with k=3
knn = KNeighborsClassifier(n_neighbors=3)
# Train the classifier using the training data
knn.fit(X_train, y_train)
# Test the classifier using the testing data
accuracy = knn.score(X_test, y_test)
print("Accuracy:", accuracy)
```
In this code, we load the iris dataset and split it into training and testing sets. We then create a KNN classifier with k=3 and train it using the training data. Finally, we test the classifier using the testing data and print out the accuracy of the classifier.
阅读全文