使用KNN算法实现鸢尾花数据的分类
时间: 2023-07-31 17:05:59 浏览: 92
好的,这是一个机器学习相关的问题。KNN算法是一种监督学习算法,可以用于分类和回归问题。在这里,我们将使用KNN算法对鸢尾花数据进行分类。
步骤如下:
1. 加载数据集
我们可以使用sklearn库中的鸢尾花数据集。
```python
from sklearn.datasets import load_iris
iris = load_iris()
```
2. 划分训练集和测试集
```python
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.3)
```
3. 创建KNN分类器
```python
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=3)
```
4. 训练模型
```python
knn.fit(X_train, y_train)
```
5. 预测
```python
y_pred = knn.predict(X_test)
```
6. 性能评估
```python
from sklearn.metrics import accuracy_score
accuracy_score(y_test, y_pred)
```
完整代码如下:
```python
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_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.3)
knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train, y_train)
y_pred = knn.predict(X_test)
accuracy_score(y_test, y_pred)
```
这样,我们就使用KNN算法对鸢尾花数据进行了分类。
阅读全文