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

15 16
from __future__ import print_function

C
Cao Ying 已提交
17 18 19 20
import unittest
import random
import numpy as np

21
from op_test import OpTest
C
Cao Ying 已提交
22 23 24 25 26


class CRFDecoding(object):
    def __init__(self, emission_weights, transition_weights,
                 seq_start_positions):
27
        assert (emission_weights.shape[0] == sum(seq_start_positions))
C
Cao Ying 已提交
28
        self.tag_num = emission_weights.shape[1]
29
        self.seq_num = len(seq_start_positions)
C
Cao Ying 已提交
30 31 32 33 34 35 36 37 38

        self.seq_start_positions = seq_start_positions
        self.x = emission_weights

        self.a = transition_weights[0, :]
        self.b = transition_weights[1, :]
        self.w = transition_weights[2:, :]

        self.track = np.zeros(
39
            (sum(seq_start_positions), self.tag_num), dtype="int64")
C
Cao Ying 已提交
40
        self.decoded_path = np.zeros(
41
            (sum(seq_start_positions), 1), dtype="int64")
C
Cao Ying 已提交
42 43 44 45

    def _decode_one_sequence(self, decoded_path, x):
        seq_len, tag_num = x.shape
        alpha = np.zeros((seq_len, tag_num), dtype="float64")
Q
Qiao Longfei 已提交
46
        track = np.zeros((seq_len, tag_num), dtype="int64")
C
Cao Ying 已提交
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75

        for i in range(tag_num):
            alpha[0, i] = self.a[i] + x[0, i]

        for k in range(1, seq_len):
            for i in range(tag_num):
                max_score = -np.finfo("float64").max
                max_idx = 0
                for j in range(tag_num):
                    score = alpha[k - 1, j] + self.w[j, i]
                    if score > max_score:
                        max_score = score
                        max_idx = j
                alpha[k, i] = max_score + x[k, i]
                track[k, i] = max_idx

        max_score = -np.finfo("float64").max
        max_idx = 0
        for i in range(tag_num):
            score = alpha[seq_len - 1, i] + self.b[i]
            if score > max_score:
                max_score = score
                max_idx = i

        decoded_path[-1] = max_idx
        for i in range(seq_len - 1, 0, -1):
            decoded_path[i - 1] = max_idx = track[i, max_idx]

    def decode(self):
76
        cur_pos = 0
C
Cao Ying 已提交
77
        for i in range(self.seq_num):
78 79 80
            start = cur_pos
            cur_pos += self.seq_start_positions[i]
            end = cur_pos
C
Cao Ying 已提交
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
            self._decode_one_sequence(self.decoded_path[start:end, :],
                                      self.x[start:end, :])
        return self.decoded_path


class TestCRFDecodingOp1(OpTest):
    """
    Compare the dynamic program with random generated parameters and inputs
    with grouth truth not being given.
    """

    def set_test_data(self):
        SEQ_NUM = 3
        TAG_NUM = 17
        MAX_SEQ_LEN = 10

97 98
        lod = [[]]
        total_len = 0
C
Cao Ying 已提交
99
        for i in range(SEQ_NUM):
100 101
            lod[-1].append(random.randint(1, MAX_SEQ_LEN))
            total_len += lod[-1][-1]
C
Cao Ying 已提交
102
        emission = np.random.uniform(-1, 1,
103
                                     [total_len, TAG_NUM]).astype("float64")
C
Cao Ying 已提交
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
        transition = np.random.uniform(-0.5, 0.5,
                                       [TAG_NUM + 2, TAG_NUM]).astype("float64")

        self.inputs = {
            "Emission": (emission, lod),
            "Transition": transition,
        }

        decoder = CRFDecoding(emission, transition, lod[0])
        decoded_path = decoder.decode()

        self.outputs = {"ViterbiPath": decoded_path}

    def setUp(self):
        self.op_type = "crf_decoding"
        self.set_test_data()

    def test_check_output(self):
        self.check_output()


class TestCRFDecodingOp2(OpTest):
    """
    Compare the dynamic program with brute force computation with
    ground truth being given.
    """

131 132 133
    def init_lod(self):
        self.lod = [[1, 2, 3, 4]]

C
Cao Ying 已提交
134 135 136 137
    def setUp(self):
        self.op_type = "crf_decoding"
        TAG_NUM = 5

138 139
        self.init_lod()
        total_len = sum(self.lod[-1])
