gen_proto_data.py 7.8 KB
Newer Older
1
# Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved
Z
zhangjinchao01 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#
# 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.

from cStringIO import StringIO

import paddle.proto.DataFormat_pb2 as DataFormat
from google.protobuf.internal.encoder import _EncodeVarint

import logging
import pprint

logging.basicConfig(
24
    format='[%(levelname)s %(asctime)s %(filename)s:%(lineno)s] %(message)s', )
Z
zhangjinchao01 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37
logger = logging.getLogger('paddle')
logger.setLevel(logging.INFO)

OOV_POLICY_IGNORE = 0
OOV_POLICY_USE = 1
OOV_POLICY_ERROR = 2

num_original_columns = 3

# Feature combination patterns.
# [[-1,0], [0,0]]  means previous token at column 0 and current token at
# column 0 are combined as one feature.
patterns = [
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
    [[-2, 0]],
    [[-1, 0]],
    [[0, 0]],
    [[1, 0]],
    [[2, 0]],
    [[-1, 0], [0, 0]],
    [[0, 0], [1, 0]],
    [[-2, 1]],
    [[-1, 1]],
    [[0, 1]],
    [[1, 1]],
    [[2, 1]],
    [[-2, 1], [-1, 1]],
    [[-1, 1], [0, 1]],
    [[0, 1], [1, 1]],
    [[1, 1], [2, 1]],
    [[-2, 1], [-1, 1], [0, 1]],
    [[-1, 1], [0, 1], [1, 1]],
    [[0, 1], [1, 1], [2, 1]],
Z
zhangjinchao01 已提交
57 58
]

59

Z
zhangjinchao01 已提交
60 61 62
def make_features(sequence):
    length = len(sequence)
    num_features = len(sequence[0])
63

Z
zhangjinchao01 已提交
64 65 66 67 68 69 70 71 72
    def get_features(pos):
        if pos < 0:
            return ['#B%s' % -pos] * num_features
        if pos >= length:
            return ['#E%s' % (pos - length + 1)] * num_features
        return sequence[pos]

    for i in xrange(length):
        for pattern in patterns:
73
            fname = '/'.join([get_features(i + pos)[f] for pos, f in pattern])
Z
zhangjinchao01 已提交
74 75
            sequence[i].append(fname)

76

Z
zhangjinchao01 已提交
77 78 79 80 81 82 83 84 85 86 87 88
'''
Source file format:
Each line is for one timestep. The features are separated by space.
An empty line indicates end of a sequence.

cutoff: a list of numbers. If count of a feature is smaller than this,
 it will be ignored.
if oov_policy[i] is OOV_POLICY_USE, id 0 is reserved for OOV features of
i-th column.

return a list of dict for each column
'''
89 90


Z
zhangjinchao01 已提交
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 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
def create_dictionaries(filename, cutoff, oov_policy):
    def add_to_dict(sequence, dicts):
        num_features = len(dicts)
        for features in sequence:
            l = len(features)
            assert l == num_features, "Wrong number of features " + line
            for i in xrange(l):
                if features[i] in dicts[i]:
                    dicts[i][features[i]] += 1
                else:
                    dicts[i][features[i]] = 1

    num_features = len(cutoff)
    dicts = []
    for i in xrange(num_features):
        dicts.append(dict())

    f = open(filename, 'rb')

    sequence = []

    for line in f:
        line = line.strip()
        if not line:
            make_features(sequence)
            add_to_dict(sequence, dicts)
            sequence = []
            continue
        features = line.split(' ')
        sequence.append(features)

    for i in xrange(num_features):
        dct = dicts[i]
        n = 1 if oov_policy[i] == OOV_POLICY_USE else 0
        todo = []
        for k, v in dct.iteritems():
            if v < cutoff[i]:
                todo.append(k)
            else:
                dct[k] = n
                n += 1

        if oov_policy[i] == OOV_POLICY_USE:
            # placeholder so that len(dct) will be the number of features
            # including OOV
            dct['#OOV#'] = 0

        logger.info('column %d dict size=%d, ignored %d' % (i, n, len(todo)))
        for k in todo:
            del dct[k]

    f.close()
    return dicts


def encode_varint(v):
    out = StringIO()
    _EncodeVarint(out.write, v)
    return out.getvalue()


def write_proto(file, message):
    s = message.SerializeToString()
    packed_len = encode_varint(len(s))
    file.write(packed_len + s)


