network_conf.py 2.3 KB
Newer Older
P
peterzhang2029 已提交
1
import paddle.v2 as paddle
P
peterzhang2029 已提交
2
from config import ModelConfig as conf
P
peterzhang2029 已提交
3 4 5


def cnn_cov_group(group_input, hidden_size):
P
peterzhang2029 已提交
6
    """
P
peterzhang2029 已提交
7
    Convolution group definition.
P
peterzhang2029 已提交
8 9
    :param group_input: The input of this layer.
    :type group_input: LayerOutput
P
peterzhang2029 已提交
10
    :params hidden_size: The size of the fully connected layer.
P
peterzhang2029 已提交
11 12
    :type hidden_size: int
    """
P
peterzhang2029 已提交
13 14 15 16
    conv3 = paddle.networks.sequence_conv_pool(
        input=group_input, context_len=3, hidden_size=hidden_size)
    conv4 = paddle.networks.sequence_conv_pool(
        input=group_input, context_len=4, hidden_size=hidden_size)
17

P
peterzhang2029 已提交
18 19
    fc_param_attr = paddle.attr.ParamAttr(name='_cov_value_weight')
    fc_bias_attr = paddle.attr.ParamAttr(name='_cov_value_bias')
20 21 22 23 24
    linear_proj = paddle.layer.fc(input=[conv3, conv4],
                                  size=hidden_size,
                                  param_attr=[fc_param_attr, fc_param_attr],
                                  bias_attr=fc_bias_attr,
                                  act=paddle.activation.Linear())
25

P
peterzhang2029 已提交
26
    return linear_proj
P
peterzhang2029 已提交
27 28


P
peterzhang2029 已提交
29 30 31 32 33 34 35
def nested_net(dict_dim, class_num, is_infer=False):
    """
    Nested network definition.
    :param dict_dim: Size of word dictionary.
    :type dict_dim: int
    :params class_num: Number of instance class.
    :type class_num: int
P
peterzhang2029 已提交
36
    :params is_infer: The boolean parameter
P
peterzhang2029 已提交
37 38 39
                        indicating inferring or training.
    :type is_infer: bool
    """
P
peterzhang2029 已提交
40 41 42
    data = paddle.layer.data(
        "word", paddle.data_type.integer_value_sub_sequence(dict_dim))

P
peterzhang2029 已提交
43
    emb = paddle.layer.embedding(input=data, size=conf.emb_size)
P
peterzhang2029 已提交
44
    nest_group = paddle.layer.recurrent_group(
P
peterzhang2029 已提交
45
        input=[paddle.layer.SubsequenceInput(emb), conf.hidden_size],
P
peterzhang2029 已提交
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
        step=cnn_cov_group)
    avg_pool = paddle.layer.pooling(
        input=nest_group,
        pooling_type=paddle.pooling.Avg(),
        agg_level=paddle.layer.AggregateLevel.TO_NO_SEQUENCE)
    prob = paddle.layer.mixed(
        size=class_num,
        input=[paddle.layer.full_matrix_projection(input=avg_pool)],
        act=paddle.activation.Softmax())
    if is_infer == False:
        label = paddle.layer.data("label",
                                  paddle.data_type.integer_value(class_num))
        cost = paddle.layer.classification_cost(input=prob, label=label)
        return cost, prob, label

    return prob