回到部落格
一般文章

實作 ANLS

用 torchmetrics 計算標準化編輯距離,補上 ST-VQA 評分使用的 0.5 門檻。

Average Normalized Levenshtein Similarity(ANLS)用編輯距離衡量預測文字與答案的接近程度。字串越長,可容忍的字元差異也越多;因此先將 Levenshtein 距離除以兩個字串中較長者的長度,再把結果轉成相似度。

ST-VQA 原始論文使用 0.5 門檻:標準化距離超過 0.5 的答案記為 0 分,其餘使用 1 - 距離,最後才對多筆樣本取平均。只計算 1 - 距離 而不套門檻,得到的是平均 NLS,分數可能與 ANLS 不同。下方範例示範逐對字串計分;若資料集一題有多個可接受答案,還需依該資料集的評分規則選取答案。

參考資料

導入必要的庫

首先,需要導入一些必要的庫,特別是由 torchmetrics 實作的 EditDistance:

python
from typing import Any, Literal, Optional, Sequence, Union

import torch
from torch import Tensor
from torchmetrics.metric import Metric
from torchmetrics.text import EditDistance
from torchmetrics.utilities.data import dim_zero_cat

EditDistance 回傳逐對字串的編輯距離;接著依較長字串的長度正規化,再套用 ANLS 的 0.5 門檻。

實作標準化功能

這個類別繼承 torchmetrics.metric.Metric,因此要實作 update 和 compute:

python
class NormalizedLevenshteinSimilarity(Metric):

    def __init__(
        self,
        substitution_cost: int = 1,
        reduction: Optional[Literal["mean", "sum", "none"]] = "mean",
        **kwargs: Any
    ) -> None:
        super().__init__(**kwargs)
        self.edit_distance = EditDistance(
            substitution_cost=substitution_cost,
            reduction=None  # Set to None to get distances for all string pairs
        )

        # ...

這裡有幾個要點:

  1. 確保輸入的 preds 和 target 是字串列表,否則函數就會計算到「字元」的部分。
  2. 計算每個字串的最大長度,這樣才能進行標準化。
python
def update(self, preds: Union[str, Sequence[str]], target: Union[str, Sequence[str]]) -> None:
    """Update state with predictions and targets."""

    if isinstance(preds, str):
        preds = [preds]
    if isinstance(target, str):
        target = [target]
    if len(preds) != len(target):
        raise ValueError("preds and target must have the same length")

    distances = self.edit_distance(preds, target)
    max_lengths = torch.tensor([
        max(len(p), len(t))
        for p, t in zip(preds, target)
    ], dtype=torch.float, device=distances.device)

    ratio = torch.where(
        max_lengths == 0,
        torch.zeros_like(distances).float(),
        distances.float() / max_lengths
    )

    nls_values = torch.where(
        ratio <= 0.5,
        1 - ratio,
        torch.zeros_like(ratio),
    )

    # ...

實作 reduction 參數

reduction="mean" 會平均每對字串套用門檻後的分數。

sum 回傳總和;none 回傳每對字串的分數。

python
def _compute(
    self,
    nls_score: Tensor,
    num_elements: Union[Tensor, int],
) -> Tensor:
    """Compute the ANLS over state."""
    if nls_score.numel() == 0 or num_elements == 0:
        return torch.tensor(0, dtype=torch.int32)
    if self.reduction == "mean":
        return nls_score.sum() / num_elements
    if self.reduction == "sum":
        return nls_score.sum()
    if self.reduction is None or self.reduction == "none":
        return nls_score

def compute(self) -> torch.Tensor:
    """Compute the NLS over state."""
    if self.reduction == "none" or self.reduction is None:
        return self._compute(dim_zero_cat(self.nls_values_list), 1)
    return self._compute(self.nls_score, self.num_elements)

reduction="none" 會回傳每對字串套用門檻後的分數;dim_zero_cat 將儲存的分數合併為一個 Tensor。

程式碼

完整的實作如下:

python
from typing import Any, Literal, Optional, Sequence, Union

import torch
from torch import Tensor
from torchmetrics.metric import Metric
from torchmetrics.text import EditDistance
from torchmetrics.utilities.data import dim_zero_cat

