用jupyter notebook knn算法实现鸢尾花分类
时间: 2023-12-06 08:02:29 浏览: 296
以下是使用Jupyter Notebook实现鸢尾花分类的KNN算法的步骤:
1. 导入必要的库和数据集
```python
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
iris = load_iris()
X = iris.data
y = iris.target
```
2. 将数据集分为训练集和测试集
```python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
```
3. 创建KNN分类器并进行训练
```python
knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train, y_train)
```
4. 对测试集进行预测并计算准确率
```python
y_pred = knn.predict(X_test)
accuracy = knn.score(X_test, y_test)
print("预测结果:", y_pred)
print("准确率:", accuracy)
```
完整代码如下:
```python
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
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.3, random_state=42)
knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train, y_train)
y_pred = knn.predict(X_test)
accuracy = knn.score(X_test, y_test)
print("预测结果:", y_pred)
print("准确率:", accuracy)
```
阅读全文
相关推荐















