sentimental_provider.py 2.0 KB
Newer Older
D
dzhwinter 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
#  Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve.
#
#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.
Z
zhangjinchao01 已提交
14 15 16 17 18 19 20 21 22 23
from paddle.trainer.PyDataProvider2 import *


def on_init(settings, dictionary, **kwargs):
    # on_init will invoke when data provider is initialized. The dictionary
    # is passed from trainer_config, and is a dict object with type
    # (word string => word id).

    # set input types in runtime. It will do the same thing as
    # @provider(input_types) will do, but it is set dynamically during runtime.
L
Luo Tao 已提交
24
    settings.input_types = {
Z
zhangjinchao01 已提交
25 26 27
        # The text is a sequence of integer values, and each value is a word id.
        # The whole sequence is the sentences that we want to predict its
        # sentimental.
L
Luo Tao 已提交
28 29 30
        'data': integer_value_sequence(len(dictionary)),  # text input
        'label': integer_value(2)  # label positive/negative
    }
Z
zhangjinchao01 已提交
31

L
Luo Tao 已提交
32 33
    # save dictionary as settings.dictionary. 
    # It will be used in process method.
Z
zhangjinchao01 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
    settings.dictionary = dictionary


@provider(init_hook=on_init)
def process(settings, filename):
    f = open(filename, 'r')

    for line in f:  # read each line of file
        label, sentence = line.split('\t')  # get label and sentence
        words = sentence.split(' ')  # get words

        # convert word string to word id
        # the word not in dictionary will be ignored.
        word_ids = []

        for each_word in words:
            if each_word in settings.dictionary:
                word_ids.append(settings.dictionary[each_word])

        # give data to paddle.
        yield word_ids, int(label)

    f.close()