C
Cao Ying 已提交
140 141 142 143 144 145 146 147
        transition = np.repeat(
            np.arange(
                TAG_NUM, dtype="float64").reshape(1, TAG_NUM),
            TAG_NUM + 2,
            axis=0)
        emission = np.repeat(
            np.arange(
                TAG_NUM, dtype="float64").reshape(1, TAG_NUM),
148
            total_len,
C
Cao Ying 已提交
149 150 151
            axis=0)

        labels = np.random.randint(
152
            low=0, high=TAG_NUM, size=(total_len, 1), dtype="int64")
C
Cao Ying 已提交
153
        predicted_labels = np.ones(
154
            (total_len, 1), dtype="int64") * (TAG_NUM - 1)
Q
Qiao Longfei 已提交
155
        expected_output = (labels == predicted_labels).astype("int64")
C
Cao Ying 已提交
156 157

        self.inputs = {
158
            "Emission": (emission, self.lod),
C
Cao Ying 已提交
159
            "Transition": transition,
160
            "Label": (labels, self.lod)
C
Cao Ying 已提交
161 162 163 164 165 166 167 168
        }

        self.outputs = {"ViterbiPath": expected_output}

    def test_check_output(self):
        self.check_output()


169 170 171 172 173 174 175 176 177 178
class TestCRFDecodingOp3(TestCRFDecodingOp2):
    def init_lod(self):
        self.lod = [[1, 0, 0, 4]]


class TestCRFDecodingOp4(TestCRFDecodingOp2):
    def init_lod(self):
        self.lod = [[0, 2, 3, 0]]


179 180 181 182 183 184 185 186 187 188 189
def seq_pad(data, length):
    max_len = np.max(length)
    shape = [len(length), max_len] + list(data.shape[1:])
    padded = np.zeros(shape).astype(data.dtype)
    offset = 0
    for i, l in enumerate(length):
        padded[i, 0:l] = data[offset:offset + l]
        offset += l
    return np.squeeze(padded)


190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
class TestCRFDecodingOp5(OpTest):
    """
    Compare the dynamic program with random generated parameters and inputs
    with grouth truth not being given.
    """

    def set_test_data(self):
        SEQ_NUM = 3
        TAG_NUM = 17
        MAX_SEQ_LEN = 10

        lod = [[]]
        total_len = 0
        for i in range(SEQ_NUM):
            lod[-1].append(random.randint(1, MAX_SEQ_LEN))
            total_len += lod[-1][-1]
        emission = np.random.uniform(-1, 1,
                                     [total_len, TAG_NUM]).astype("float64")
        transition = np.random.uniform(-0.5, 0.5,
                                       [TAG_NUM + 2, TAG_NUM]).astype("float64")

        self.inputs = {
212
            "Emission": seq_pad(emission, lod[0]),
213 214 215 216 217 218 219
            "Transition": transition,
            "Length": np.array(lod).astype('int64'),
        }

        decoder = CRFDecoding(emission, transition, lod[0])
        decoded_path = decoder.decode()

220
        self.outputs = {"ViterbiPath": seq_pad(decoded_path, lod[0])}
221 222 223 224 225 226 227 228 229

    def setUp(self):
        self.op_type = "crf_decoding"
        self.set_test_data()

    def test_check_output(self):
        self.check_output()


230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
class TestCRFDecodingOp6(OpTest):
    def init_lod(self):
        self.lod = [[1, 2, 3, 4]]

    def setUp(self):
        self.op_type = "crf_decoding"
        TAG_NUM = 5

        self.init_lod()
        total_len = sum(self.lod[-1])
        transition = np.repeat(
            np.arange(
                TAG_NUM, dtype="float64").reshape(1, TAG_NUM),
            TAG_NUM + 2,
            axis=0)
        emission = np.repeat(
            np.arange(
                TAG_NUM, dtype="float64").reshape(1, TAG_NUM),
            total_len,
            axis=0)

        labels = np.random.randint(
            low=0, high=TAG_NUM, size=(total_len, 1), dtype="int64")
        predicted_labels = np.ones(
            (total_len, 1), dtype="int64") * (TAG_NUM - 1)
        expected_output = (labels == predicted_labels).astype("int64")

        self.inputs = {
            "Emission": seq_pad(emission, self.lod[0]),
            "Transition": transition,
            "Label": seq_pad(labels, self.lod[0]),
            "Length": np.array(self.lod).astype('int64'),
        }

        self.outputs = {"ViterbiPath": seq_pad(expected_output, self.lod[0])}

    def test_check_output(self):
        self.check_output()


C
Cao Ying 已提交
270 271
if __name__ == "__main__":
    unittest.main()