network_conf.py 4.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# Copyright (c) 2018 PaddlePaddle Authors. 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.
"""
neural network for word2vec
"""

from __future__ import print_function

Q
Qiao Longfei 已提交
20
import math
21
import numpy as np
Q
Qiao Longfei 已提交
22

23 24
import paddle.fluid as fluid

25 26 27 28 29 30

def skip_gram_word2vec(dict_size,
                       word_frequencys,
                       embedding_size,
                       max_code_length=None,
                       with_hsigmoid=False,
T
tangwei12 已提交
31 32
                       with_nce=True,
                       is_sparse=False):
33
    def nce_layer(input, label, embedding_size, num_total_classes,
T
tangwei12 已提交
34
                  num_neg_samples, sampler, word_frequencys, sample_weight):
35 36 37 38

        w_param_name = "nce_w"
        b_param_name = "nce_b"
        w_param = fluid.default_main_program().global_block().create_parameter(
39 40 41
            shape=[num_total_classes, embedding_size],
            dtype='float32',
            name=w_param_name)
42 43 44
        b_param = fluid.default_main_program().global_block().create_parameter(
            shape=[num_total_classes, 1], dtype='float32', name=b_param_name)

45 46 47 48
        cost = fluid.layers.nce(input=input,
                                label=label,
                                num_total_classes=num_total_classes,
                                sampler=sampler,
T
tangwei12 已提交
49
                                custom_dist=word_frequencys,
50 51 52
                                sample_weight=sample_weight,
                                param_attr=fluid.ParamAttr(name=w_param_name),
                                bias_attr=fluid.ParamAttr(name=b_param_name),
J
JiabinYang 已提交
53 54
                                num_neg_samples=num_neg_samples,
                                is_sparse=is_sparse)
55 56 57

        return cost

58 59
    def hsigmoid_layer(input, label, path_table, path_code, non_leaf_num,
                       is_sparse):
T
tangwei12 已提交
60
        if non_leaf_num is None:
61 62 63
            non_leaf_num = dict_size

        cost = fluid.layers.hsigmoid(
T
tangwei12 已提交
64 65
            input=input,
            label=label,
J
JiabinYang 已提交
66
            num_classes=non_leaf_num,
67 68
            path_table=path_table,
            path_code=path_code,
J
JiabinYang 已提交
69
            is_custom=True,
J
JiabinYang 已提交
70
            is_sparse=is_sparse)
71 72

        return cost
Q
Qiao Longfei 已提交
73

T
tangwei12 已提交
74
    datas = []
75

T
tangwei12 已提交
76
    input_word = fluid.layers.data(name="input_word", shape=[1], dtype='int64')
J
JiabinYang 已提交
77 78
    predict_word = fluid.layers.data(
        name='predict_word', shape=[1], dtype='int64')
T
tangwei12 已提交
79 80 81 82
    datas.append(input_word)
    datas.append(predict_word)

    if with_hsigmoid:
83 84
        path_table = fluid.layers.data(
            name='path_table',
J
JiabinYang 已提交
85 86
            shape=[max_code_length if max_code_length else 40],
            dtype='int64')
87 88
        path_code = fluid.layers.data(
            name='path_code',
J
JiabinYang 已提交
89 90
            shape=[max_code_length if max_code_length else 40],
            dtype='int64')
91 92
        datas.append(path_table)
        datas.append(path_code)
T
tangwei12 已提交
93

J
JiabinYang 已提交
94 95
    py_reader = fluid.layers.create_py_reader_by_data(
        capacity=64, feed_list=datas, name='py_reader', use_double_buffer=True)
T
tangwei12 已提交
96

T
tangwei12 已提交
97
    words = fluid.layers.read_file(py_reader)
98

Q
Qiao Longfei 已提交
99
    emb = fluid.layers.embedding(
T
tangwei12 已提交
100
        input=words[0],
T
tangwei12 已提交
101
        is_sparse=is_sparse,
Q
Qiao Longfei 已提交
102
        size=[dict_size, embedding_size],
103 104 105 106
        param_attr=fluid.ParamAttr(
            name='embeding',
            initializer=fluid.initializer.Normal(scale=1 /
                                                 math.sqrt(dict_size))))
107

T
tangwei12 已提交
108 109
    cost, cost_nce, cost_hs = None, None, None

110
    if with_nce:
J
JiabinYang 已提交
111 112
        cost_nce = nce_layer(emb, words[1], embedding_size, dict_size, 5,
                             "uniform", word_frequencys, None)
T
tangwei12 已提交
113
        cost = cost_nce
114
    if with_hsigmoid:
J
JiabinYang 已提交
115 116
        cost_hs = hsigmoid_layer(emb, words[1], words[2], words[3], dict_size,
                                 is_sparse)
T
tangwei12 已提交
117 118
        cost = cost_hs
    if with_nce and with_hsigmoid:
T
tangwei12 已提交
119
        cost = fluid.layers.elementwise_add(cost_nce, cost_hs)
Q
Qiao Longfei 已提交
120 121 122

    avg_cost = fluid.layers.reduce_mean(cost)

123
    return avg_cost, py_reader