class NormalizedLevenshteinSimilarity(Metric):
    """
    Normalized Levenshtein Similarity (NLS) is a metric that computes the
    normalized Levenshtein similarity between two sequences.
    This metric is 1 - normalized edit distance when the distance is at most 0.5,
    where `levenshtein_distance` is the Levenshtein distance between the two
    sequences and `max_length` is the maximum length of the two sequences.

    NLS aims to provide a similarity measure for character sequences
    (such as text), making it useful in areas like text similarity analysis,
    Optical Character Recognition (OCR), and Natural Language Processing (NLP).

    This class inherits from `Metric` and uses the `EditDistance` class to
    compute the Levenshtein distance.

    Inputs to the ``update`` and ``compute`` methods are as follows:

    - ``preds`` (:class:`~Union[str, Sequence[str]]`):
        Predicted text sequences or a collection of sequences.
    - ``target`` (:class:`~Union[str, Sequence[str]]`):
        Target text sequences or a collection of sequences.

    Output from the ``compute`` method is as follows:

    - ``nls`` (:class:`~torch.Tensor`): A tensor containing the NLS value.
        Returns 0.0 when there are no samples; otherwise, it returns the NLS.

    Args:
        substitution_cost:
            The cost of substituting one character for another. Default is 1.
        reduction:
            Method to aggregate metric scores.
            Default is 'mean', options are 'sum' or None.

            - ``'mean'``: takes the mean over samples, which is ANLS.
            - ``'sum'``: takes the sum over samples
            - ``None`` or ``'none'``: returns the score per sample

        kwargs: Additional keyword arguments.

    Example::
        Multiple strings example:

        >>> metric = NormalizedLevenshteinSimilarity(reduction=None)
        >>> preds = ["rain", "lnaguaeg"]
        >>> target = ["shine", "language"]
        >>> metric(preds, target)
        tensor([0.0000, 0.5000])
        >>> metric = NormalizedLevenshteinSimilarity(reduction="mean")
        >>> metric(preds, target)
        tensor(0.2500)
    """

    def __init__(
        self,
        substitution_cost: int = 1,
        reduction: Optional[Literal["mean", "sum", "none"]] = "mean",
        **kwargs: Any
    ) -> None:
        super().__init__(**kwargs)
        self.edit_distance = EditDistance(
            substitution_cost=substitution_cost,
            reduction=None  # Set to None to get distances for all string pairs
        )

        allowed_reduction = (None, "mean", "sum", "none")
        if reduction not in allowed_reduction:
            raise ValueError(
                f"Expected argument `reduction` to be one of {allowed_reduction}, but got {reduction}")
        self.reduction = reduction

        if self.reduction == "none" or self.reduction is None:
            self.add_state(
                "nls_values_list",
                default=[],
                dist_reduce_fx="cat"
            )
        else:
            self.add_state(
                "nls_score",
                default=torch.tensor(0.0),
                dist_reduce_fx="sum"
            )
            self.add_state(
                "num_elements",
                default=torch.tensor(0),
                dist_reduce_fx="sum"
            )

    def update(self, preds: Union[str, Sequence[str]], target: Union[str, Sequence[str]]) -> None:
        """Update state with predictions and targets."""
        if isinstance(preds, str):
            preds = [preds]
        if isinstance(target, str):
            target = [target]
        if len(preds) != len(target):
            raise ValueError("preds and target must have the same length")

        distances = self.edit_distance(preds, target)
        max_lengths = torch.tensor([
            max(len(p), len(t))
            for p, t in zip(preds, target)
        ], dtype=torch.float, device=distances.device)

        ratio = torch.where(
            max_lengths == 0,
            torch.zeros_like(distances).float(),
            distances.float() / max_lengths
        )

        nls_values = torch.where(
        ratio <= 0.5,
        1 - ratio,
        torch.zeros_like(ratio),
    )

        if self.reduction == "none" or self.reduction is None:
            self.nls_values_list.append(nls_values)
        else:
            self.nls_score += nls_values.sum()
            self.num_elements += nls_values.shape[0]

    def _compute(
        self,
        nls_score: Tensor,
        num_elements: Union[Tensor, int],
    ) -> Tensor:
        """Compute the ANLS over state."""
        if nls_score.numel() == 0 or num_elements == 0:
            return torch.tensor(0, dtype=torch.int32)
        if self.reduction == "mean":
            return nls_score.sum() / num_elements
        if self.reduction == "sum":
            return nls_score.sum()
        if self.reduction is None or self.reduction == "none":
            return nls_score

    def compute(self) -> torch.Tensor:
        """Compute the NLS over state."""
        if self.reduction == "none" or self.reduction is None:
            return self._compute(dim_zero_cat(self.nls_values_list), 1)
        return self._compute(self.nls_score, self.num_elements)

if __name__ == "__main__":
    anls = NormalizedLevenshteinSimilarity(reduction='mean')
    preds = ["rain", "lnaguaeg"]
    target = ["shine", "language"]
    print(anls(preds, target))

最後

這份程式示範單一答案、逐對字串的 ANLS 計算。要與特定資料集的官方評分一致,還需核對大小寫與空白正規化、多答案選取方式,以及空字串的處理規則。