Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Fix] Make accuracy take into account ignore_index #1259

Merged
merged 2 commits into from
Feb 14, 2022

Conversation

HJoonKwon
Copy link
Contributor

@HJoonKwon HJoonKwon commented Jan 29, 2022

Motivation

Your repository has been so helpful for my projects and I deeply appreciate it.
My opinion can be wrong, but please look into it and I hope it can be helpful a bit at least.

I tried to apply

reduce_zero_label=True 

to ignore the background label, and it turned out that the value of acc_seg from the decode_head was weirdly low while other values such as loss and IoU were all looking good. Looking into the decode_head.py,

    @force_fp32(apply_to=('seg_logit', ))
    def losses(self, seg_logit, seg_label):
        """Compute segmentation loss."""
        loss = dict()
        seg_logit = resize(
            input=seg_logit,
            size=seg_label.shape[2:],
            mode='bilinear',
            align_corners=self.align_corners)
        if self.sampler is not None:
            seg_weight = self.sampler.sample(seg_logit, seg_label)
        else:
            seg_weight = None
        seg_label = seg_label.squeeze(1)

        if not isinstance(self.loss_decode, nn.ModuleList):
            losses_decode = [self.loss_decode]
        else:
            losses_decode = self.loss_decode
        for loss_decode in losses_decode:
            if loss_decode.loss_name not in loss:
                loss[loss_decode.loss_name] = loss_decode(
                    seg_logit,
                    seg_label,
                    weight=seg_weight,
                    ignore_index=self.ignore_index)
            else:
                loss[loss_decode.loss_name] += loss_decode(
                    seg_logit,
                    seg_label,
                    weight=seg_weight,
                    ignore_index=self.ignore_index)

        loss['acc_seg'] = accuracy(seg_logit, seg_label)
        return loss

the loss_decode receives self.ignore_index as an input argument, while the accuracy doesn't. I think it explains why the accuracy seemed so different from other metrics. Thus, I think the accuracy function should receive the ignore index as an argument as well to take into account the ignore_index to calculate the accuracy of the decode head.

And, I found that the point_head.py also uses the same function without receiving the ignore_index. So I guess both of them should be fixed.

Modification

Firstly, the accuracy function can be defined like this

def accuracy(pred, target, ignore_index=255, topk=1, thresh=None): 

and inside of the function, the accuracy can be calculated like this to exclude the ignored index,

res.append(correct_k.mul_(100.0 / target[target!=ignore_index].numel())) 

Secondly, in decode_head.py, we can simply put self.ignore_index into one of the arguments like this,

loss['acc_seg'] = accuracy(seg_logit, seg_label, ignore_index=self.ignore_index) 

Finally, the same strategy can be applied to point_head.py like this,

loss['acc_point'] = accuracy(point_logits, point_label, ignore_index=self.ignore_index)

BC-breaking (Optional)

Use cases (Optional)

Checklist

  1. Pre-commit or other linting tools are used to fix the potential lint issues.
  2. The modification is covered by complete unit tests. If not, please add more unit test to ensure the correctness.
  3. If the modification has potential influence on downstream projects, this PR should be tested with downstream projects, like MMDet or MMDet3D.
  4. The documentation has been modified accordingly, like docstring or example tutorials.

@CLAassistant
Copy link

CLAassistant commented Jan 29, 2022

CLA assistant check
All committers have signed the CLA.

@HJoonKwon HJoonKwon changed the title [Fix] Make accuracy take ignore_index into account [Fix] Make accuracy take into account ignore_index Jan 29, 2022
@codecov
Copy link

codecov bot commented Feb 8, 2022

Codecov Report

Merging #1259 (dd02ad8) into master (b163101) will increase coverage by 0.00%.
The diff coverage is 100.00%.

Impacted file tree graph

@@           Coverage Diff           @@
##           master    #1259   +/-   ##
=======================================
  Coverage   90.22%   90.22%           
=======================================
  Files         130      130           
  Lines        7558     7560    +2     
  Branches     1258     1258           
=======================================
+ Hits         6819     6821    +2     
  Misses        531      531           
  Partials      208      208           
Flag Coverage Δ
unittests 90.22% <100.00%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Impacted Files Coverage Δ
mmseg/models/decode_heads/decode_head.py 92.63% <100.00%> (ø)
mmseg/models/decode_heads/point_head.py 93.54% <100.00%> (ø)
mmseg/models/losses/accuracy.py 100.00% <100.00%> (ø)

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 0934a57...dd02ad8. Read the comment docs.

Copy link
Collaborator

@MeowZheng MeowZheng left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please add UT to test this feature in

@@ -2,12 +2,13 @@
import torch.nn as nn


def accuracy(pred, target, topk=1, thresh=None):
def accuracy(pred, target, topk=1, thresh=None, ignore_index=255):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it would be better to set None as default value of ignore_index

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, I will do it with adding UT by tonight(KST). Thank you for the comment :)

"""Calculate accuracy according to the prediction and target.

Args:
pred (torch.Tensor): The model prediction, shape (N, num_class, ...)
target (torch.Tensor): The target of each prediction, shape (N, , ...)
ignore_index (int | None): The label index to be ignored. Default: 255
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
ignore_index (int | None): The label index to be ignored. Default: 255
ignore_index (int | None): The label index to be ignored.
If it is None, any label will be taken into account. Default: None

Copy link
Collaborator

@Junjun2016 Junjun2016 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi, thanks for your contribution.
Please fix the lint error and add unittests.

@HJoonKwon
Copy link
Contributor Author

I found a bug while making unit tests for it, and it is fixed now. I checked the pre-commit and all passed fine :)

@Junjun2016
Copy link
Collaborator

I found a bug while making unit tests for it, and it is fixed now. I checked the pre-commit and all passed fine :)

Great.

@HJoonKwon
Copy link
Contributor Author

Hi! I have a question. Should I do pull-rebase based on the most recent commit on the master branch? or Am I done here? :)

@MeowZheng
Copy link
Collaborator

Yes, you should

@HJoonKwon
Copy link
Contributor Author

@MeowZheng Okay, I did pull-rebase based on the current master branch and pushed again!

@MeowZheng MeowZheng merged commit 346f70d into open-mmlab:master Feb 14, 2022
bowenroom pushed a commit to bowenroom/mmsegmentation that referenced this pull request Feb 25, 2022
* make accuracy take into account ignore_index

* add UT for accuracy
@MengzhangLI MengzhangLI mentioned this pull request Mar 9, 2022
wjkim81 pushed a commit to wjkim81/mmsegmentation that referenced this pull request Dec 3, 2023
…nction (open-mmlab#1259)

* add unit tests for Q(error) is Gaussian

* minor refactor

* add docstrings and paper reference

* update pretrained model path

* fix bug

* fix bug

* align with official training setting

* remove random shift

* add docs and remove irrelevant files

* remove debug code

* fix code style

* fix unittest and remove irrelevant files

Co-authored-by: ly015 <liyining0712@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants