sequence_label.py 6.5 KB
Newer Older
T
tianxin04 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#   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
C
chenxuyi 已提交
18 19 20
from __future__ import unicode_literals
from __future__ import absolute_import

T
tianxin04 已提交
21 22 23 24 25 26 27 28

import os
import time
import argparse
import numpy as np
import multiprocessing

import paddle
C
chenxuyi 已提交
29
import logging
T
tianxin04 已提交
30 31
import paddle.fluid as fluid

C
cclauss 已提交
32 33
from six.moves import xrange

T
tianxin04 已提交
34 35
from model.ernie import ErnieModel

C
chenxuyi 已提交
36
log = logging.getLogger(__name__)
Y
Yibing Liu 已提交
37 38

def create_model(args, pyreader_name, ernie_config, is_prediction=False):
T
tianxin04 已提交
39 40 41
    pyreader = fluid.layers.py_reader(
        capacity=50,
        shapes=[[-1, args.max_seq_len, 1], [-1, args.max_seq_len, 1],
Y
Yibing Liu 已提交
42
                [-1, args.max_seq_len, 1], [-1, args.max_seq_len, 1],
T
tianxin 已提交
43 44 45 46 47
                [-1, args.max_seq_len, 1], [-1, args.max_seq_len, 1], [-1, 1]],
        dtypes=[
            'int64', 'int64', 'int64', 'int64', 'float32', 'int64', 'int64'
        ],
        lod_levels=[0, 0, 0, 0, 0, 0, 0],
T
tianxin04 已提交
48 49 50
        name=pyreader_name,
        use_double_buffer=True)

T
tianxin 已提交
51
    (src_ids, sent_ids, pos_ids, task_ids, input_mask, labels,
T
tianxin04 已提交
52 53 54 55 56 57
     seq_lens) = fluid.layers.read_file(pyreader)

    ernie = ErnieModel(
        src_ids=src_ids,
        position_ids=pos_ids,
        sentence_ids=sent_ids,
T
tianxin 已提交
58
        task_ids=task_ids,
Y
Yibing Liu 已提交
59
        input_mask=input_mask,
T
tianxin04 已提交
60 61 62 63
        config=ernie_config,
        use_fp16=args.use_fp16)

    enc_out = ernie.get_sequence_output()
T
tianxin 已提交
64 65
    enc_out = fluid.layers.dropout(
        x=enc_out, dropout_prob=0.1, dropout_implementation="upscale_in_train")
T
tianxin04 已提交
66 67 68 69 70 71 72 73
    logits = fluid.layers.fc(
        input=enc_out,
        size=args.num_labels,
        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(
Y
Yibing Liu 已提交
74 75
            name="cls_seq_label_out_b",
            initializer=fluid.initializer.Constant(0.)))
76
    infers = fluid.layers.argmax(logits, axis=2)
T
tianxin04 已提交
77

