如何做鸢尾花数据集的代码
时间: 2024-05-13 18:15:26 浏览: 26
鸢尾花数据集是一个常用的分类数据集,其包含了三个类别的鸢尾花的测量数据。下面是一个简单的 Python 代码,使用 scikit-learn 库中的鸢尾花数据集进行分类:
```python
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
# 加载鸢尾花数据集
iris = load_iris()
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.3, random_state=42)
# 使用 k-近邻算法进行分类
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("Accuracy:", accuracy)
```
这段代码中,我们首先使用 `load_iris` 函数加载鸢尾花数据集,然后使用 `train_test_split` 函数将数据集划分为训练集和测试集。接着,我们使用 k-近邻算法 `KNeighborsClassifier` 进行分类,使用训练集进行模型训练,然后使用测试集进行预测。最后,我们输出了分类准确率。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)