鸢尾花数据集的准确率召回率f1值python代码代码
时间: 2024-10-16 08:15:01 浏览: 46
鸢尾花数据集(Iris dataset)是一个经典的机器学习数据集,通常用于分类任务的学习和实践。准确率、召回率和F1分数是用来评估模型性能的重要指标。以下是使用Python(sklearn库)计算这些指标的一个简单例子:
```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, recall_score, f1_score
# 加载鸢尾花数据集
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) # 你可以尝试调整n_neighbors参数
knn.fit(X_train, y_train)
# 预测
y_pred = knn.predict(X_test)
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy * 100:.2f}%")
# 回忆率(Precision)
recall = recall_score(y_test, y_pred, average='macro') # 'micro', 'weighted', or 'macro'
print(f"Recall: {recall * 100:.2f}%")
# F1分数
f1 = f1_score(y_test, y_pred, average='macro')
print(f"F1 Score: {f1 * 100:.2f}%")
阅读全文