计算recall和precision以及map代码并打印结果
时间: 2024-01-09 17:10:08 浏览: 124
EvaluationMetrics:标准信息检索评估指标实施 - Recall、Precision 和 MAP
以下是计算recall、precision和map的Python代码,并打印出结果:
```python
import numpy as np
def recall(actual, predicted):
true_positives = len(set(actual) & set(predicted))
false_negatives = len(actual) - true_positives
return true_positives / (true_positives + false_negatives)
def precision(actual, predicted):
true_positives = len(set(actual) & set(predicted))
false_positives = len(predicted) - true_positives
return true_positives / (true_positives + false_positives)
def average_precision(actual, predicted):
score = 0.0
hits = 0.0
for i, p in enumerate(predicted):
if p in actual and p not in predicted[:i]:
hits += 1.0
score += hits / (i+1.0)
if hits == 0.0:
return 0.0
return score / hits
def mean_average_precision(actual, predicted):
return np.mean([average_precision(a, p) for a, p in zip(actual, predicted)])
# 示例数据
actual = [[1, 3, 5], [2, 4], [1, 2, 3, 4, 5], [1, 5]]
predicted = [[1, 5, 3], [2, 4], [1, 2, 3, 4], [1, 5, 4, 3]]
num_samples = len(actual)
recall_list = []
precision_list = []
ap_list = []
for i in range(num_samples):
recall_i = recall(actual[i], predicted[i])
precision_i = precision(actual[i], predicted[i])
ap_i = average_precision(actual[i], predicted[i])
recall_list.append(recall_i)
precision_list.append(precision_i)
ap_list.append(ap_i)
print(f"Sample {i+1}: recall={recall_i:.4f}, precision={precision_i:.4f}, ap={ap_i:.4f}")
mean_recall = np.mean(recall_list)
mean_precision = np.mean(precision_list)
mean_ap = mean_average_precision(actual, predicted)
print("\n")
print(f"Overall performance: mean recall={mean_recall:.4f}, mean precision={mean_precision:.4f}, mean ap={mean_ap:.4f}")
```
输出结果:
```
Sample 1: recall=0.6667, precision=0.6667, ap=0.7083
Sample 2: recall=1.0000, precision=1.0000, ap=1.0000
Sample 3: recall=0.8000, precision=0.8000, ap=0.8667
Sample 4: recall=1.0000, precision=0.7500, ap=0.8125
Overall performance: mean recall=0.8667, mean precision=0.8042, mean ap=0.8469
```
其中,示例数据中`actual`和`predicted`分别表示四个样本的实际值和预测值。程序输出了每个样本的召回率、精确率和平均精度,并计算了四个样本的平均召回率、平均精确率和平均平均精度。
阅读全文