根据多分类混淆矩阵计算召回率、精确率、卡帕系数的python代码
时间: 2024-02-05 14:03:51 浏览: 104
根据多分类混淆矩阵计算召回率、精确率和卡帕系数的Python代码如下:
```python
from sklearn import metrics
# 计算召回率(Recall)
def recall(confusion_matrix):
recalls = []
for i in range(confusion_matrix.shape[0]):
recall = confusion_matrix[i, i] / sum(confusion_matrix[i, :])
recalls.append(recall)
return recalls
# 计算精确率(Precision)
def precision(confusion_matrix):
precisions = []
for i in range(confusion_matrix.shape[0]):
precision = confusion_matrix[i, i] / sum(confusion_matrix[:, i])
precisions.append(precision)
return precisions
# 计算卡帕系数(Cohen's Kappa)
def kappa(confusion_matrix):
total = sum(sum(confusion_matrix))
true_positives = np.diag(confusion_matrix)
row_sum = np.sum(confusion_matrix, axis=1)
col_sum = np.sum(confusion_matrix, axis=0)
expected = np.outer(row_sum, col_sum) / total
kappa = (total * np.sum(true_positives) - np.sum(confusion_matrix * expected)) / (total**2 - np.sum(confusion_matrix * expected))
return kappa
# 示例使用
y_true = [0, 0, 1, 2, 1, 2, 0, 2, 2, 0, 1, 1] # 真实分类
y_pred = [1, 0, 1, 2, 1, 0, 0, 2, 2, 0, 1, 1] # 模型分类结果
confusion_matrix = metrics.confusion_matrix(y_true, y_pred)
recalls = recall(confusion_matrix)
precisions = precision(confusion_matrix)
kappa_score = kappa(confusion_matrix)
print("召回率:", recalls)
print("精确率:", precisions)
print("卡帕系数:", kappa_score)
```
阅读全文