sequence_labeling.py 13.9 KB
Newer Older
X
Xing Wu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 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 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 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 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 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 208 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 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 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
#   Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# 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
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# 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.
"""
The function lex_net(args) define the lexical analysis network structure
"""
import sys
import os
import math
import numpy as np

import paddle.fluid as fluid
from paddle.fluid.initializer import NormalInitializer
from paddle.fluid.dygraph import to_variable
from paddle.fluid.dygraph.nn import Embedding, Linear, GRUUnit

class DynamicGRU(fluid.dygraph.Layer):
    def __init__(self,
                 size,
                 h_0=None,
                 param_attr=None,
                 bias_attr=None,
                 is_reverse=False,
                 gate_activation='sigmoid',
                 candidate_activation='tanh',
                 origin_mode=False,
                 init_size = None):
        super(DynamicGRU, self).__init__()

        self.gru_unit = GRUUnit(
            size * 3,
            param_attr=param_attr,
            bias_attr=bias_attr,
            activation=candidate_activation,
            gate_activation=gate_activation,
            origin_mode=origin_mode)

        self.size = size
        self.h_0 = h_0
        self.is_reverse = is_reverse


    def forward(self, inputs):
        hidden = self.h_0
        res = []

        for i in range(inputs.shape[1]):
            if self.is_reverse:
                i = inputs.shape[1] - 1 - i

            input_ = inputs[ :, i:i+1, :]
            input_ = fluid.layers.reshape(input_, [-1, input_.shape[2]], inplace=False)
            hidden, reset, gate = self.gru_unit(input_, hidden)
            hidden_ = fluid.layers.reshape(hidden, [-1, 1, hidden.shape[1]], inplace=False)
            res.append(hidden_)

        if self.is_reverse:
            res = res[::-1]
        res = fluid.layers.concat(res, axis=1)
        return res


class BiGRU(fluid.dygraph.Layer):
    def __init__(self,
                 input_dim,
                 grnn_hidden_dim,
                 init_bound,
                 h_0=None):
        super(BiGRU, self).__init__()

        self.pre_gru = Linear(input_dim=input_dim,
                            output_dim=grnn_hidden_dim * 3,
                            param_attr=fluid.ParamAttr(
                            initializer=fluid.initializer.Uniform(
                                low=-init_bound, high=init_bound),
                                regularizer=fluid.regularizer.L2DecayRegularizer(
                                    regularization_coeff=1e-4)))#,
                            #num_flatten_dims=2)

        self.gru = DynamicGRU(size=grnn_hidden_dim,
                h_0=h_0,
                param_attr=fluid.ParamAttr(
                    initializer=fluid.initializer.Uniform(
                        low=-init_bound, high=init_bound),
                    regularizer=fluid.regularizer.L2DecayRegularizer(
                        regularization_coeff=1e-4)))

        self.pre_gru_r = Linear(input_dim=input_dim,
                            output_dim=grnn_hidden_dim * 3,
                            param_attr=fluid.ParamAttr(
                                initializer=fluid.initializer.Uniform(
                                    low=-init_bound, high=init_bound),
                                regularizer=fluid.regularizer.L2DecayRegularizer(
                                    regularization_coeff=1e-4)))#,
                            #num_flatten_dims=2)

        self.gru_r = DynamicGRU(size=grnn_hidden_dim,
                            is_reverse=True,
                            h_0=h_0,
                            param_attr=fluid.ParamAttr(
                                initializer=fluid.initializer.Uniform(
                                    low=-init_bound, high=init_bound),
                                regularizer=fluid.regularizer.L2DecayRegularizer(
                                    regularization_coeff=1e-4)))


    def forward(self, input_feature):
        res_pre_gru = self.pre_gru(input_feature)
        res_gru = self.gru(res_pre_gru)
        res_pre_gru_r = self.pre_gru_r(input_feature)
        res_gru_r = self.gru_r(res_pre_gru_r)
        bi_merge = fluid.layers.concat(input=[res_gru, res_gru_r], axis=-1)
        return bi_merge


