train_v2.py 10.7 KB
Newer Older
1
from os.path import join as join_path
H
hedaoyuan 已提交
2 3
import paddle.trainer_config_helpers.attrs as attrs
from paddle.trainer_config_helpers.poolings import MaxPooling
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 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 108 109 110 111 112 113 114 115 116 117 118 119
import paddle.v2 as paddle
import paddle.v2.layer as layer
import paddle.v2.activation as activation
import paddle.v2.data_type as data_type


def sequence_conv_pool(input,
                       input_size,
                       context_len,
                       hidden_size,
                       name=None,
                       context_start=None,
                       pool_type=None,
                       context_proj_layer_name=None,
                       context_proj_param_attr=False,
                       fc_layer_name=None,
                       fc_param_attr=None,
                       fc_bias_attr=None,
                       fc_act=None,
                       pool_bias_attr=None,
                       fc_attr=None,
                       context_attr=None,
                       pool_attr=None):
    """
    Text convolution pooling layers helper.

    Text input => Context Projection => FC Layer => Pooling => Output.

    :param name: name of output layer(pooling layer name)
    :type name: basestring
    :param input: name of input layer
    :type input: LayerOutput
    :param context_len: context projection length. See
                        context_projection's document.
    :type context_len: int
    :param hidden_size: FC Layer size.
    :type hidden_size: int
    :param context_start: context projection length. See
                          context_projection's context_start.
    :type context_start: int or None
    :param pool_type: pooling layer type. See pooling_layer's document.
    :type pool_type: BasePoolingType.
    :param context_proj_layer_name: context projection layer name.
                                    None if user don't care.
    :type context_proj_layer_name: basestring
    :param context_proj_param_attr: context projection parameter attribute.
                                    None if user don't care.
    :type context_proj_param_attr: ParameterAttribute or None.
    :param fc_layer_name: fc layer name. None if user don't care.
    :type fc_layer_name: basestring
    :param fc_param_attr: fc layer parameter attribute. None if user don't care.
    :type fc_param_attr: ParameterAttribute or None
    :param fc_bias_attr: fc bias parameter attribute. False if no bias,
                         None if user don't care.
    :type fc_bias_attr: ParameterAttribute or None
    :param fc_act: fc layer activation type. None means tanh
    :type fc_act: BaseActivation
    :param pool_bias_attr: pooling layer bias attr. None if don't care.
                           False if no bias.
    :type pool_bias_attr: ParameterAttribute or None.
    :param fc_attr: fc layer extra attribute.
    :type fc_attr: ExtraLayerAttribute
    :param context_attr: context projection layer extra attribute.
    :type context_attr: ExtraLayerAttribute
    :param pool_attr: pooling layer extra attribute.
    :type pool_attr: ExtraLayerAttribute
    :return: output layer name.
    :rtype: LayerOutput
    """
    # Set Default Value to param
    context_proj_layer_name = "%s_conv_proj" % name \
        if context_proj_layer_name is None else context_proj_layer_name

    with layer.mixed(
            name=context_proj_layer_name,
            size=input_size * context_len,
            act=activation.Linear(),
            layer_attr=context_attr) as m:
        m += layer.context_projection(
            input=input,
            context_len=context_len,
            context_start=context_start,
            padding_attr=context_proj_param_attr)

    fc_layer_name = "%s_conv_fc" % name \
        if fc_layer_name is None else fc_layer_name
    fl = layer.fc(name=fc_layer_name,
                  input=m,
                  size=hidden_size,
                  act=fc_act,
                  layer_attr=fc_attr,
                  param_attr=fc_param_attr,
                  bias_attr=fc_bias_attr)

    return layer.pooling(
        name=name,
        input=fl,
        pooling_type=pool_type,
        bias_attr=pool_bias_attr,
        layer_attr=pool_attr)


def convolution_net(input_dim,
                    class_dim=2,
                    emb_dim=128,
                    hid_dim=128,
                    is_predict=False):
    data = layer.data("word", data_type.integer_value_sequence(input_dim))
    emb = layer.embedding(input=data, size=emb_dim)
    conv_3 = sequence_conv_pool(
        input=emb, input_size=emb_dim, context_len=3, hidden_size=hid_dim)
    conv_4 = sequence_conv_pool(
        input=emb, input_size=emb_dim, context_len=4, hidden_size=hid_dim)
    output = layer.fc(input=[conv_3, conv_4],
                      size=class_dim,
                      act=activation.Softmax())
H
hedaoyuan 已提交
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 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 184 185 186
    lbl = layer.data("label", data_type.integer_value(2))
    cost = layer.classification_cost(input=output, label=lbl)
    return cost


