cls.py 3.9 KB
Newer Older
X
xixiaoyao 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# -*- 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.

import paddle.fluid as fluid
from paddle.fluid import layers
X
xixiaoyao 已提交
18 19 20
from paddlepalm.interface import task_paradigm
import numpy as np
import os
X
xixiaoyao 已提交
21 22 23 24 25

class TaskParadigm(task_paradigm):
    '''
    classification
    '''
X
xixiaoyao 已提交
26
    def __init__(self, config, phase, backbone_config=None):
X
xixiaoyao 已提交
27
        self._is_training = phase == 'train'
X
xixiaoyao 已提交
28
        self._hidden_size = backbone_config['hidden_size']
X
xixiaoyao 已提交
29 30
        self.num_classes = config['n_classes']
    
X
xixiaoyao 已提交
31 32 33 34 35 36 37 38 39
        if 'initializer_range' in config:
            self._param_initializer = config['initializer_range']
        else:
            self._param_initializer = fluid.initializer.TruncatedNormal(
                scale=backbone_config.get('initializer_range', 0.02))
        if 'dropout_prob' in config:
            self._dropout_prob = config['dropout_prob']
        else:
            self._dropout_prob = backbone_config.get('hidden_dropout_prob', 0.0)
X
xixiaoyao 已提交
40 41
        self._pred_output_path = config.get('pred_output_path', None)
        self._preds = []
X
xixiaoyao 已提交
42

X
xixiaoyao 已提交
43 44
    @property
    def inputs_attrs(self):
X
xixiaoyao 已提交
45
        if self._is_training:
W
wangxiao 已提交
46
            reader = {"label_ids": [[-1], 'int64']}
X
xixiaoyao 已提交
47 48 49 50
        else:
            reader = {}
        bb = {"sentence_embedding": [[-1, self._hidden_size], 'float32']}
        return {'reader': reader, 'backbone': bb}
X
xixiaoyao 已提交
51 52 53 54 55 56

    @property
    def outputs_attrs(self):
        if self._is_training:
            return {'loss': [[1], 'float32']}
        else:
X
xixiaoyao 已提交
57
            return {'logits': [[-1, self.num_classes], 'float32']}
X
xixiaoyao 已提交
58

X
xixiaoyao 已提交
59
    def build(self, inputs, scope_name=''):
X
xixiaoyao 已提交
60 61
        sent_emb = inputs['backbone']['sentence_embedding']
        if self._is_training:
X
xixiaoyao 已提交
62
            label_ids = inputs['reader']['label_ids']
X
xixiaoyao 已提交
63 64 65 66 67
            cls_feats = fluid.layers.dropout(
                x=sent_emb,
                dropout_prob=self._dropout_prob,
                dropout_implementation="upscale_in_train")

X
xixiaoyao 已提交
68
        logits = fluid.layers.fc(
X
xixiaoyao 已提交
69
            input=sent_emb,
X
xixiaoyao 已提交
70 71
            size=self.num_classes,
            param_attr=fluid.ParamAttr(
X
xixiaoyao 已提交
72
                name=scope_name+"cls_out_w",
X
xixiaoyao 已提交
73
                initializer=self._param_initializer),
X
xixiaoyao 已提交
74
            bias_attr=fluid.ParamAttr(
X
xixiaoyao 已提交
75
                name=scope_name+"cls_out_b", initializer=fluid.initializer.Constant(0.)))
X
xixiaoyao 已提交
76 77

        if self._is_training:
W
wangxiao 已提交
78 79
            loss = fluid.layers.cross_entropy(
                input=logits, label=label_ids)
X
xixiaoyao 已提交
80
            loss = layers.mean(loss)
X
xixiaoyao 已提交
81 82 83
            return {"loss": loss}
        else:
            return {"logits":logits}
X
xixiaoyao 已提交
84

X
xixiaoyao 已提交
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
    def postprocess(self, rt_outputs):
        if not self._is_training:
            logits = rt_outputs['logits']
            preds = np.argmax(logits, -1)
            self._preds.extend(preds.tolist())

    def epoch_postprocess(self, post_inputs):
        # there is no post_inputs needed and not declared in epoch_inputs_attrs, hence no elements exist in post_inputs
        if not self._is_training:
            if self._pred_output_path is None:
                raise ValueError('argument pred_output_path not found in config. Please add it into config dict/file.')
            with open(os.path.join(self._pred_output_path, 'predictions.json'), 'w') as writer:
                for p in self._preds:
                    writer.write(str(p)+'\n')
            print('Predictions saved at '+os.path.join(self._pred_output_path, 'predictions.json'))