'''
if oov_policy[i] == OOV_POLICY_USE, features in i-th column which are not
existed in dicts[i] will be assigned to id 0.
if oov_policy[i] == OOV_POLICY_ERROR, all features in i-th column MUST exist
in dicts[i].
'''

165 166

def gen_proto_file(input_file, dicts, oov_policy, output_file):
Z
zhangjinchao01 已提交
167 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 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
    def write_sequence(out, sequence):
        num_features = len(dicts)
        is_beginning = True
        for features in sequence:
            assert len(features) == num_features, \
                "Wrong number of features: " + line
            sample = DataFormat.DataSample()
            for i in xrange(num_original_columns):
                id = dicts[i].get(features[i], -1)
                if id != -1:
                    sample.id_slots.append(id)
                elif oov_policy[i] == OOV_POLICY_IGNORE:
                    sample.id_slots.append(0xffffffff)
                elif oov_policy[i] == OOV_POLICY_ERROR:
                    logger.fatal("Unknown token: %s" % features[i])
                else:
                    sample.id_slots.append(0)

            if patterns:
                dim = 0
                vec = sample.vector_slots.add()
                for i in xrange(num_original_columns, num_features):
                    id = dicts[i].get(features[i], -1)
                    if id != -1:
                        vec.ids.append(dim + id)
                    elif oov_policy[i] == OOV_POLICY_IGNORE:
                        pass
                    elif oov_policy[i] == OOV_POLICY_ERROR:
                        logger.fatal("Unknown token: %s" % features[i])
                    else:
                        vec.ids.append(dim + 0)

                    dim += len(dicts[i])

            sample.is_beginning = is_beginning
            is_beginning = False
            write_proto(out, sample)

    num_features = len(dicts)
    f = open(input_file, 'rb')
    out = open(output_file, 'wb')

    header = DataFormat.DataHeader()
    if patterns:
        slot_def = header.slot_defs.add()
        slot_def.type = DataFormat.SlotDef.VECTOR_SPARSE_NON_VALUE
213 214
        slot_def.dim = sum(
            [len(dicts[i]) for i in xrange(num_original_columns, len(dicts))])
Z
zhangjinchao01 已提交
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
        logger.info("feature_dim=%s" % slot_def.dim)

    for i in xrange(num_original_columns):
        slot_def = header.slot_defs.add()
        slot_def.type = DataFormat.SlotDef.INDEX
        slot_def.dim = len(dicts[i])

    write_proto(out, header)

    num_sequences = 0
    sequence = []
    for line in f:
        line = line.strip()
        if not line:
            make_features(sequence)
            write_sequence(out, sequence)
            sequence = []
            num_sequences += 1
            continue
        features = line.split(' ')
        sequence.append(features)

    f.close()
    out.close()

    logger.info("num_sequences=%s" % num_sequences)

242

Z
zhangjinchao01 已提交
243
dict2 = {
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
    'B-ADJP': 0,
    'I-ADJP': 1,
    'B-ADVP': 2,
    'I-ADVP': 3,
    'B-CONJP': 4,
    'I-CONJP': 5,
    'B-INTJ': 6,
    'I-INTJ': 7,
    'B-LST': 8,
    'I-LST': 9,
    'B-NP': 10,
    'I-NP': 11,
    'B-PP': 12,
    'I-PP': 13,
    'B-PRT': 14,
    'I-PRT': 15,
    'B-SBAR': 16,
    'I-SBAR': 17,
    'B-UCP': 18,
    'I-UCP': 19,
    'B-VP': 20,
    'I-VP': 21,
    'O': 22
Z
zhangjinchao01 已提交
267 268 269 270 271 272 273
}

if __name__ == '__main__':
    cutoff = [3, 1, 0]
    cutoff += [3] * len(patterns)
    oov_policy = [OOV_POLICY_IGNORE, OOV_POLICY_ERROR, OOV_POLICY_ERROR]
    oov_policy += [OOV_POLICY_IGNORE] * len(patterns)
274
    dicts = create_dictionaries('trainer/tests/train.txt', cutoff, oov_policy)
Z
zhangjinchao01 已提交
275
    dicts[2] = dict2
276 277 278 279
    gen_proto_file('trainer/tests/train.txt', dicts, oov_policy,
                   'trainer/tests/train_proto.bin')
    gen_proto_file('trainer/tests/test.txt', dicts, oov_policy,
                   'trainer/tests/test_proto.bin')