test_edit_distance_op.py 6.4 KB
Newer Older
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
F
fengjiayi 已提交
2
#
D
dzhwinter 已提交
3 4 5
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
F
fengjiayi 已提交
6
#
D
dzhwinter 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
F
fengjiayi 已提交
8
#
D
dzhwinter 已提交
9 10 11 12 13 14
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

Y
Yibing Liu 已提交
15 16
import unittest
import numpy as np
17
from op_test import OpTest
Z
zhiboniu 已提交
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
import paddle


def python_edit_distance(input,
                         label,
                         input_length=None,
                         label_length=None,
                         normalized=True,
                         ignored_tokens=None):
    return paddle.nn.functional.loss.edit_distance(
        input,
        label,
        normalized=normalized,
        ignored_tokens=ignored_tokens,
        input_length=input_length,
        label_length=label_length)
Y
Yibing Liu 已提交
34 35 36 37 38


def Levenshtein(hyp, ref):
    """ Compute the Levenshtein distance between two strings.

39
    :param hyp: hypothesis string in index
Y
Yibing Liu 已提交
40
    :type hyp: list
41
    :param ref: reference string in index
Y
Yibing Liu 已提交
42 43 44 45 46 47 48 49 50
    :type ref: list
    """
    m = len(hyp)
    n = len(ref)
    if m == 0:
        return n
    if n == 0:
        return m

51
    dist = np.zeros((m + 1, n + 1)).astype("float32")
Y
Yibing Liu 已提交
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
    for i in range(0, m + 1):
        dist[i][0] = i
    for j in range(0, n + 1):
        dist[0][j] = j

    for i in range(1, m + 1):
        for j in range(1, n + 1):
            cost = 0 if hyp[i - 1] == ref[j - 1] else 1
            deletion = dist[i - 1][j] + 1
            insertion = dist[i][j - 1] + 1
            substitution = dist[i - 1][j - 1] + cost
            dist[i][j] = min(deletion, insertion, substitution)
    return dist[m][n]


67
class TestEditDistanceOp(OpTest):
68

69 70
    def setUp(self):
        self.op_type = "edit_distance"
Z
zhiboniu 已提交
71
        self.python_api = python_edit_distance
72
        normalized = False
73 74
        x1 = np.array([[12, 3, 5, 8, 2]]).astype("int64")
        x2 = np.array([[12, 4, 7, 8]]).astype("int64")
75 76
        x1 = np.transpose(x1)
        x2 = np.transpose(x2)
77 78
        self.x1_lod = [1, 4]
        self.x2_lod = [3, 1]
79

80
        num_strs = len(self.x1_lod)
81
        distance = np.zeros((num_strs, 1)).astype("float32")
82
        sequence_num = np.array(2).astype("int64")
83 84 85

        x1_offset = 0
        x2_offset = 0
86 87
        for i in range(0, num_strs):
            distance[i] = Levenshtein(
88 89 90 91
                hyp=x1[x1_offset:(x1_offset + self.x1_lod[i])],
                ref=x2[x2_offset:(x2_offset + self.x2_lod[i])])
            x1_offset += self.x1_lod[i]
            x2_offset += self.x2_lod[i]
92
            if normalized is True:
93
                len_ref = self.x2_lod[i]
94
                distance[i] = distance[i] / len_ref
95

96
        self.attrs = {'normalized': normalized}
97
        self.inputs = {'Hyps': (x1, [self.x1_lod]), 'Refs': (x2, [self.x2_lod])}
98
        self.outputs = {'Out': distance, 'SequenceNum': sequence_num}
99 100

    def test_check_output(self):
Z
zhiboniu 已提交
101
        self.check_output(check_eager=True)
102 103


104
class TestEditDistanceOpNormalizedCase0(OpTest):
105

106 107 108
    def reset_config(self):
        pass

109 110 111
    def post_config(self):
        pass

Y
Yibing Liu 已提交
112
    def setUp(self):
113
        self.op_type = "edit_distance"
Z
zhiboniu 已提交
114
        self.python_api = python_edit_distance
Y
Yibing Liu 已提交
115
        normalized = True
