sequence_task.py 9.8 KB
Newer Older
K
kinghuin 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#coding:utf-8
#  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.

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import time
from collections import OrderedDict
22

K
kinghuin 已提交
23 24 25
import numpy as np
import paddle.fluid as fluid
from paddlehub.finetune.evaluate import chunk_eval, calculate_f1
K
kinghuin 已提交
26
from paddlehub.common.logger import logger
K
kinghuin 已提交
27
from .base_task import BaseTask
K
kinghuin 已提交
28 29


K
kinghuin 已提交
30
class SequenceLabelTask(BaseTask):
K
kinghuin 已提交
31 32 33 34
    def __init__(self,
                 feature,
                 max_seq_len,
                 num_classes,
K
kinghuin 已提交
35 36 37
                 dataset=None,
                 feed_list=None,
                 data_reader=None,
K
kinghuin 已提交
38 39
                 startup_program=None,
                 config=None,
S
Steffy-zxf 已提交
40 41
                 metrics_choices="default",
                 add_crf=False):
K
kinghuin 已提交
42 43 44
        if metrics_choices == "default":
            metrics_choices = ["f1", "precision", "recall"]

S
Steffy-zxf 已提交
45 46
        self.add_crf = add_crf

K
kinghuin 已提交
47 48
        main_program = feature.block.program
        super(SequenceLabelTask, self).__init__(
K
kinghuin 已提交
49
            dataset=dataset,
K
kinghuin 已提交
50 51 52 53 54 55 56 57 58 59
            data_reader=data_reader,
            main_program=main_program,
            feed_list=feed_list,
            startup_program=startup_program,
            config=config,
            metrics_choices=metrics_choices)
        self.feature = feature
        self.max_seq_len = max_seq_len
        self.num_classes = num_classes

S
Steffy-zxf 已提交
60 61 62 63 64 65
    @property
    def return_numpy(self):
        if self.add_crf:
            return False
        else:
            return True
K
kinghuin 已提交
66

S
Steffy-zxf 已提交
67
    def _build_net(self):
68 69
        self.seq_len = fluid.layers.data(
            name="seq_len", shape=[1], dtype='int64', lod_level=0)
S
Steffy-zxf 已提交
70
        self.seq_len_used = fluid.layers.squeeze(self.seq_len, axes=[1])
K
kinghuin 已提交
71

S
Steffy-zxf 已提交
72 73
        if self.add_crf:
            unpad_feature = fluid.layers.sequence_unpad(
74
                self.feature, length=self.seq_len_used)
S
Steffy-zxf 已提交
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
            self.emission = fluid.layers.fc(
                size=self.num_classes,
                input=unpad_feature,
                param_attr=fluid.ParamAttr(
                    initializer=fluid.initializer.Uniform(low=-0.1, high=0.1),
                    regularizer=fluid.regularizer.L2DecayRegularizer(
                        regularization_coeff=1e-4)))
            size = self.emission.shape[1]
            fluid.layers.create_parameter(
                shape=[size + 2, size], dtype=self.emission.dtype, name='crfw')
            self.ret_infers = fluid.layers.crf_decoding(
                input=self.emission, param_attr=fluid.ParamAttr(name='crfw'))
            ret_infers = fluid.layers.assign(self.ret_infers)
            return [ret_infers]
        else:
            self.logits = fluid.layers.fc(
                input=self.feature,
                size=self.num_classes,
                num_flatten_dims=2,
                param_attr=fluid.ParamAttr(
                    name="cls_seq_label_out_w",
                    initializer=fluid.initializer.TruncatedNormal(scale=0.02)),
                bias_attr=fluid.ParamAttr(
                    name="cls_seq_label_out_b",
                    initializer=fluid.initializer.Constant(0.)))

            self.ret_infers = fluid.layers.reshape(
                x=fluid.layers.argmax(self.logits, axis=2), shape=[-1, 1])

            logits = self.logits
            logits = fluid.layers.flatten(logits, axis=2)
            logits = fluid.layers.softmax(logits)
            self.num_labels = logits.shape[1]
            return [logits]
K
kinghuin 已提交
109 110 111 112 113 114 115

    def _add_label(self):
        label = fluid.layers.data(
            name="label", shape=[self.max_seq_len, 1], dtype='int64')
        return [label]

    def _add_loss(self):
S
Steffy-zxf 已提交
116
        if self.add_crf:
117 118
            labels = fluid.layers.sequence_unpad(self.labels[0],
                                                 self.seq_len_used)
S
Steffy-zxf 已提交
119 120 121 122 123 124 125 126 127 128
            crf_cost = fluid.layers.linear_chain_crf(
                input=self.emission,
                label=labels,
                param_attr=fluid.ParamAttr(name='crfw'))
            loss = fluid.layers.mean(x=crf_cost)
        else:
            labels = fluid.layers.flatten(self.labels[0], axis=2)
            ce_loss = fluid.layers.cross_entropy(
                input=self.outputs[0], label=labels)
            loss = fluid.layers.mean(x=ce_loss)
K
kinghuin 已提交
129 130 131
        return loss

    def _add_metrics(self):
S
Steffy-zxf 已提交
132
        if self.add_crf:
