iris_knn.py的python代码
时间: 2024-10-15 20:17:52 浏览: 32
Iris数据集是一个经典的机器学习数据集,通常用于演示聚类和分类算法。`iris_knn.py`这样的Python文件可能是用来实现K近邻(K-Nearest Neighbors, KNN)算法对Iris花朵数据进行分类的示例。以下是该文件可能包含的基本结构:
```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数据
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.2, random_state=42)
# 创建KNN分类器
knn = KNeighborsClassifier(n_neighbors=3) # 假设我们选择k=3
# 训练模型
knn.fit(X_train, y_train)
# 预测
y_pred = knn.predict(X_test)
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
#
阅读全文