def stacked_lstm_net(input_dim,
                     class_dim=2,
                     emb_dim=128,
                     hid_dim=512,
                     stacked_num=3,
                     is_predict=False):
    """
    A Wrapper for sentiment classification task.
    This network uses bi-directional recurrent network,
    consisting three LSTM layers. This configure is referred to
    the paper as following url, but use fewer layrs.
        http://www.aclweb.org/anthology/P15-1109

    input_dim: here is word dictionary dimension.
    class_dim: number of categories.
    emb_dim: dimension of word embedding.
    hid_dim: dimension of hidden layer.
    stacked_num: number of stacked lstm-hidden layer.
    is_predict: is predicting or not.
                Some layers is not needed in network when predicting.
    """
    assert stacked_num % 2 == 1

    layer_attr = attrs.ExtraLayerAttribute(drop_rate=0.5)
    fc_para_attr = attrs.ParameterAttribute(learning_rate=1e-3)
    lstm_para_attr = attrs.ParameterAttribute(initial_std=0., learning_rate=1.)
    para_attr = [fc_para_attr, lstm_para_attr]
    bias_attr = attrs.ParameterAttribute(initial_std=0., l2_rate=0.)
    relu = activation.Relu()
    linear = activation.Linear()

    data = layer.data("word", data_type.integer_value_sequence(input_dim))
    emb = layer.embedding(input=data, size=emb_dim)

    fc1 = layer.fc(input=emb, size=hid_dim, act=linear, bias_attr=bias_attr)
    lstm1 = layer.lstmemory(
        input=fc1, act=relu, bias_attr=bias_attr, layer_attr=layer_attr)

    inputs = [fc1, lstm1]
    for i in range(2, stacked_num + 1):
        fc = layer.fc(input=inputs,
                      size=hid_dim,
                      act=linear,
                      param_attr=para_attr,
                      bias_attr=bias_attr)
        lstm = layer.lstmemory(
            input=fc,
            reverse=(i % 2) == 0,
            act=relu,
            bias_attr=bias_attr,
            layer_attr=layer_attr)
        inputs = [fc, lstm]

    fc_last = layer.pooling(input=inputs[0], pooling_type=MaxPooling())
    lstm_last = layer.pooling(input=inputs[1], pooling_type=MaxPooling())
    output = layer.fc(input=[fc_last, lstm_last],
                      size=class_dim,
                      act=activation.Softmax(),
                      bias_attr=bias_attr,
                      param_attr=para_attr)

    lbl = layer.data("label", data_type.integer_value(2))
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
    cost = layer.classification_cost(input=output, label=lbl)
    return cost


def data_reader():
    data_dir = "./data/pre-imdb"
    train_file = "train_part_000"
    test_file = "test_part_000"
    dict_file = "dict.txt"
    train_file = join_path(data_dir, train_file)
    test_file = join_path(data_dir, test_file)
    dict_file = join_path(data_dir, dict_file)

    with open(dict_file, 'r') as fdict, open(train_file, 'r') as fdata:
        dictionary = dict()
        for i, line in enumerate(fdict):
            dictionary[line.split('\t')[0]] = i

        for line_count, line in enumerate(fdata):
            label, comment = line.strip().split('\t\t')
            label = int(label)
            words = comment.split()
            word_slot = [dictionary[w] for w in words if w in dictionary]
            yield (word_slot, label)


H
hedaoyuan 已提交
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
def test_reader():
    data_dir = "./data/pre-imdb"
    train_file = "train_part_000"
    test_file = "test_part_000"
    dict_file = "dict.txt"
    train_file = join_path(data_dir, train_file)
    test_file = join_path(data_dir, test_file)
    dict_file = join_path(data_dir, dict_file)

    with open(dict_file, 'r') as fdict, open(test_file, 'r') as ftest:
        dictionary = dict()
        for i, line in enumerate(fdict):
            dictionary[line.split('\t')[0]] = i

        for line_count, line in enumerate(ftest):
            label, comment = line.strip().split('\t\t')
            label = int(label)
            words = comment.split()
            word_slot = [dictionary[w] for w in words if w in dictionary]
            yield (word_slot, label)


235 236 237 238 239 240 241 242 243 244 245 246 247
if __name__ == '__main__':
    data_dir = "./data/pre-imdb"
    train_list = "train.list"
    test_list = "test.list"
    dict_file = "dict.txt"
    dict_dim = len(open(join_path(data_dir, "dict.txt")).readlines())
    class_dim = len(open(join_path(data_dir, 'labels.list')).readlines())
    is_predict = False

    # init
    paddle.init(use_gpu=True, trainer_count=4)

    # network config
H
hedaoyuan 已提交
248 249 250
    # cost = convolution_net(dict_dim, class_dim=class_dim, is_predict=is_predict)
    cost = stacked_lstm_net(
        dict_dim, class_dim=class_dim, stacked_num=3, is_predict=is_predict)
251 252 253 254

    # create parameters
    parameters = paddle.parameters.create(cost)

H
hedaoyuan 已提交
255 256 257 258
    adam_optimizer = paddle.optimizer.Adam(
        learning_rate=2e-3,
        regularization=paddle.optimizer.L2Regularization(rate=8e-4),
        model_average=paddle.optimizer.ModelAverage(average_window=0.5))
259 260 261

    def event_handler(event):
        if isinstance(event, paddle.event.EndIteration):
H
hedaoyuan 已提交
262
            if event.batch_id % 100 == 0:
263 264
                print "Pass %d, Batch %d, Cost %f, %s" % (
                    event.pass_id, event.batch_id, event.cost, event.metrics)
H
hedaoyuan 已提交
265 266 267 268 269 270 271
        if isinstance(event, paddle.event.EndPass):
            result = trainer.test(
                reader=paddle.reader.batched(
                    test_reader, batch_size=128),
                reader_dict={'word': 0,
                             'label': 1})
            print "Test with Pass %d, %s" % (event.pass_id, result.metrics)
272 273 274 275 276 277 278

    trainer = paddle.trainer.SGD(cost=cost,
                                 parameters=parameters,
                                 update_equation=adam_optimizer)

    trainer.train(
        reader=paddle.reader.batched(
H
hedaoyuan 已提交
279 280
            paddle.reader.shuffle(
                data_reader, buf_size=4096), batch_size=128),
281 282 283 284
        event_handler=event_handler,
        reader_dict={'word': 0,
                     'label': 1},
        num_passes=10)