db_lstm.py 7.8 KB
Newer Older
Z
zhangjinchao01 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
# Copyright (c) 2016 Baidu, Inc. 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 math
import os
import sys
from paddle.trainer_config_helpers import *

#file paths
Z
zhangjinchao01 已提交
22 23 24
word_dict_file = './data/wordDict.txt'
label_dict_file = './data/targetDict.txt'
predicate_file= './data/verbDict.txt'
Z
zhangjinchao01 已提交
25 26 27 28 29 30 31 32 33 34
train_list_file = './data/train.list'
test_list_file = './data/test.list'

is_test = get_config_arg('is_test', bool, False)
is_predict = get_config_arg('is_predict', bool, False)

if not is_predict:
    #load dictionaries
    word_dict = dict()
    label_dict = dict()
Z
zhangjinchao01 已提交
35
    predicate_dict = dict()
Z
zhangjinchao01 已提交
36
    with open(word_dict_file, 'r') as f_word, \
Z
zhangjinchao01 已提交
37 38
         open(label_dict_file, 'r') as f_label, \
         open(predicate_file, 'r') as f_pre:
Z
zhangjinchao01 已提交
39 40 41 42 43 44 45 46
        for i, line in enumerate(f_word):
            w = line.strip()
            word_dict[w] = i

        for i, line in enumerate(f_label):
            w = line.strip()
            label_dict[w] = i

Z
zhangjinchao01 已提交
47 48 49 50 51
        for i, line in enumerate(f_pre):
            w = line.strip()
            predicate_dict[w] = i


Z
zhangjinchao01 已提交
52 53 54 55 56 57 58 59 60 61
    if is_test:
        train_list_file = None 

    #define data provider
    define_py_data_sources2(
        train_list=train_list_file,
        test_list=test_list_file,
        module='dataprovider',
        obj='process',
        args={'word_dict': word_dict,
Z
zhangjinchao01 已提交
62 63
              'label_dict': label_dict,
              'predicate_dict': predicate_dict })
Z
zhangjinchao01 已提交
64 65 66

    word_dict_len = len(word_dict)
    label_dict_len = len(label_dict)
Z
zhangjinchao01 已提交
67
    pred_len = len(predicate_dict)
Z
zhangjinchao01 已提交
68 69 70 71

else:
    word_dict_len = get_config_arg('dict_len', int)
    label_dict_len = get_config_arg('label_len', int)
Z
zhangjinchao01 已提交
72
    pred_len = get_config_arg('pred_len', int)
Z
zhangjinchao01 已提交
73

Z
zhangjinchao01 已提交
74
############################## Hyper-parameters ##################################
Z
zhangjinchao01 已提交
75 76 77
mark_dict_len = 2
word_dim = 32
mark_dim = 5
Z
zhangjinchao01 已提交
78
hidden_dim = 512
Z
zhangjinchao01 已提交
79
depth = 8
Z
zhangjinchao01 已提交
80 81 82 83 84



########################### Optimizer #######################################

Z
zhangjinchao01 已提交
85 86 87

settings(
    batch_size=150,
Z
zhangjinchao01 已提交
88 89
    learning_method=MomentumOptimizer(momentum=0),
    learning_rate=2e-2,
Z
zhangjinchao01 已提交
90
    regularization=L2Regularization(8e-4),
Z
zhangjinchao01 已提交
91 92 93 94 95
    is_async=False,
    model_average=ModelAverage(average_window=0.5,
                               max_average_window=10000),
                               
)
Z
zhangjinchao01 已提交
96

Z
zhangjinchao01 已提交
97 98 99 100 101



####################################### network ##############################
#8 features and 1 target
Z
zhangjinchao01 已提交
102
word = data_layer(name='word_data', size=word_dict_len)
Z
zhangjinchao01 已提交
103 104 105
predicate = data_layer(name='verb_data', size=pred_len)

ctx_n2 = data_layer(name='ctx_n2_data', size=word_dict_len)
Z
zhangjinchao01 已提交
106 107 108
ctx_n1 = data_layer(name='ctx_n1_data', size=word_dict_len)
ctx_0 = data_layer(name='ctx_0_data', size=word_dict_len)
ctx_p1 = data_layer(name='ctx_p1_data', size=word_dict_len)
Z
zhangjinchao01 已提交
109
ctx_p2 = data_layer(name='ctx_p2_data', size=word_dict_len)
Z
zhangjinchao01 已提交
110 111
mark = data_layer(name='mark_data', size=mark_dict_len)

Z
zhangjinchao01 已提交
112

Z
zhangjinchao01 已提交
113 114 115 116
if not is_predict:
    target = data_layer(name='target', size=label_dict_len)


Z
zhangjinchao01 已提交
117 118 119 120 121 122 123 124
default_std=1/math.sqrt(hidden_dim)/3.0

emb_para = ParameterAttribute(name='emb', initial_std=0., learning_rate=0.)
std_0 = ParameterAttribute(initial_std=0.)
std_default = ParameterAttribute(initial_std=default_std) 

