python绘制评价指标
时间: 2025-06-20 16:52:39 浏览: 7
### 使用 Python 绘制机器学习评价指标
#### 准确率、精确率、召回率和 F1 分数
为了计算并展示这些基本评估指标,可以利用 `sklearn` 库中的函数来获取模型预测的结果,并进一步通过 `matplotlib` 或者 `seaborn` 来可视化数据。
```python
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
import matplotlib.pyplot as plt
import seaborn as sns
def plot_classification_metrics(y_true, y_pred):
acc = accuracy_score(y_true, y_pred)
pre = precision_score(y_true, y_pred, average='weighted')
rec = recall_score(y_true, y_pred, average='weighted')
f1 = f1_score(y_true, y_pred, average='weighted')
metrics = ['Accuracy', 'Precision', 'Recall', 'F1 Score']
scores = [acc, pre, rec, f1]
fig, ax = plt.subplots()
bars = ax.bar(metrics, scores)
# Add value labels on top of the bars
for bar in bars:
height = bar.get_height()
ax.text(bar.get_x() + bar.get_width()/2., height,
f'{height:.2f}', ha='center', va='bottom')
plt.title('Classification Metrics Scores')
plt.ylim(0, 1.1) # To give some space above the highest bar.
plt.show()
# Example usage with dummy data (replace these lines with actual predictions and true values from a model)
y_true_example = [0, 1, 1, 0, 1]
y_pred_example = [0, 1, 0, 0, 1]
plot_classification_metrics(y_true_example, y_pred_example)
```
此代码片段定义了一个名为 `plot_classification_metrics` 的函数,该函数接受真实标签 (`y_true`) 和预测标签 (`y_pred`) 参数作为输入,并绘制条形图显示四个分类性能度量:准确率、精确率、召回率以及 F1 分数值[^1]。
#### ROC 曲线及其 AUC 值
对于二元分类问题而言,可以通过构建接收操作特征(ROC)曲线来直观理解不同阈值下的分类效果。这通常涉及到真阳性和假阳性比率之间的权衡关系。
```python
from sklearn.metrics import roc_curve, auc
import numpy as np
def plot_roc_curve(y_true, y_scores):
fpr, tpr, _ = roc_curve(y_true, y_scores)
roc_auc = auc(fpr, tpr)
plt.figure()
lw = 2
plt.plot(fpr, tpr, color='darkorange',
lw=lw, label=f'ROC curve (area = {roc_auc:.2f})')
plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver Operating Characteristic Curve')
plt.legend(loc="lower right")
plt.show()
# Example usage with dummy probability scores (replace this line with actual prediction probabilities from a binary classifier)
y_scores_example = np.array([0.1, 0.4, 0.35, 0.8])
plot_roc_curve(y_true_example, y_scores_example)
```
这段脚本展示了如何创建一个简单的 ROC 图表,它不仅画出了曲线下面积(Area Under Curve),还包含了对角虚线表示随机猜测的情况。注意这里假设已经有一个能够给出概率估计的二类分类器[^2]。
阅读全文
相关推荐


















