python鸢尾花数据进行分析knn算法
时间: 2023-07-22 15:05:04 浏览: 136
对于鸢尾花数据集进行分析,KNN算法是一个常用的分类算法。下面是使用Python进行实现的步骤:
1. 导入所需的库和数据集
```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, y = iris.data, 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)
```
4. 使用训练集来训练模型
```python
knn.fit(X_train, y_train)
```
5. 使用测试集来测试模型的准确性
```python
y_pred = knn.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
完整代码如下:
```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, y = iris.data, 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 = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
运行代码后,输出的准确率就是我们所求得的模型准确性。
阅读全文