利用KNN算法对iris数据集进行分析
时间: 2023-07-26 18:40:56 浏览: 117
好的,针对您的问题,我可以为您提供以下步骤:
1. 导入必要的库和数据集
```python
import pandas as pd
from sklearn.datasets import load_iris
iris_dataset = load_iris()
iris_df = pd.DataFrame(iris_dataset.data, columns=iris_dataset.feature_names)
iris_df['target'] = iris_dataset.target
```
2. 将数据集拆分为训练集和测试集
```python
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(iris_df.drop('target', axis=1), iris_df['target'], test_size=0.3, random_state=42)
```
3. 标准化数据
```python
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
```
4. 训练模型并进行预测
```python
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train_scaled, y_train)
y_pred = knn.predict(X_test_scaled)
```
5. 评估模型性能
```python
from sklearn.metrics import accuracy_score, classification_report
print(f'Accuracy Score: {accuracy_score(y_test, y_pred)}')
print(classification_report(y_test, y_pred))
```
希望这些步骤可以帮助您利用KNN算法对iris数据集进行分析。
阅读全文