test_ctc_align.py 8.0 KB
Newer Older
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
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
6
#
D
dzhwinter 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
8
#
D
dzhwinter 已提交
9 10 11 12 13
# 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.
14

15 16
from __future__ import print_function

17 18 19
import sys
import unittest
import numpy as np
20 21
from op_test import OpTest
from test_softmax_op import stable_softmax
22
import paddle.fluid as fluid
23 24


25 26
def CTCAlign(input, lod, blank, merge_repeated, padding=0, input_length=None):
    if input_length is None:
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
        lod0 = lod[0]
        result = []
        cur_offset = 0
        for i in range(len(lod0)):
            prev_token = -1
            for j in range(cur_offset, cur_offset + lod0[i]):
                token = input[j][0]
                if (token != blank) and not (merge_repeated and
                                             token == prev_token):
                    result.append(token)
                prev_token = token
            cur_offset += lod0[i]
        result = np.array(result).reshape([len(result), 1]).astype("int32")
        if len(result) == 0:
            result = np.array([-1])
42
        return result
43 44
    else:
        result = [[] for i in range(len(input))]
45
        output_length = []
46 47
        for i in range(len(input)):
            prev_token = -1
48
            for j in range(input_length[i][0]):
49 50 51 52 53 54
                token = input[i][j]
                if (token != blank) and not (merge_repeated and
                                             token == prev_token):
                    result[i].append(token)
                prev_token = token
            start = len(result[i])
55
            output_length.append([start])
56 57 58 59
            for j in range(start, len(input[i])):
                result[i].append(padding)
        result = np.array(result).reshape(
            [len(input), len(input[0])]).astype("int32")
60 61
        output_length = np.array(output_length).reshape(
            [len(input), 1]).astype("int32")
62

63
    return result, output_length
64 65


W
wanghaoshuang 已提交
66
class TestCTCAlignOp(OpTest):
67
    def config(self):
W
wanghaoshuang 已提交
68
        self.op_type = "ctc_align"
69
        self.input_lod = [[11, 7]]
70 71 72 73 74 75 76 77
        self.blank = 0
        self.merge_repeated = False
        self.input = np.array(
            [0, 1, 2, 2, 0, 4, 0, 4, 5, 0, 6, 6, 0, 0, 7, 7, 7, 0]).reshape(
                [18, 1]).astype("int32")

    def setUp(self):
        self.config()
W
wanghaoshuang 已提交
78 79
        output = CTCAlign(self.input, self.input_lod, self.blank,
                          self.merge_repeated)
80 81 82 83 84 85 86 87 88 89 90 91 92

        self.inputs = {"Input": (self.input, self.input_lod), }
        self.outputs = {"Output": output}
        self.attrs = {
            "blank": self.blank,
            "merge_repeated": self.merge_repeated
        }

    def test_check_output(self):
        self.check_output()
        pass


W
wanghaoshuang 已提交
93
class TestCTCAlignOpCase1(TestCTCAlignOp):
94
    def config(self):
W
wanghaoshuang 已提交
95
        self.op_type = "ctc_align"
96
        self.input_lod = [[11, 8]]
97 98 99
        self.blank = 0
        self.merge_repeated = True
        self.input = np.array(
W
wanghaoshuang 已提交
100 101
            [0, 1, 2, 2, 0, 4, 0, 4, 5, 0, 6, 6, 0, 0, 7, 7, 7, 0, 0]).reshape(
                [19, 1]).astype("int32")
102 103


104 105 106
class TestCTCAlignOpCase2(TestCTCAlignOp):
    def config(self):
        self.op_type = "ctc_align"
107
        self.input_lod = [[4]]
108 109 110 111 112
        self.blank = 0
        self.merge_repeated = True
        self.input = np.array([0, 0, 0, 0]).reshape([4, 1]).astype("int32")


113 114 115 116 117
class TestCTCAlignPaddingOp(OpTest):
    def config(self):
        self.op_type = "ctc_align"
        self.input_lod = []
        self.blank = 0
118
        self.padding_value = 0
119 120 121 122
        self.merge_repeated = True
        self.input = np.array([[0, 2, 4, 4, 0, 6, 3, 6, 6, 0, 0],
                               [1, 1, 3, 0, 0, 4, 5, 6, 0, 0, 0]]).reshape(
                                   [2, 11]).astype("int32")
123
        self.input_length = np.array([[9], [8]]).reshape([2, 1]).astype("int32")
