task.py 7.4 KB
Newer Older
1
#  Copyright (c) 2019  PaddlePaddle Authors. All Rights Reserved.
Z
Zeyu Chen 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14
#
# 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.

15 16 17 18
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

Z
Zeyu Chen 已提交
19
import os
20 21 22 23
import collections
import time
import multiprocessing

W
wuzewu 已提交
24 25 26
import numpy as np
import paddle.fluid as fluid

Z
Zeyu Chen 已提交
27 28

class Task(object):
Z
Zeyu Chen 已提交
29 30 31 32 33
    """
    A simple transfer learning task definition,
    including Paddle's main_program, startup_program and inference program
    """

W
wuzewu 已提交
34 35 36 37 38 39
    def __init__(self,
                 task_type,
                 graph_var_dict,
                 main_program,
                 startup_program,
                 inference_program=None):
40 41
        self.task_type = task_type
        self.graph_var_dict = graph_var_dict
Z
Zeyu Chen 已提交
42 43
        self._main_program = main_program
        self._startup_program = startup_program
W
wuzewu 已提交
44 45
        self._inference_program = inference_program
        self._test_program = main_program.clone(for_test=True)
46 47 48 49 50 51

    def variable(self, var_name):
        if var_name in self.graph_var_dict:
            return self.graph_var_dict[var_name]

        raise KeyError("var_name {} not in task graph".format(var_name))
Z
Zeyu Chen 已提交
52 53 54 55 56 57

    def main_program(self):
        return self._main_program

    def startup_program(self):
        return self._startup_program
W
wuzewu 已提交
58 59 60

    def inference_program(self):
        return self._inference_program
61

W
wuzewu 已提交
62 63 64
    def test_program(self):
        return self._test_program

65 66 67 68 69 70
    def metric_variable_names(self):
        metric_variable_names = []
        for var_name in self.graph_var_dict:
            metric_variable_names.append(var_name)

        return metric_variable_names
Z
Zeyu Chen 已提交
71 72


W
wuzewu 已提交
73
def create_text_cls_task(feature, num_classes, hidden_units=None):
Z
Zeyu Chen 已提交
74 75 76 77
    """
    Append a multi-layer perceptron classifier for binary classification base
    on input feature
    """
W
wuzewu 已提交
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
    program = feature.block.program
    with fluid.program_guard(program):
        cls_feats = fluid.layers.dropout(
            x=feature,
            dropout_prob=0.1,
            dropout_implementation="upscale_in_train")

        # append fully connected layer according to hidden_units
        if hidden_units is not None:
            for n_hidden in hidden_units:
                cls_feats = fluid.layers.fc(input=cls_feats, size=n_hidden)

        logits = fluid.layers.fc(
            input=cls_feats,
            size=num_classes,
            param_attr=fluid.ParamAttr(
                name="cls_out_w",
                initializer=fluid.initializer.TruncatedNormal(scale=0.02)),
            bias_attr=fluid.ParamAttr(
                name="cls_out_b", initializer=fluid.initializer.Constant(0.)),
            act="softmax")

        inference_program = fluid.default_main_program().clone(for_test=True)
        label = fluid.layers.data(name="label", dtype="int64", shape=[1])
        ce_loss = fluid.layers.cross_entropy(input=logits, label=label)
        loss = fluid.layers.mean(x=ce_loss)

        num_example = fluid.layers.create_tensor(dtype='int64')
        accuracy = fluid.layers.accuracy(
            input=logits, label=label, total=num_example)

        graph_var_dict = {
            "loss": loss,
            "accuracy": accuracy,
            "num_example": num_example,
            "label": label,
            "probs": logits
        }

        task = Task(
            "text_classification",
            graph_var_dict,
            fluid.default_main_program(),
            fluid.default_startup_program(),
            inference_program=inference_program)
Z
Zeyu Chen 已提交
123 124 125 126

    return task


W
wuzewu 已提交
127
def create_img_cls_task(feature, num_classes, hidden_units=None):
Z
Zeyu Chen 已提交
128
    """
Z
Zeyu Chen 已提交
129 130 131 132 133 134 135 136 137
    Create the transfer learning task for image classification.
    Args:
        feature:

    Return:
        Task

    Raise:
        None
Z
Zeyu Chen 已提交
138
    """
W
wuzewu 已提交
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
    program = feature.block.program
    with fluid.program_guard(program):
        cls_feats = feature
        # append fully connected layer according to hidden_units
        if hidden_units is not None:
            for n_hidden in hidden_units:
                cls_feats = fluid.layers.fc(input=cls_feats, size=n_hidden)

        probs = fluid.layers.fc(
            input=cls_feats,
            size=num_classes,
            param_attr=fluid.ParamAttr(
                name="cls_out_w",
                initializer=fluid.initializer.TruncatedNormal(scale=0.02)),
            bias_attr=fluid.ParamAttr(
                name="cls_out_b", initializer=fluid.initializer.Constant(0.)),
            act="softmax")

        inference_program = fluid.default_main_program().clone(for_test=True)

        label = fluid.layers.data(name="label", dtype="int64", shape=[1])
        ce_loss = fluid.layers.cross_entropy(input=probs, label=label)
        loss = fluid.layers.mean(x=ce_loss)

        num_example = fluid.layers.create_tensor(dtype='int64')
        accuracy = fluid.layers.accuracy(
            input=probs, label=label, total=num_example)

        graph_var_dict = {
            "loss": loss,
            "probs": probs,
            "accuracy": accuracy,
            "num_example": num_example,
            "label": label,
            "probs": probs
        }

        task = Task(
            "image_classification",
            graph_var_dict,
            fluid.default_main_program(),
            fluid.default_startup_program(),
            inference_program=inference_program)
Z
Zeyu Chen 已提交
182 183 184 185

    return task


W
wuzewu 已提交
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
def create_seq_label_task(feature, max_seq_len, num_classes):
    program = feature.block.program
    with fluid.program_guard(program):
        logits = fluid.layers.fc(
            input=feature,
            size=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.)))

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

        logits = fluid.layers.flatten(logits, axis=2)
        logits = fluid.layers.softmax(logits)

        inference_program = fluid.default_main_program().clone(for_test=True)

        seq_len = fluid.layers.data(name="seq_len", shape=[1], dtype='int64')
        label = fluid.layers.data(
            name="label", shape=[max_seq_len, 1], dtype='int64')
        ret_labels = fluid.layers.reshape(x=label, shape=[-1, 1])

        labels = fluid.layers.flatten(label, axis=2)
        ce_loss = fluid.layers.cross_entropy(input=logits, label=labels)
        loss = fluid.layers.mean(x=ce_loss)

        graph_var_dict = {
            "loss": loss,
            "probs": logits,
            "labels": ret_labels,
            "infers": ret_infers,
            "seq_len": seq_len,
            "label": label
        }

        task = Task(
            "sequence_labeling",
            graph_var_dict,
            fluid.default_main_program(),
            fluid.default_startup_program(),
            inference_program=inference_program)
Z
Zeyu Chen 已提交
232 233

    return task