-
Notifications
You must be signed in to change notification settings - Fork 49
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
[Feature] Add OneMinusNormEditDistance for OCR Task #95
Open
Harold-lkk
wants to merge
6
commits into
open-mmlab:main
Choose a base branch
from
Harold-lkk:lkk/OneMinusNormEditDistance
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
c43b7c0
[Feature] Add OneMinusNormEditDistance for OCR Task
Harold-lkk 3b2eef3
fix comment
Harold-lkk 6d51dbc
add api doc
Harold-lkk 6283ff8
fix doc comment
Harold-lkk e0a934e
rename valid to invalid
Harold-lkk dbeb3ea
fix comment
Harold-lkk File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,86 @@ | ||
# Copyright (c) OpenMMLab. All rights reserved. | ||
import re | ||
from typing import TYPE_CHECKING, Dict, List, Sequence | ||
|
||
from mmeval.core import BaseMetric | ||
from mmeval.utils import try_import | ||
|
||
if TYPE_CHECKING: | ||
from rapidfuzz.distance import Levenshtein | ||
else: | ||
distance = try_import('rapidfuzz.distance') | ||
if distance is not None: | ||
Levenshtein = distance.Levenshtein | ||
|
||
|
||
class OneMinusNormEditDistance(BaseMetric): | ||
r"""One minus NED metric for text recognition task. | ||
|
||
Args: | ||
letter_case (str): There are three options to alter the letter cases | ||
|
||
- unchanged: Do not change prediction texts and labels. | ||
- upper: Convert prediction texts and labels into uppercase | ||
characters. | ||
- lower: Convert prediction texts and labels into lowercase | ||
characters. | ||
|
||
Usually, it only works for English characters. Defaults to | ||
'unchanged'. | ||
invalid_symbol (str): A regular expression to filter out invalid or | ||
not cared characters. Defaults to '[^A-Za-z0-9\u4e00-\u9fa5]'. | ||
**kwargs: Keyword parameters passed to :class:`BaseMetric`. | ||
|
||
Examples: | ||
>>> from mmeval import OneMinusNormEditDistance | ||
>>> metric = OneMinusNormEditDistance() | ||
>>> metric(['helL', 'HEL'], ['hello', 'HELLO']) | ||
{'1-N.E.D': 0.6} | ||
>>> metric = OneMinusNormEditDistance(letter_case='upper') | ||
>>> metric(['helL', 'HEL'], ['hello', 'HELLO']) | ||
{'1-N.E.D': 0.7} | ||
""" | ||
|
||
def __init__(self, | ||
letter_case: str = 'unchanged', | ||
invalid_symbol: str = '[^A-Za-z0-9\u4e00-\u9fa5]', | ||
**kwargs): | ||
super().__init__(**kwargs) | ||
|
||
assert letter_case in ['unchanged', 'upper', 'lower'] | ||
self.letter_case = letter_case | ||
self.invalid_symbol = re.compile(invalid_symbol) | ||
|
||
def add(self, predictions: Sequence[str], groundtruths: Sequence[str]): # type: ignore # yapf: disable # noqa: E501 | ||
"""Process one batch of data and predictions. | ||
|
||
Args: | ||
predictions (list[str]): The prediction texts. | ||
groundtruths (list[str]): The ground truth texts. | ||
""" | ||
for pred, label in zip(predictions, groundtruths): | ||
if self.letter_case in ['upper', 'lower']: | ||
pred = getattr(pred, self.letter_case)() | ||
label = getattr(label, self.letter_case)() | ||
label = self.invalid_symbol.sub('', label) | ||
pred = self.invalid_symbol.sub('', pred) | ||
norm_ed = Levenshtein.normalized_distance(pred, label) | ||
self._results.append(norm_ed) | ||
|
||
def compute_metric(self, results: List[float]) -> Dict: | ||
"""Compute the metrics from processed results. | ||
|
||
Args: | ||
results (list[float]): The processed results of each batch. | ||
|
||
Returns: | ||
dict[str, float]: Nested dicts as results. | ||
|
||
- 1-N.E.D (float): One minus the normalized edit distance. | ||
""" | ||
gt_word_num = len(results) | ||
norm_ed_sum = sum(results) | ||
normalized_edit_distance = norm_ed_sum / max(1.0, gt_word_num) | ||
C1rN09 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
metric_results = {} | ||
metric_results['1-N.E.D'] = 1.0 - normalized_edit_distance | ||
return metric_results |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,4 @@ | ||
opencv-python!=4.5.5.62,!=4.5.5.64 | ||
pycocotools | ||
rapidfuzz | ||
shapely |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
import pytest | ||
|
||
from mmeval import OneMinusNormEditDistance | ||
|
||
|
||
def test_init(): | ||
with pytest.raises(AssertionError): | ||
OneMinusNormEditDistance(letter_case='fake') | ||
|
||
|
||
@pytest.mark.parametrize( | ||
argnames=['letter_case', 'expected'], | ||
argvalues=[('unchanged', 0.6), ('upper', 0.7), ('lower', 0.7)]) | ||
def test_one_minus_norm_edit_distance_metric(letter_case, expected): | ||
metric = OneMinusNormEditDistance(letter_case=letter_case) | ||
res = metric(['helL', 'HEL'], ['hello', 'HELLO']) | ||
assert abs(res['1-N.E.D'] - expected) < 1e-7 | ||
metric.reset() | ||
for pred, label in zip(['helL', 'HEL'], ['hello', 'HELLO']): | ||
metric.add([pred], [label]) | ||
res = metric.compute() | ||
assert abs(res['1-N.E.D'] - expected) < 1e-7 |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
rapidfuzz
is not added inruntime.txt
so the metric will throw an error when callingadd
method. The solution is to check it in__init__
. Refer tommeval/mmeval/metrics/connectivity_error.py
Line 60 in 976f399