word_embedding = embedding_layer(size=word_dim, input=word, param_attr=emb_para)
predicate_embedding = embedding_layer(size=word_dim, input=predicate, param_attr=ParameterAttribute(name='vemb',initial_std=default_std))
Z
zhangjcqq 已提交
125

Z
zhangjinchao01 已提交
126 127 128 129 130 131 132
ctx_n2_embedding = embedding_layer(size=word_dim, input=ctx_n2, param_attr=emb_para)
ctx_n1_embedding = embedding_layer(size=word_dim, input=ctx_n1, param_attr=emb_para)
ctx_0_embedding = embedding_layer(size=word_dim, input=ctx_0, param_attr=emb_para)
ctx_p1_embedding = embedding_layer(size=word_dim, input=ctx_p1, param_attr=emb_para)
ctx_p2_embedding = embedding_layer(size=word_dim, input=ctx_p2, param_attr=emb_para)
mark_embedding = embedding_layer(name='word_ctx-in_embedding', size=mark_dim, input=mark, param_attr=std_0)

Z
zhangjinchao01 已提交
133 134

hidden_0 = mixed_layer(
Z
zhangjinchao01 已提交
135
    name='hidden0',
Z
zhangjinchao01 已提交
136
    size=hidden_dim,
Z
zhangjinchao01 已提交
137
    bias_attr=std_default,
Z
zhangjinchao01 已提交
138
    input=[
Z
zhangjinchao01 已提交
139 140 141 142 143 144 145 146
        full_matrix_projection(input=word_embedding, param_attr=std_default),
        full_matrix_projection(input=predicate_embedding, param_attr=std_default),
        full_matrix_projection(input=ctx_n2_embedding, param_attr=std_default),
        full_matrix_projection(input=ctx_n1_embedding, param_attr=std_default),
        full_matrix_projection(input=ctx_0_embedding, param_attr=std_default),
        full_matrix_projection(input=ctx_p1_embedding, param_attr=std_default),
        full_matrix_projection(input=ctx_p2_embedding, param_attr=std_default),
        full_matrix_projection(input=mark_embedding, param_attr=std_default)
Z
zhangjinchao01 已提交
147 148
    ])

Z
zhangjinchao01 已提交
149 150 151 152 153 154 155 156 157 158 159 160

mix_hidden_lr = 1e-3
lstm_para_attr = ParameterAttribute(initial_std=0.0, learning_rate=1.0)
hidden_para_attr = ParameterAttribute(initial_std=default_std, learning_rate=mix_hidden_lr)

lstm_0 = lstmemory(name='lstm0',
                   input=hidden_0, 
                   act=ReluActivation(),
                   gate_act=SigmoidActivation(),
                   state_act=SigmoidActivation(),
                   bias_attr=std_0,
                   param_attr=lstm_para_attr)
Z
zhangjinchao01 已提交
161 162 163 164

#stack L-LSTM and R-LSTM with direct edges
input_tmp = [hidden_0, lstm_0]

Z
zhangjinchao01 已提交
165

Z
zhangjinchao01 已提交
166 167
for i in range(1, depth):

Z
zhangjinchao01 已提交
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
    mix_hidden = mixed_layer(name='hidden'+str(i),
                             size=hidden_dim, 
                             bias_attr=std_default,
                             input=[full_matrix_projection(input=input_tmp[0], param_attr=hidden_para_attr),
                                    full_matrix_projection(input=input_tmp[1], param_attr=lstm_para_attr)
                                   ]
                             )

    lstm = lstmemory(name='lstm'+str(i),
                     input=mix_hidden,
                     act=ReluActivation(),
                     gate_act=SigmoidActivation(),
                     state_act=SigmoidActivation(),
                     reverse=((i % 2)==1),
                     bias_attr=std_0,
                     param_attr=lstm_para_attr)

    input_tmp = [mix_hidden, lstm]

feature_out = mixed_layer(name='output',
                          size=label_dict_len,
                          bias_attr=std_default, 
                          input=[full_matrix_projection(input=input_tmp[0], param_attr=hidden_para_attr),
                                 full_matrix_projection(input=input_tmp[1], param_attr=lstm_para_attr)
                                ],
                          )
Z
zhangjinchao01 已提交
194 195 196 197



if not is_predict:
Z
zhangjinchao01 已提交
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
    crf_l = crf_layer( name = 'crf',
                       size = label_dict_len,
                       input = feature_out, 
                       label = target,
                       param_attr=ParameterAttribute(name='crfw',initial_std=default_std, learning_rate=mix_hidden_lr)

                      )

    
    crf_dec_l = crf_decoding_layer(name = 'crf_dec_l',
                                   size = label_dict_len,
                                   input = feature_out,
                                   label = target,
                                   param_attr=ParameterAttribute(name='crfw')
                                       )


    eval = sum_evaluator(input=crf_dec_l)
        
    outputs(crf_l)

Z
zhangjinchao01 已提交
219
else:
Z
zhangjinchao01 已提交
220 221 222 223 224 225 226 227
    crf_dec_l = crf_decoding_layer(name = 'crf_dec_l',
                                   size = label_dict_len,
                                   input = feature_out,
                                   param_attr=ParameterAttribute(name='crfw')
                                       )

    outputs(crf_dec_l)