用confusion_matrix计算性能
时间: 2023-10-01 15:02:13 浏览: 35
Confusion matrix是评估分类模型性能的一种方法。它是一个二维矩阵,其中行表示实际类别,列表示预测类别。在二分类问题中,confusion matrix如下所示:
| | 预测正类 | 预测负类 |
| :----------: | :----------: | :----------: |
| **实际正类** | TP | FN |
| **实际负类** | FP | TN |
其中,TP表示真正例(True Positive),即实际为正例且被模型预测为正例的样本数;FN表示假反例(False Negative),即实际为正例但被模型预测为负例的样本数;FP表示假正例(False Positive),即实际为负例但被模型预测为正例的样本数;TN表示真反例(True Negative),即实际为负例且被模型预测为负例的样本数。
通过confusion matrix,可以计算出一些性能指标,如准确率、召回率、精确率和F1值等。这些指标可以帮助我们更全面地评估分类模型的性能。
例如,准确率可以表示为:
$Accuracy = \frac{TP + TN}{TP + FP + FN + TN}$
召回率可以表示为:
$Recall = \frac{TP}{TP + FN}$
精确率可以表示为:
$Precision = \frac{TP}{TP + FP}$
F1值可以表示为:
$F1 = \frac{2 \times Precision \times Recall}{Precision + Recall}$
在实际应用中,我们可以使用Python中的sklearn.metrics库计算confusion matrix及其相关指标。例如,下面的代码演示了如何计算confusion matrix和准确率:
```python
from sklearn.metrics import confusion_matrix, accuracy_score
y_true = [0, 1, 0, 1, 0, 0, 1, 1]
y_pred = [0, 1, 1, 1, 0, 0, 0, 1]
cm = confusion_matrix(y_true, y_pred)
accuracy = accuracy_score(y_true, y_pred)
print("Confusion matrix:\n", cm)
print("Accuracy:", accuracy)
```
输出结果为:
```
Confusion matrix:
[[3 1]
[2 2]]
Accuracy: 0.625
```
其中,confusion matrix为:
| | 预测正类 | 预测负类 |
| :--: | :--: | :--: |
| 实际正类 | 3 | 1 |
| 实际负类 | 2 | 2 |
准确率为0.625。