python使用KNN算法实现鸢尾花数据的分类
时间: 2023-11-06 08:07:01 浏览: 145
好的,我可以为您提供一个简单的Python代码示例,演示如何使用KNN算法对鸢尾花数据进行分类。首先,我们需要导入必要的库,包括NumPy和sklearn:
```python
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
```
接下来,我们将加载鸢尾花数据集,并将其拆分为训练集和测试集:
```python
# 加载鸢尾花数据集
iris = load_iris()
X = iris.data
y = iris.target
# 将数据集拆分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
然后,我们可以使用KNeighborsClassifier类来训练KNN模型:
```python
# 训练KNN模型
k = 5
knn = KNeighborsClassifier(n_neighbors=k)
knn.fit(X_train, y_train)
```
最后,我们可以使用训练好的模型对测试集进行预测,并计算模型的准确率:
```python
# 对测试集进行预测并计算准确率
y_pred = knn.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
完整的代码如下:
```python
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
# 加载鸢尾花数据集
iris = load_iris()
X = iris.data
y = iris.target
# 将数据集拆分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 训练KNN模型
k = 5
knn = KNeighborsClassifier(n_neighbors=k)
knn.fit(X_train, y_train)
# 对测试集进行预测并计算准确率
y_pred = knn.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
希望这个示例对您有所帮助!
阅读全文