用熟悉的编程语言编写一个2*2的混淆矩阵计算器,并计算f1
时间: 2024-09-08 17:02:42 浏览: 106
Java编程语言编写的计算器应用程序
混淆矩阵是一种统计工具,常用于评估分类模型的性能,特别是在二分类任务中。它展示了实际类别(True Positives, True Negatives, False Positives, False Negatives)与预测结果之间的对应情况。下面是一个简单的Python示例,使用字典来模拟2x2混淆矩阵,并计算F1分数:
```python
def confusion_matrix(actual, predicted):
matrix = {
"TP": 0,
"TN": 0,
"FP": 0,
"FN": 0
}
for i in range(len(actual)):
if actual[i] == predicted[i]:
if actual[i] == 1: # 如果真实值为正
matrix["TP"] += 1
else:
matrix["TN"] += 1
else:
if actual[i] == 1: # 真实值为正,预测值为负
matrix["FN"] += 1
else: # 预测值为正,真实值为负
matrix["FP"] += 1
return matrix
# 示例数据
actual = [0, 1, 1, 0]
predicted = [0, 0, 1, 1]
matrix = confusion_matrix(actual, predicted)
print("Confusion Matrix:")
for category, count in matrix.items():
print(f"{category}: {count}")
def f1_score(precision, recall):
if precision + recall == 0:
return 0
else:
return (2 * precision * recall) / (precision + recall)
# 计算精度(Precision)、召回率(Recall)
precision = matrix["TP"] / (matrix["TP"] + matrix["FP"])
recall = matrix["TP"] / (matrix["TP"] + matrix["FN"])
f1 = f1_score(precision, recall)
print("\nF1 Score:", f1)
阅读全文