78 79 80 81 82 83 84 85 86
    ret_infers = fluid.layers.reshape(x=infers, shape=[-1, 1])
    lod_labels = fluid.layers.sequence_unpad(labels, seq_lens)
    lod_infers = fluid.layers.sequence_unpad(infers, seq_lens)

    (_, _, _, num_infer, num_label, num_correct) = fluid.layers.chunk_eval(
         input=lod_infers,
         label=lod_labels,
         chunk_scheme=args.chunk_scheme,
         num_chunk_types=((args.num_labels-1)//(len(args.chunk_scheme)-1)))
T
tianxin04 已提交
87 88 89

    labels = fluid.layers.flatten(labels, axis=2)
    ce_loss, probs = fluid.layers.softmax_with_cross_entropy(
Y
Yibing Liu 已提交
90 91 92 93
        logits=fluid.layers.flatten(
            logits, axis=2),
        label=labels,
        return_softmax=True)
T
tianxin 已提交
94 95
    input_mask = fluid.layers.flatten(input_mask, axis=2)
    ce_loss = ce_loss * input_mask
T
tianxin04 已提交
96 97
    loss = fluid.layers.mean(x=ce_loss)

Y
Yibing Liu 已提交
98
    graph_vars = {
C
chenxuyi 已提交
99
        "inputs": src_ids,
Y
Yibing Liu 已提交
100 101
        "loss": loss,
        "probs": probs,
C
chenxuyi 已提交
102
        "seqlen": seq_lens,
103 104 105
        "num_infer": num_infer,
        "num_label": num_label,
        "num_correct": num_correct,
Y
Yibing Liu 已提交
106
    }
T
tianxin04 已提交
107 108

    for k, v in graph_vars.items():
Y
Yibing Liu 已提交
109
        v.persistable = True
T
tianxin04 已提交
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130

    return pyreader, graph_vars


def calculate_f1(num_label, num_infer, num_correct):
    if num_infer == 0:
        precision = 0.0
    else:
        precision = num_correct * 1.0 / num_infer

    if num_label == 0:
        recall = 0.0
    else:
        recall = num_correct * 1.0 / num_label

    if num_correct == 0:
        f1 = 0.0
    else:
        f1 = 2 * precision * recall / (precision + recall)
    return precision, recall, f1

Y
Yibing Liu 已提交
131 132 133 134 135 136 137 138

def evaluate(exe,
             program,
             pyreader,
             graph_vars,
             tag_num,
             dev_count=1):
    fetch_list = [
139 140
        graph_vars["num_infer"].name, graph_vars["num_label"].name,
        graph_vars["num_correct"].name
Y
Yibing Liu 已提交
141
    ]
T
tianxin04 已提交
142

C
chenxuyi 已提交
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
    total_label, total_infer, total_correct = 0.0, 0.0, 0.0
    time_begin = time.time()
    pyreader.start()
    while True:
        try:
            np_num_infer, np_num_label, np_num_correct = exe.run(program=program,
                                                    fetch_list=fetch_list)
            total_infer += np.sum(np_num_infer)
            total_label += np.sum(np_num_label)
            total_correct += np.sum(np_num_correct)

        except fluid.core.EOFException:
            pyreader.reset()
            break

    precision, recall, f1 = calculate_f1(total_label, total_infer,
                                         total_correct)
    time_end = time.time()
    return  \
        "[evaluation] f1: %f, precision: %f, recall: %f, elapsed time: %f s" \
        % (f1, precision, recall, time_end - time_begin)


def chunk_predict(np_inputs, np_probs, np_lens, dev_count=1):
    inputs = np_inputs.reshape([-1]).astype(np.int32)
    probs = np_probs.reshape([-1, np_probs.shape[-1]])

    all_lens = np_lens.reshape([dev_count, -1]).astype(np.int32).tolist()

    base_index = 0
    out = []
    for dev_index in xrange(dev_count):
        lens = all_lens[dev_index]
        max_len = 0
        for l in lens:
            max_len = max(max_len, l)

        for i in xrange(len(lens)):
            seq_st = base_index + i * max_len + 1
            seq_en = seq_st + (lens[i] - 2)
            prob = probs[seq_st:seq_en, :]
C
chenxuyi 已提交
184
            infers = np.argmax(prob, -1)
C
chenxuyi 已提交
185 186 187
            out.append((
                    inputs[seq_st:seq_en].tolist(), 
                    infers.tolist(),
C
chenxuyi 已提交
188
                    prob.tolist()))
C
chenxuyi 已提交
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
        base_index += max_len * len(lens)
    return out


def predict(exe,
            test_program,
            test_pyreader,
            graph_vars,
            dev_count=1):
    fetch_list = [
        graph_vars["inputs"].name,
        graph_vars["probs"].name,
        graph_vars["seqlen"].name,
    ]

    test_pyreader.start()
    res = []
    while True:
        try:
C
chenxuyi 已提交
208
            inputs, probs, np_lens = exe.run(program=test_program,
C
chenxuyi 已提交
209 210 211 212 213 214 215
                                        fetch_list=fetch_list)
            r = chunk_predict(inputs, probs, np_lens, dev_count)
            res += r
        except fluid.core.EOFException:
            test_pyreader.reset()
            break
    return res
T
tianxin04 已提交
216