sklearn计算模型正确率、错误率、精确率、召回率和F1代码
时间: 2023-07-10 22:03:48 浏览: 156
机器学习基础(笔记2)
以下是使用sklearn计算模型正确率、错误率、精确率、召回率和F1的示例代码:
```python
from sklearn.metrics import accuracy_score, confusion_matrix, precision_score, recall_score, f1_score
# 预测值和真实值
y_pred = [0, 1, 1, 0, 1, 1, 0, 0, 0, 1]
y_true = [0, 1, 0, 0, 1, 1, 0, 1, 1, 1]
# 计算模型正确率
accuracy = accuracy_score(y_true, y_pred)
print("Accuracy: {:.2f}%".format(accuracy * 100))
# 计算模型错误率
error_rate = 1 - accuracy
print("Error Rate: {:.2f}%".format(error_rate * 100))
# 计算混淆矩阵
conf_matrix = confusion_matrix(y_true, y_pred)
print("Confusion Matrix:\n", conf_matrix)
# 计算精确率
precision = precision_score(y_true, y_pred)
print("Precision: {:.2f}%".format(precision * 100))
# 计算召回率
recall = recall_score(y_true, y_pred)
print("Recall: {:.2f}%".format(recall * 100))
# 计算F1
f1 = f1_score(y_true, y_pred)
print("F1 Score: {:.2f}%".format(f1 * 100))
```
输出结果如下:
```
Accuracy: 70.00%
Error Rate: 30.00%
Confusion Matrix:
[[3 2]
[2 3]]
Precision: 60.00%
Recall: 60.00%
F1 Score: 60.00%
```
其中,正确率为70%,错误率为30%,混淆矩阵显示了模型的真正、假正、假负和真负预测数,精确率为60%,召回率为60%,F1分数为60%。
阅读全文