YOLO使用COCO评价指标输出每个类别AP结果

本文介绍了如何在COCO.py和cocoeval.py文件中进行修改,包括COCO类的初始化增加类别名称获取,以及在cocoeval.py中对COCO评估指标的summarize函数进行了扩展,支持按类别计算平均精度和平均召回率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在调用的文件中找到coco.py,cocoeval.py文件(pycharm通过Ctrl和鼠标跳转即可)

from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval

① 首先修改coco.py的类COCO的初始化def __init__,添加代码:

def __init__(self, annotation_file=None):
        """
        Constructor of Microsoft COCO helper class for reading and visualizing annotations.
        :param annotation_file (str): location of annotation file
        :param image_folder (str): location to the folder that hosts images.
        :return:
        """
        # load dataset
        self.dataset,self.anns,self.cats,self.imgs = dict(),dict(),dict(),dict()
        self.imgToAnns, self.catToImgs = defaultdict(list), defaultdict(list)
        if not annotation_file == None:
            print('loading annotations into memory...')
            tic = time.time()
            with open(annotation_file, 'r') as f:
                dataset = json.load(f)
            assert type(dataset)==dict, 'annotation file format {} not supported'.format(type(dataset))
            print('Done (t={:0.2f}s)'.format(time.time()- tic))
            # 下面这句代码为添加内容
            print("category names: {}".format([e["name"] for e in sorted(dataset["categories"], key=lambda x: x["id"])]))
            self.dataset = dataset
            self.createIndex()

 ② 修改cocoeval.py,在第456行下添加代码,修改summarize函数:


def summarize(self):
        '''
        Compute and display summary metrics for evaluation results.
        Note this functin can *only* be applied on the default parameter setting
        '''
        def _summarize( ap=1, iouThr=None, areaRng='all', maxDets=100 ):
            p = self.params
            iStr = ' {:<18} {} @[ IoU={:<9} | area={:>6s} | maxDets={:>3d} ] = {:0.3f}'
            titleStr = 'Average Precision' if ap == 1 else 'Average Recall'
            typeStr = '(AP)' if ap==1 else '(AR)'
            iouStr = '{:0.2f}:{:0.2f}'.format(p.iouThrs[0], p.iouThrs[-1]) \
                if iouThr is None else '{:0.2f}'.format(iouThr)
 
            aind = [i for i, aRng in enumerate(p.areaRngLbl) if aRng == areaRng]
            mind = [i for i, mDet in enumerate(p.maxDets) if mDet == maxDets]
            if ap == 1:
                # dimension of precision: [TxRxKxAxM]
                s = self.eval['precision']
                # IoU
                if iouThr is not None:
                    t = np.where(iouThr == p.iouThrs)[0]
                    s = s[t]
                s = s[:,:,:,aind,mind]
            else:
                # dimension of recall: [TxKxAxM]
                s = self.eval['recall']
                if iouThr is not None:
                    t = np.where(iouThr == p.iouThrs)[0]
                    s = s[t]
                s = s[:,:,aind,mind]
            if len(s[s>-1])==0:
                mean_s = -1
            else:
                mean_s = np.mean(s[s>-1])
            #print(iStr.format(titleStr, typeStr, iouStr, areaRng, maxDets, mean_s))
            # 以下代码为添加内容
            category_dimension = 1 + int(ap)
            if s.shape[category_dimension] > 1:
 
                iStr += ", per category = {}"
                mean_axis = (0,)
                if ap == 1:
                    mean_axis = (0, 1)
                per_category_mean_s = np.mean(s, axis=mean_axis).flatten()
                with np.printoptions(precision=3, suppress=True, sign=" ", floatmode="fixed"):
                    print(iStr.format(titleStr, typeStr, iouStr, areaRng, maxDets, mean_s, per_category_mean_s))
            else:
                print(iStr.format(titleStr, typeStr, iouStr, areaRng, maxDets, mean_s, ""))
            return mean_s

最后:

如果你想要进一步了解更多的相关知识,可以关注下面公众号联系~会不定期发布相关设计内容包括但不限于如下内容:信号处理、通信仿真、算法设计、matlab appdesigner,gui设计、simulink仿真......希望能帮到你!

5a8015ddde1e41418a38e958eb12ecbd.png

 

### YOLO模型训练结果评估方法 #### 准确率与召回率 对于YOLO系列模型而言,在评估其训练效果时,准确率(Precision)和召回率(Recall)是非常重要的两个指标。这两个数值能够反映出模型预测框的质量以及覆盖真实物体的能力。当这两项数据在整个训练周期内的变化较为平稳时,则表明该次训练过程相对稳定有效[^1]。 #### 平均精度均值(mAP) 除了上述提到的基础评测标准外,还需要特别注意平均精度均值这一综合性更强的评判依据。具体来说分为两种常见形式: - **mAP@0.5**:表示IoU阈值设定为0.5情况下得到的结果; - **mAP@[.5:.95]** 或者称为 COCO AP :意味着取多个不同交并比范围下的表现综合考量后的得分。 这两种方式都可以很好地衡量模型的整体性能,并且后者更能体现算法面对复杂场景时的表现力[^2]。 #### 损失函数曲线 观察损失函数随迭代次数的变化趋势也是不可或缺的一环。理想状态下,随着轮数增加,总Loss应该呈现出逐渐下降的趋势直至收敛;如果发现存在明显震荡或者其他异常现象,则可能暗示着学习率设置不当等问题待解决。 ```python import matplotlib.pyplot as plt def plot_loss_curve(losses): epochs = range(len(losses)) plt.figure(figsize=(8, 6)) plt.plot(epochs, losses, 'b', label='Training loss') plt.title('Training Loss Curve') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.show() # 假设losses是一个包含每一轮训练结束后的loss值列表 plot_loss_curve([0.7, 0.6, 0.5, 0.4]) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MatpyMaster

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值