用python代码写测试集的MAP和MAR指标
时间: 2023-12-17 17:11:23 浏览: 41
假设你已经有了测试集的真实标签和模型预测的标签,可以使用以下代码计算MAP和MAR指标:
```python
import numpy as np
def calculate_MAP(predictions, targets):
"""
计算测试集的平均精度(MAP)
predictions: 模型预测结果
targets: 真实标签
"""
avg_precision = 0
num_examples = len(predictions)
for i in range(num_examples):
precision = 0
num_correct = 0
for j in range(len(predictions[i])):
if predictions[i][j] == targets[i][j]:
num_correct += 1
precision += num_correct / (j + 1)
if num_correct > 0:
avg_precision += precision / num_correct
MAP = avg_precision / num_examples
return MAP
def calculate_MAR(predictions, targets):
"""
计算测试集的平均倒数排名(MAR)
predictions: 模型预测结果
targets: 真实标签
"""
avg_reciprocal_rank = 0
num_examples = len(predictions)
for i in range(num_examples):
reciprocal_rank = 0
for j in range(len(predictions[i])):
if predictions[i][j] == targets[i][j]:
reciprocal_rank = 1 / (j + 1)
break
avg_reciprocal_rank += reciprocal_rank
MAR = avg_reciprocal_rank / num_examples
return MAR
```
其中,`predictions`和`targets`都是二维数组,每行表示一个样本的预测结果或真实标签,每列表示一个类别的预测结果或真实标签。`MAP`和`MAR`都是一个标量,分别表示测试集的平均精度和平均倒数排名。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)