class Linear_chain_crf(fluid.dygraph.Layer):

    def __init__(self,
                param_attr, 
                size=None,
                is_test=False,
                dtype='float32'):
        super(Linear_chain_crf, self).__init__()

        self._param_attr = param_attr
        self._dtype = dtype
        self._size = size
        self._is_test=is_test
        self._transition = self.create_parameter(
                        attr=self._param_attr,
                        shape=[self._size + 2, self._size],
                        dtype=self._dtype)

    @property
    def weight(self):
        return self._transition

    @weight.setter
    def weight(self, value):
        self._transition = value

    def forward(self, input, label, length=None):
        
        alpha = self._helper.create_variable_for_type_inference(
                        dtype=self._dtype)
        emission_exps = self._helper.create_variable_for_type_inference(
                        dtype=self._dtype)
        transition_exps = self._helper.create_variable_for_type_inference(
                        dtype=self._dtype)
        log_likelihood = self._helper.create_variable_for_type_inference(
                        dtype=self._dtype)
        this_inputs = {
            "Emission": [input],
            "Transition": self._transition,
            "Label": [label]
        }
        if length:
            this_inputs['Length'] = [length]
        self._helper.append_op(
                        type='linear_chain_crf',
                        inputs=this_inputs,
                        outputs={
                            "Alpha": [alpha],
                            "EmissionExps": [emission_exps],
                            "TransitionExps": transition_exps,
                            "LogLikelihood": log_likelihood
                        },
                        attrs={
                            "is_test": self._is_test,
                        })
        return log_likelihood


class Crf_decoding(fluid.dygraph.Layer):

    def __init__(self,
                param_attr, 
                size=None,
                is_test=False,
                dtype='float32'):
        super(Crf_decoding, self).__init__()

        self._dtype = dtype
        self._size = size
        self._is_test = is_test
        self._param_attr = param_attr
        self._transition = self.create_parameter(
                        attr=self._param_attr,
                        shape=[self._size + 2, self._size],
                        dtype=self._dtype)

    @property
    def weight(self):
        return self._transition

    @weight.setter
    def weight(self, value):
        self._transition = value

    def forward(self, input, label=None, length=None):
        
        viterbi_path = self._helper.create_variable_for_type_inference(
                        dtype=self._dtype)
        this_inputs = {"Emission": [input], "Transition": self._transition, "Label": label}
        if length:
            this_inputs['Length'] = [length]
        self._helper.append_op(
                        type='crf_decoding',
                        inputs=this_inputs,
                        outputs={"ViterbiPath": [viterbi_path]},
                        attrs={
                            "is_test": self._is_test,
                        })
        return viterbi_path


class Chunk_eval(fluid.dygraph.Layer):

    def __init__(self,
                num_chunk_types,
                chunk_scheme,
                excluded_chunk_types=None):
        super(Chunk_eval, self).__init__()
        self.num_chunk_types = num_chunk_types
        self.chunk_scheme = chunk_scheme
        self.excluded_chunk_types = excluded_chunk_types

    def forward(self, input, label, seq_length=None):
        
        precision = self._helper.create_variable_for_type_inference(dtype="float32")
        recall = self._helper.create_variable_for_type_inference(dtype="float32")
        f1_score = self._helper.create_variable_for_type_inference(dtype="float32")
        num_infer_chunks = self._helper.create_variable_for_type_inference(dtype="int64")
        num_label_chunks = self._helper.create_variable_for_type_inference(dtype="int64")
        num_correct_chunks = self._helper.create_variable_for_type_inference(dtype="int64")

        this_input = {"Inference": [input], "Label": [label]}
        if seq_length:
            this_input["SeqLength"] = [seq_length]

        self._helper.append_op(
                        type='chunk_eval',
                        inputs=this_input,
                        outputs={
                                "Precision": [precision],
                                "Recall": [recall],
                                "F1-Score": [f1_score],
                                "NumInferChunks": [num_infer_chunks],
                                "NumLabelChunks": [num_label_chunks],
                                "NumCorrectChunks": [num_correct_chunks]
                            },
                        attrs={
                            "num_chunk_types": self.num_chunk_types,
                            "chunk_scheme": self.chunk_scheme,
                            "excluded_chunk_types": self.excluded_chunk_types or []
                        })
        return (precision, recall, f1_score, num_infer_chunks, num_label_chunks,
            num_correct_chunks)