124 125 126

    def setUp(self):
        self.config()
127 128 129 130 131 132 133 134
        output, output_length = CTCAlign(self.input, self.input_lod, self.blank,
                                         self.merge_repeated,
                                         self.padding_value, self.input_length)
        self.inputs = {
            "Input": (self.input, self.input_lod),
            "InputLength": self.input_length
        }
        self.outputs = {"Output": output, "OutputLength": output_length}
135 136 137
        self.attrs = {
            "blank": self.blank,
            "merge_repeated": self.merge_repeated,
138
            "padding_value": self.padding_value
139 140 141 142 143 144 145 146 147 148 149 150
        }

    def test_check_output(self):
        self.check_output()


class TestCTCAlignOpCase3(TestCTCAlignPaddingOp):
    def config(self):
        self.op_type = "ctc_align"
        self.blank = 0
        self.input_lod = []
        self.merge_repeated = True
151
        self.padding_value = 0
152 153 154
        self.input = np.array([[0, 1, 2, 2, 0, 4], [0, 4, 5, 0, 6, 0],
                               [0, 7, 7, 7, 0, 0]]).reshape(
                                   [3, 6]).astype("int32")
155 156
        self.input_length = np.array([[6], [5],
                                      [4]]).reshape([3, 1]).astype("int32")
157 158 159 160


class TestCTCAlignOpCase4(TestCTCAlignPaddingOp):
    '''
161
    # test tensor input which has attr input padding_value
162 163 164 165 166 167 168
    '''

    def config(self):
        self.op_type = "ctc_align"
        self.blank = 0
        self.input_lod = []
        self.merge_repeated = False
169
        self.padding_value = 0
170 171 172
        self.input = np.array([[0, 1, 2, 2, 0, 4], [0, 4, 5, 0, 6, 0],
                               [0, 7, 7, 7, 0, 0]]).reshape(
                                   [3, 6]).astype("int32")
173 174
        self.input_length = np.array([[6], [5],
                                      [4]]).reshape([3, 1]).astype("int32")
175 176 177 178 179 180 181 182


class TestCTCAlignOpCase5(TestCTCAlignPaddingOp):
    def config(self):
        self.op_type = "ctc_align"
        self.blank = 0
        self.input_lod = []
        self.merge_repeated = False
183
        self.padding_value = 1
184 185 186
        self.input = np.array([[0, 1, 2, 2, 0, 4], [0, 4, 5, 0, 6, 0],
                               [0, 7, 1, 7, 0, 0]]).reshape(
                                   [3, 6]).astype("int32")
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
        self.input_length = np.array([[6], [5],
                                      [4]]).reshape([3, 1]).astype("int32")


class TestCTCAlignOpApi(unittest.TestCase):
    def test_api(self):
        x = fluid.layers.data('x', shape=[4], dtype='float32')
        y = fluid.layers.ctc_greedy_decoder(x, blank=0)

        x_pad = fluid.layers.data('x_pad', shape=[4, 4], dtype='float32')
        x_pad_len = fluid.layers.data('x_pad_len', shape=[1], dtype='int64')
        y_pad, y_pad_len = fluid.layers.ctc_greedy_decoder(
            x_pad, blank=0, input_length=x_pad_len)

        place = fluid.CPUPlace()
        x_tensor = fluid.create_lod_tensor(
            np.random.rand(8, 4).astype("float32"), [[4, 4]], place)

        x_pad_tensor = np.random.rand(2, 4, 4).astype("float32")
        x_pad_len_tensor = np.array([[4], [4]]).reshape([2, 1]).astype("int64")

        exe = fluid.Executor(place)

        exe.run(fluid.default_startup_program())
        ret = exe.run(feed={
            'x': x_tensor,
            'x_pad': x_pad_tensor,
            'x_pad_len': x_pad_len_tensor
        },
                      fetch_list=[y, y_pad, y_pad_len],
                      return_numpy=False)
218 219


220 221 222 223 224 225 226 227 228 229 230
class BadInputTestCTCAlignr(unittest.TestCase):
    def test_error(self):
        with fluid.program_guard(fluid.Program()):

            def test_bad_x():
                x = fluid.layers.data(name='x', shape=[8], dtype='int64')
                cost = fluid.layers.ctc_greedy_decoder(input=x, blank=0)

            self.assertRaises(TypeError, test_bad_x)


231 232
if __name__ == "__main__":
    unittest.main()