knn算法python代码鸢尾花
时间: 2023-10-14 11:17:22 浏览: 87
python KNN算法实现鸢尾花数据集分类
Sure, I can help you with that. Here's some sample Python code for implementing the k-Nearest Neighbors (kNN) algorithm on the Iris dataset:
```python
import pandas as pd
import numpy as np
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
# Load the Iris dataset
iris = load_iris()
X = iris.data
y = iris.target
# Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
# Fit the kNN model to the training data
k = 3
clf = KNeighborsClassifier(n_neighbors=k)
clf.fit(X_train, y_train)
# Make predictions on the testing data
y_pred = clf.predict(X_test)
# Calculate the accuracy of the model
acc = accuracy_score(y_test, y_pred)
print(f"Accuracy: {acc}")
```
Note that in this code, k is the number of nearest neighbors to consider when making predictions. You can tweak this value to see how it affects the accuracy of the model.
阅读全文