class lex_net(fluid.dygraph.Layer):
    def __init__(self, 
                    args, 
                    vocab_size, 
                    num_labels,
                    length=None):
        super(lex_net, self).__init__()
        """
        define the lexical analysis network structure
        word: stores the input of the model
        for_infer: a boolean value, indicating if the model to be created is for training or predicting.

        return:
            for infer: return the prediction
            otherwise: return the prediction
        """
        self.word_emb_dim = args.word_emb_dim
        self.vocab_size = vocab_size
        self.num_labels = num_labels
        self.grnn_hidden_dim = args.grnn_hidden_dim
        self.emb_lr = args.emb_learning_rate if 'emb_learning_rate' in dir(args) else 1.0
        self.crf_lr = args.emb_learning_rate if 'crf_learning_rate' in dir(args) else 1.0
        self.bigru_num = args.bigru_num
        self.init_bound = 0.1
        #self.IS_SPARSE = True

        self.word_embedding = Embedding(
            size=[self.vocab_size, self.word_emb_dim],
            dtype='float32',
            #is_sparse=self.IS_SPARSE,
            param_attr=fluid.ParamAttr(
                learning_rate=self.emb_lr,
                name="word_emb",
                initializer=fluid.initializer.Uniform(
                    low=-self.init_bound, high=self.init_bound)))

        h_0 = np.zeros((args.batch_size, self.grnn_hidden_dim), dtype="float32")
        h_0 = to_variable(h_0)
        self.bigru_units = []
        for i in range(self.bigru_num):
            if i == 0:
                self.bigru_units.append(
                    self.add_sublayer("bigru_units%d" % i,
                    BiGRU(self.grnn_hidden_dim, self.grnn_hidden_dim, self.init_bound, h_0=h_0)
                ))
            else:
                self.bigru_units.append(
                    self.add_sublayer("bigru_units%d" % i,
                    BiGRU(self.grnn_hidden_dim * 2, self.grnn_hidden_dim, self.init_bound, h_0=h_0)
                ))
        
        self.fc = Linear(input_dim=self.grnn_hidden_dim * 2,
                        output_dim=self.num_labels,
                        param_attr=fluid.ParamAttr(
                            initializer=fluid.initializer.Uniform(
                                low=-self.init_bound, high=self.init_bound),
                            regularizer=fluid.regularizer.L2DecayRegularizer(
                                regularization_coeff=1e-4)))#,
                        #num_flatten_dims=2)
        
        self.linear_chain_crf = Linear_chain_crf(
                param_attr=fluid.ParamAttr(
X
Xing Wu 已提交
333
                    name='linear_chain_crfw', learning_rate=self.crf_lr),
X
Xing Wu 已提交
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
                size=self.num_labels)

        self.crf_decoding = Crf_decoding(
                param_attr=fluid.ParamAttr(
                    name='crfw', learning_rate=self.crf_lr),
                size=self.num_labels)
        
    def forward(self, word, target=None, length=None):
        """
        Configure the network
        """
        #word = fluid.layers.unsqueeze(word, [2])
        word_embed = self.word_embedding(word)
        input_feature = word_embed
        
        for i in range(self.bigru_num):
            bigru_output = self.bigru_units[i](input_feature)
            input_feature = bigru_output

        emission = self.fc(bigru_output)

        if target is not None:
            crf_cost = self.linear_chain_crf(
                input=emission,
                label=target,
                length=length)
            avg_cost = fluid.layers.mean(x=crf_cost)
            self.crf_decoding.weight = self.linear_chain_crf.weight
            crf_decode = self.crf_decoding(
                input=emission,
                length=length)
            return avg_cost, crf_decode#, word_embed, bigru_output, emission
        else:
            crf_decode = self.crf_decoding(
                input=emission,
                length=length)
            return crf_decode