test_linear_chain_crf_op.py 8.6 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
caoying03 已提交
17 18 19 20
import unittest
import random
import numpy as np

21
from op_test import OpTest
C
caoying03 已提交
22 23 24


class LinearChainCrfForward(object):
C
caoying03 已提交
25 26
    def __init__(self, seq_start_positions, emission_weights, emission_row_max,
                 emission_exps, transition_weights, transition_exps, labels):
C
caoying03 已提交
27 28 29 30 31 32 33
        self.tag_num = emission_weights.shape[1]
        self.seq_num = len(seq_start_positions) - 1

        self.seq_start_positions = seq_start_positions
        self.labels = labels
        self.x = emission_weights

C
caoying03 已提交
34 35
        self.x_row_max = emission_row_max
        self.x_exps = emission_exps
C
caoying03 已提交
36 37 38

        # unnormalized logits of the transition weights for the start mark.
        self.a = transition_weights[0, :]
C
caoying03 已提交
39
        self.a_exps = transition_exps[0, :]
C
caoying03 已提交
40 41
        # unnormalized logits of the transition weights for the end mark.
        self.b = transition_weights[1, :]
C
caoying03 已提交
42
        self.b_exps = transition_exps[1, :]
C
caoying03 已提交
43 44
        # unnormalized logits of the transition weights for all the other tags.
        self.w = transition_weights[2:, :]
C
caoying03 已提交
45
        self.w_exps = transition_exps[2:, :]
C
caoying03 已提交
46 47 48 49 50

        # The output of linear chain crf operator.
        # alpha is a memo table in dynamic programming to caculate
        # nomalization factor.
        self.alpha = np.zeros(
C
caoying03 已提交
51
            (seq_start_positions[-1], self.tag_num), dtype="float64")
C
caoying03 已提交
52
        self.log_likelihood = np.zeros((self.seq_num, 1))
C
caoying03 已提交
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79

    def _l1_norm(self, x):
        s = np.sum(x)
        x /= s
        return s

    def _forward_a_sequence(self, x, x_row_max, x_exps, label, alpha):
        seq_len = x_row_max.shape[0]
        log_likelihood = 0.

        for i in range(self.tag_num):
            alpha[0, i] = self.a_exps[i] * x_exps[0, i]
        log_likelihood = -x_row_max[0] - np.log(self._l1_norm(alpha[0, :]))

        # calculate the unnormalized logits of the normalization factor.
        for k in range(1, seq_len):
            for i in range(self.tag_num):
                s = 0.
                for j in range(self.tag_num):
                    s += alpha[k - 1, j] * self.w_exps[j, i]
                alpha[k, i] = x_exps[k, i] * s
            log_likelihood -= x_row_max[k] + np.log(self._l1_norm(alpha[k, :]))
        s = 0.
        for i in range(self.tag_num):
            s += alpha[-1, i] * self.b_exps[i]
        log_likelihood -= np.log(s)

80
        # calculate the nominator part.
C
caoying03 已提交
81
        log_likelihood += (
C
caoying03 已提交
82 83
            self.a[label[0]] + x[0, label[0]] + self.b[label[-1]])

C
caoying03 已提交
84
        for k in range(1, seq_len):
C
caoying03 已提交
85
            log_likelihood += (x[k, label[k]] + self.w[label[k - 1], label[k]])
86
        return -log_likelihood
C
caoying03 已提交
87 88 89 90 91

    def crf_forward_compute(self):
        for i in range(self.seq_num):
            start = self.seq_start_positions[i]
            end = self.seq_start_positions[i + 1]
92 93
            if start >= end:
                continue
C
caoying03 已提交
94
            self.log_likelihood[i] = self._forward_a_sequence(
C
caoying03 已提交
95
                self.x[start:end, :], self.x_row_max[start:end, :],
C
caoying03 已提交
96 97 98 99 100 101 102
                self.x_exps[start:end, :], self.labels[start:end, :],
                self.alpha[start:end, :])
        return self.alpha, self.log_likelihood


class TestLinearChainCrfOp(OpTest):
    def set_test_data(self):
C
caoying03 已提交
103 104 105
        # TODO(caoying) Fix the unittest by: add the boundary cases when
        # sequence lengths are 1, 2, and 3.

C
caoying03 已提交
106
        SEQ_NUM = 3
C
caoying03 已提交
107
        TAG_NUM = 17
C
caoying03 已提交
108
        MAX_SEQ_LEN = 5
C
caoying03 已提交
109 110

        # the linear_chain_crf operator only supports sequence (LoD level = 1)
111 112
        lod = [[]]
        seq_start_pos = [0]
C
caoying03 已提交
113
        for i in range(SEQ_NUM):
114
            lod[-1].append(random.randint(1, MAX_SEQ_LEN))
