task.py 5.8 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
    """

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

    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 已提交
47 48 49 50 51 52

    def main_program(self):
        return self._main_program

    def startup_program(self):
        return self._startup_program
W
wuzewu 已提交
53 54 55

    def inference_program(self):
        return self._inference_program
56 57 58 59 60 61 62

    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 已提交
63 64


65
def create_text_cls_task(feature, label, num_classes, hidden_units=None):
Z
Zeyu Chen 已提交
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
    """
    Append a multi-layer perceptron classifier for binary classification base
    on input feature
    """
    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.)))

    ce_loss, probs = fluid.layers.softmax_with_cross_entropy(
        logits=logits, label=label, return_softmax=True)
    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
    }

    task = Task("text_classification", graph_var_dict,
                fluid.default_main_program(), fluid.default_startup_program())

    return task


108
def create_img_cls_task(feature, label, num_classes, hidden_units=None):
Z
Zeyu Chen 已提交
109
    """
Z
Zeyu Chen 已提交
110 111 112 113 114 115 116 117 118
    Create the transfer learning task for image classification.
    Args:
        feature:

    Return:
        Task

    Raise:
        None
Z
Zeyu Chen 已提交
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
    """
    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)

    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.)))

    ce_loss, probs = fluid.layers.softmax_with_cross_entropy(
        logits=logits, label=label, return_softmax=True)
    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
    }

150
    task = Task("image_classification", graph_var_dict,
Z
Zeyu Chen 已提交
151 152 153 154 155
                fluid.default_main_program(), fluid.default_startup_program())

    return task


156
def create_seq_label_task(feature, labels, seq_len, num_classes):
Z
Zeyu Chen 已提交
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
    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_labels = fluid.layers.reshape(x=labels, shape=[-1, 1])
    ret_infers = fluid.layers.reshape(
        x=fluid.layers.argmax(logits, axis=2), shape=[-1, 1])

    labels = fluid.layers.flatten(labels, axis=2)
    ce_loss, probs = fluid.layers.softmax_with_cross_entropy(
        logits=fluid.layers.flatten(logits, axis=2),
        label=labels,
        return_softmax=True)
    loss = fluid.layers.mean(x=ce_loss)

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

    task = Task("sequence_labeling", graph_var_dict,
                fluid.default_main_program(), fluid.default_startup_program())

    return task