133 134
            labels = fluid.layers.sequence_unpad(self.labels[0],
                                                 self.seq_len_used)
S
Steffy-zxf 已提交
135 136 137 138 139 140 141 142 143 144 145 146
            (precision, recall, f1_score, num_infer_chunks, num_label_chunks,
             num_correct_chunks) = fluid.layers.chunk_eval(
                 input=self.outputs[0],
                 label=labels,
                 chunk_scheme="IOB",
                 num_chunk_types=int(np.ceil((self.num_classes - 1) / 2.0)))
            chunk_evaluator = fluid.metrics.ChunkEvaluator()
            chunk_evaluator.reset()
            return [precision, recall, f1_score]
        else:
            self.ret_labels = fluid.layers.reshape(
                x=self.labels[0], shape=[-1, 1])
147
            return [self.ret_labels, self.ret_infers, self.seq_len_used]
K
kinghuin 已提交
148 149 150 151

    def _calculate_metrics(self, run_states):
        total_infer = total_label = total_correct = loss_sum = 0
        run_step = run_time_used = run_examples = 0
S
Steffy-zxf 已提交
152
        precision_sum = recall_sum = f1_score_sum = 0
K
kinghuin 已提交
153 154
        for run_state in run_states:
            loss_sum += np.mean(run_state.run_results[-1])
S
Steffy-zxf 已提交
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
            if self.add_crf:
                precision_sum += np.mean(
                    run_state.run_results[0]) * run_state.run_examples
                recall_sum += np.mean(
                    run_state.run_results[1]) * run_state.run_examples
                f1_score_sum += np.mean(
                    run_state.run_results[2]) * run_state.run_examples
            else:
                np_labels = run_state.run_results[0]
                np_infers = run_state.run_results[1]
                np_lens = run_state.run_results[2]
                label_num, infer_num, correct_num = chunk_eval(
                    np_labels, np_infers, np_lens, self.num_labels,
                    self.device_count)
                total_infer += infer_num
                total_label += label_num
                total_correct += correct_num
K
kinghuin 已提交
172 173 174 175 176 177 178
            run_examples += run_state.run_examples
            run_step += run_state.run_step

        run_time_used = time.time() - run_states[0].run_time_begin
        run_speed = run_step / run_time_used
        avg_loss = loss_sum / run_examples

S
Steffy-zxf 已提交
179 180 181 182 183 184 185
        if self.add_crf:
            precision = precision_sum / run_examples
            recall = recall_sum / run_examples
            f1 = f1_score_sum / run_examples
        else:
            precision, recall, f1 = calculate_f1(total_label, total_infer,
                                                 total_correct)
K
kinghuin 已提交
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
        # The first key will be used as main metrics to update the best model
        scores = OrderedDict()

        for metric in self.metrics_choices:
            if metric == "precision":
                scores["precision"] = precision
            elif metric == "recall":
                scores["recall"] = recall
            elif metric == "f1":
                scores["f1"] = f1
            else:
                raise ValueError("Not Support Metric: \"%s\"" % metric)

        return scores, avg_loss, run_speed

    @property
    def feed_list(self):
K
kinghuin 已提交
203 204 205 206 207 208
        if self._compatible_mode:
            feed_list = [varname for varname in self._base_feed_list]
            if self.is_train_phase or self.is_test_phase:
                feed_list += [self.labels[0].name, self.seq_len.name]
            else:
                feed_list += [self.seq_len.name]
K
kinghuin 已提交
209
        else:
K
kinghuin 已提交
210
            feed_list = super(SequenceLabelTask, self).feed_list
K
kinghuin 已提交
211 212 213 214 215 216 217
        return feed_list

    @property
    def fetch_list(self):
        if self.is_train_phase or self.is_test_phase:
            return [metric.name for metric in self.metrics] + [self.loss.name]
        elif self.is_predict_phase:
218
            return [self.ret_infers.name] + [self.seq_len_used.name]
K
kinghuin 已提交
219
        return [output.name for output in self.outputs]
K
kinghuin 已提交
220 221

    def _postprocessing(self, run_states):
K
kinghuin 已提交
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
        if self._compatible_mode:
            id2label = {
                val: key
                for key, val in self._base_data_reader.label_map.items()
            }
        else:
            if self._label_list:
                id2label = {}
                for index, label in enumerate(self._label_list):
                    id2label[index] = label
            else:
                logger.warning(
                    "Fail to postprocess the predict output. Please set label_list parameter in predict function or initialize the task with dataset parameter."
                )
                return run_states

K
kinghuin 已提交
238 239 240 241 242 243 244 245 246 247
        results = []
        for batch_states in run_states:
            batch_results = batch_states.run_results
            batch_infers = batch_results[0].reshape([-1]).astype(
                np.int32).tolist()
            seq_lens = batch_results[1].reshape([-1]).astype(np.int32).tolist()
            current_id = 0
            for length in seq_lens:
                seq_infers = batch_infers[current_id:current_id + length]
                seq_result = list(map(id2label.get, seq_infers[1:-1]))
K
kinghuin 已提交
248
                current_id += length if self.add_crf else self.max_seq_len
K
kinghuin 已提交
249 250
                results.append(seq_result)
        return results