MMengine 如何修改evaluator

因为本人项目需要使用video swin transformer

默认是提供了一些evaluation metrics 但是我看了一下 我准召率 f1这些都没有,毕竟本事是值考虑多标签任务的正确性的

mmaction.apis — MMAction2 1.2.0 documentation

自定义Metric的代码可以参考这个教程

模型精度评测(Evaluation) — mmengine 0.10.2 文档

from typing import Sequence, List

from mmengine.evaluator import BaseMetric
from mmengine.registry import METRICS

import numpy as np


@METRICS.register_module()  # 将 Accuracy 类注册到 METRICS 注册器
class SimpleAccuracy(BaseMetric):
    """ Accuracy Evaluator

    Default prefix: ACC

    Metrics:
        - accuracy (float): classification accuracy
    """

    default_prefix = 'ACC'  # 设置 default_prefix

    def process(self, data_batch: Sequence[dict], data_samples: Sequence[dict]):
        """Process one batch of data and predictions. The processed
        Results should be stored in `self.results`, which will be used
        to compute the metrics when all batches have been processed.

        Args:
            data_batch (Sequence[Tuple[Any, dict]]): A batch of data
                from the dataloader.
            data_samples (Sequence[dict]): A batch of outputs from
                the model.
        """

        # 取出分类预测结果和类别标签
        result = {
            'pred': data_samples['pred_label'],
            'gt': data_samples['data_sample']['gt_label']
        }

        # 将当前 batch 的结果存进 self.results
        self.results.append(result)

    def compute_metrics(self, results: List):
        """Compute the metrics from processed results.

        Args:
            results (dict): The processed results of each batch.

        Returns:
            Dict: The computed metrics. The keys are the names of the metrics,
            and the values are corresponding results.
        """

        # 汇总所有样本的分类预测结果和类别标签
        preds = np.concatenate([res['pred'] for res in results])
        gts = np.concatenate([res['gt'] for res in results])

        # 计算分类正确率
        acc = (preds == gts).sum() / preds.size

        # 返回评测指标结果
        return {'accuracy': acc}

给的代码在我这个版本下是不匹配的,估计是没有更新

实际上process拿到的data-samples部分是

[{'num_classes': 2,
  'img_shape': (64, 64),
  'pred_label': tensor([1], device='cuda:0'),
  'pred_score': tensor([0.3516, 0.6484], device='cuda:0'),
  'gt_label': tensor([1], device='cuda:0')}]

是一个数组,所有需要额外写一步先提取第一个元素

其他的就按教程中的自定义方法写再加上自定义的metric 添加到结果字典中返回就可以

  • 9
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如何解决Loading and preparing results... DONE (t=0.01s) creating index... index created! Running per image evaluation... Evaluate annotation type *bbox* DONE (t=0.44s). Accumulating evaluation results... Traceback (most recent call last): File "tools/train.py", line 133, in <module> main() File "tools/train.py", line 129, in main runner.train() File "/home/wangbei/anaconda3/envs/Object_mmdetection/lib/python3.8/site-packages/mmengine/runner/runner.py", line 1721, in train model = self.train_loop.run() # type: ignore File "/home/wangbei/anaconda3/envs/Object_mmdetection/lib/python3.8/site-packages/mmengine/runner/loops.py", line 102, in run self.runner.val_loop.run() File "/home/wangbei/anaconda3/envs/Object_mmdetection/lib/python3.8/site-packages/mmengine/runner/loops.py", line 366, in run metrics = self.evaluator.evaluate(len(self.dataloader.dataset)) File "/home/wangbei/anaconda3/envs/Object_mmdetection/lib/python3.8/site-packages/mmengine/evaluator/evaluator.py", line 79, in evaluate _results = metric.evaluate(size) File "/home/wangbei/anaconda3/envs/Object_mmdetection/lib/python3.8/site-packages/mmengine/evaluator/metric.py", line 133, in evaluate _metrics = self.compute_metrics(results) # type: ignore File "/home/wangbei/mmdetection(coco)/mmdet/evaluation/metrics/coco_metric.py", line 512, in compute_metrics coco_eval.accumulate() File "/home/wangbei/anaconda3/envs/Object_mmdetection/lib/python3.8/site-packages/pycocotools-2.0-py3.8-linux-x86_64.egg/pycocotools/cocoeval.py", line 378, in accumulate tp_sum = np.cumsum(tps, axis=1).astype(dtype=np.float) File "/home/wangbei/anaconda3/envs/Object_mmdetection/lib/python3.8/site-packages/numpy/__init__.py", line 305, in __getattr__ raise AttributeError(__former_attrs__[attr]) AttributeError: module 'numpy' has no attribute 'float'. `np.float` was a deprecated alias for the builtin `float`. To avoid this error in existing code, use `float` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.float64` here. The aliases was originally deprecated in NumPy 1.20; for more details and guidance see the original release note at: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations WARNING:torch.distributed.elastic.multiprocessing.api:Sending process 29887 closing signal SIGTERM ERROR:torch.distributed.elastic.multiprocessing.api:failed (exitcode: 1) local_rank: 0 (pid: 29886) of binary: /home/wangbei/anaconda3/envs/Object_mmdetection/bin/python
06-09

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值