115 116 117
            seq_start_pos.append(seq_start_pos[-1] + lod[-1][-1])
        emission = np.random.uniform(
            -1, 1, [seq_start_pos[-1], TAG_NUM]).astype("float64")
C
caoying03 已提交
118 119 120
        emission_row_max = np.amax(emission, axis=1, keepdims=True)
        emission_exps = np.exp(emission - emission_row_max)

C
caoying03 已提交
121
        transition = np.random.uniform(-0.5, 0.5,
C
caoying03 已提交
122
                                       [TAG_NUM + 2, TAG_NUM]).astype("float64")
C
caoying03 已提交
123 124
        transition_exps = np.exp(transition)

C
caoying03 已提交
125
        labels = np.random.randint(
126
            low=0, high=TAG_NUM, size=(seq_start_pos[-1], 1), dtype="int64")
C
caoying03 已提交
127 128 129 130

        self.inputs = {
            "Emission": (emission, lod),
            "Transition": transition,
131
            "Label": (labels, lod)
C
caoying03 已提交
132
        }
133
        crf = LinearChainCrfForward(seq_start_pos, emission, emission_row_max,
C
caoying03 已提交
134 135
                                    emission_exps, transition, transition_exps,
                                    labels)
C
caoying03 已提交
136 137
        alpha, log_likelihood = crf.crf_forward_compute()

C
caoying03 已提交
138 139 140 141 142 143
        self.outputs = {
            "Alpha": alpha,
            "EmissionExps": emission_exps,
            "TransitionExps": transition_exps,
            "LogLikelihood": log_likelihood
        }
C
caoying03 已提交
144 145 146 147 148 149 150 151

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

    def test_check_output(self):
        self.check_output()

C
caoying03 已提交
152
    def test_check_grad(self):
C
caoying03 已提交
153
        self.check_grad(["Emission", "Transition"], "LogLikelihood")
C
caoying03 已提交
154 155 156

    def test_check_grad_ignore_transition(self):
        self.check_grad(
C
caoying03 已提交
157
            ["Emission"], "LogLikelihood", no_grad_set=set("Transition"))
C
caoying03 已提交
158

C
caoying03 已提交
159

160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
class TestLinearChainCrfPaddingTensor(OpTest):
    def seq_pad(self, 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 padded

    def seq_pad_exps(self, data, length):
        # Adding for transition_exps
        max_len = np.max(length)
        shape = [len(length), max_len] + list(data.shape[1:])
        padded = np.ones(shape).astype(data.dtype)
        offset = 0
        for i, l in enumerate(length):
            padded[i, 0:l] = data[offset:offset + l]
            offset += l
        return padded

    def set_test_data_1(self):
        # Fix the unittest by: add padding tensor in inputs 
        SEQ_NUM = 3
        TAG_NUM = 17
        MAX_SEQ_LEN = 5

        # the linear_chain_crf operator only supports sequence (LoD level = 1)
        lod = [[]]
        seq_start_pos = [0]
        for i in range(SEQ_NUM):
            lod[-1].append(random.randint(1, MAX_SEQ_LEN))
            seq_start_pos.append(seq_start_pos[-1] + lod[-1][-1])
        emission = np.random.uniform(
            -1, 1, [seq_start_pos[-1], TAG_NUM]).astype("float64")
        emission_row_max = np.amax(emission, axis=1, keepdims=True)
        emission_exps = np.exp(emission - emission_row_max)
        transition = np.random.uniform(-0.5, 0.5,
                                       [TAG_NUM + 2, TAG_NUM]).astype("float64")
        transition_exps = np.exp(transition)

        labels = np.random.randint(
            low=0, high=TAG_NUM, size=(seq_start_pos[-1], 1), dtype="int64")
        self.inputs = {
            "Emission": self.seq_pad(emission, lod[0]),
            "Transition": transition,
            "Label": self.seq_pad(labels, lod[0]),
208
            "Length": np.array(lod).astype("int64")
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
        }
        crf = LinearChainCrfForward(seq_start_pos, emission, emission_row_max,
                                    emission_exps, transition, transition_exps,
                                    labels)
        alpha, log_likelihood = crf.crf_forward_compute()
        self.outputs = {
            "Alpha": self.seq_pad(alpha, lod[0]),
            "EmissionExps": self.seq_pad_exps(emission_exps, lod[0]),
            "TransitionExps": transition_exps,
            "LogLikelihood": log_likelihood
        }

    def setUp(self):
        self.op_type = "linear_chain_crf"
        self.set_test_data_1()

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
        self.check_grad(["Emission", "Transition"], "LogLikelihood")

    def test_check_grad_ignore_transition(self):
        self.check_grad(
            ["Emission"], "LogLikelihood", no_grad_set=set("Transition"))


C
caoying03 已提交
236 237
if __name__ == "__main__":
    unittest.main()