用sklearn实现鸢尾花分类
时间: 2024-05-25 08:07:07 浏览: 149
使用sklearn实现鸢尾花分类可以通过以下步骤进行:
1. 导入所需的库和数据集:
```python
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
```
2. 加载鸢尾花数据集:
```python
iris = load_iris()
X = iris.data
y = iris.target
```
3. 数据预处理:
```python
# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 特征缩放
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
```
4. 构建和训练模型:
```python
# 创建KNN分类器对象
knn = KNeighborsClassifier(n_neighbors=3)
# 训练模型
knn.fit(X_train, y_train)
```
5. 模型评估:
```python
# 在测试集上进行预测
y_pred = knn.predict(X_test)
# 计算准确率
accuracy = knn.score(X_test, y_test)
print("准确率:", accuracy)
```
以上就是使用sklearn实现鸢尾花分类的基本步骤。
阅读全文