116 117
        self.x1 = np.array([[10, 3, 6, 5, 8, 2]]).astype("int64")
        self.x2 = np.array([[10, 4, 6, 7, 8]]).astype("int64")
118 119
        self.x1_lod = [3, 0, 3]
        self.x2_lod = [2, 1, 2]
120 121 122
        self.x1 = np.transpose(self.x1)
        self.x2 = np.transpose(self.x2)

123
        self.reset_config()
Y
Yibing Liu 已提交
124

125
        num_strs = len(self.x1_lod)
126
        distance = np.zeros((num_strs, 1)).astype("float32")
127
        sequence_num = np.array(num_strs).astype("int64")
128 129 130

        x1_offset = 0
        x2_offset = 0
131 132
        for i in range(0, num_strs):
            distance[i] = Levenshtein(
133 134
                hyp=self.x1[x1_offset:(x1_offset + self.x1_lod[i])],
                ref=self.x2[x2_offset:(x2_offset + self.x2_lod[i])])
135 136
            x1_offset += self.x1_lod[i]
            x2_offset += self.x2_lod[i]
137
            if normalized is True:
138
                len_ref = self.x2_lod[i]
139
                distance[i] = distance[i] / len_ref
140

Y
Yibing Liu 已提交
141
        self.attrs = {'normalized': normalized}
142 143 144 145
        self.inputs = {
            'Hyps': (self.x1, [self.x1_lod]),
            'Refs': (self.x2, [self.x2_lod])
        }
146
        self.outputs = {'Out': distance, 'SequenceNum': sequence_num}
Y
Yibing Liu 已提交
147

148 149
        self.post_config()

Y
Yibing Liu 已提交
150
    def test_check_output(self):
Z
zhiboniu 已提交
151
        self.check_output(check_eager=True)
Y
Yibing Liu 已提交
152 153


154
class TestEditDistanceOpNormalizedCase1(TestEditDistanceOpNormalizedCase0):
155

156 157 158 159 160 161
    def reset_config(self):
        self.x1_lod = [0, 6, 0]
        self.x2_lod = [2, 1, 2]


class TestEditDistanceOpNormalizedCase2(TestEditDistanceOpNormalizedCase0):
162

163 164 165 166 167
    def reset_config(self):
        self.x1_lod = [0, 0, 6]
        self.x2_lod = [2, 2, 1]


168
class TestEditDistanceOpNormalizedTensor(OpTest):
169

170 171 172 173 174 175 176 177
    def reset_config(self):
        self.x1 = np.array([[10, 3, 0, 0], [6, 5, 8, 2]], dtype=np.int64)
        self.x2 = np.array([[10, 4, 0], [6, 7, 8]], dtype=np.int64)
        self.x1_lod = np.array([2, 4], dtype=np.int64)
        self.x2_lod = np.array([2, 3], dtype=np.int64)

    def setUp(self):
        self.op_type = "edit_distance"
Z
zhiboniu 已提交
178
        self.python_api = python_edit_distance
179 180 181 182 183 184 185 186 187
        normalized = True

        self.reset_config()

        num_strs = len(self.x1_lod)
        distance = np.zeros((num_strs, 1)).astype("float32")
        sequence_num = np.array(num_strs).astype("int64")

        for i in range(0, num_strs):
188 189
            distance[i] = Levenshtein(hyp=self.x1[i][0:self.x1_lod[i]],
                                      ref=self.x2[i][0:self.x2_lod[i]])
190 191 192 193 194 195 196 197 198 199 200 201 202 203
            if normalized is True:
                len_ref = self.x2_lod[i]
                distance[i] = distance[i] / len_ref

        self.attrs = {'normalized': normalized}
        self.inputs = {
            'Hyps': self.x1,
            'Refs': self.x2,
            'HypsLength': self.x1_lod,
            'RefsLength': self.x2_lod
        }
        self.outputs = {'Out': distance, 'SequenceNum': sequence_num}

    def test_check_output(self):
Z
zhiboniu 已提交
204
        self.check_output(check_eager=True)
205 206


Y
Yibing Liu 已提交
207
if __name__ == '__main__':
Z
zhiboniu 已提交
208
    paddle.enable_static()
Y
Yibing Liu 已提交
209
    unittest.main()