二分类混淆矩阵百分比显示程序
时间: 2023-08-28 17:17:29 浏览: 187
以下是一个 Python 程序,用于计算和显示二分类混淆矩阵的百分比:
```python
import numpy as np
def confusion_matrix(y_true, y_pred):
"""
计算二分类混淆矩阵
:param y_true: 真实标签
:param y_pred: 预测标签
:return: 混淆矩阵
"""
tp = np.sum(np.logical_and(y_true == 1, y_pred == 1))
tn = np.sum(np.logical_and(y_true == 0, y_pred == 0))
fp = np.sum(np.logical_and(y_true == 0, y_pred == 1))
fn = np.sum(np.logical_and(y_true == 1, y_pred == 0))
return np.array([[tn, fp], [fn, tp]])
def print_confusion_matrix(y_true, y_pred):
"""
打印二分类混淆矩阵的百分比
:param y_true: 真实标签
:param y_pred: 预测标签
"""
cm = confusion_matrix(y_true, y_pred)
cm_pct = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print('Confusion Matrix (Percentage):')
print(cm_pct)
# 示例
y_true = np.array([0, 1, 0, 1, 0, 0, 1, 1])
y_pred = np.array([0, 1, 0, 1, 0, 1, 0, 1])
print_confusion_matrix(y_true, y_pred)
```
输出结果:
```
Confusion Matrix (Percentage):
[[0.75 0.25]
[0.25 0.75]]
```
其中,混淆矩阵的四个元素分别为 True Negative (TN),False Positive (FP),False Negative (FN),True Positive (TP),对应地,程序中的变量为 tn,fp,fn,tp。将混淆矩阵的每个元素除以该行总数,即可得到每个元素的百分比值。
阅读全文