model.py 2.4 KB
Newer Older
T
tangwei 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   Copyright (c) 2020 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.

X
xujiaqi01 已提交
15 16 17
import paddle.fluid as fluid
import math

18 19
from paddlerec.core.utils import envs
from paddlerec.core.model import Model as ModelBase
X
xujiaqi01 已提交
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

import paddle.fluid as fluid
import paddle.fluid.layers.nn as nn
import paddle.fluid.layers.tensor as tensor
import paddle.fluid.layers.control_flow as cf

class Model(ModelBase):
    def __init__(self, config):
        ModelBase.__init__(self, config)

    def train_net(self):
        """ network definition """
       
        data = fluid.data(name="input", shape=[None, max_len], dtype='int64')
        label = fluid.data(name="label", shape=[None, 1], dtype='int64')
        seq_len = fluid.data(name="seq_len", shape=[None], dtype='int64')
        # embedding layer
        emb = fluid.embedding(input=data, size=[dict_dim, emb_dim])
        emb = fluid.layers.sequence_unpad(emb, length=seq_len)
        # convolution layer
        conv = fluid.nets.sequence_conv_pool(
            input=emb,
            num_filters=cnn_dim,
            filter_size=cnn_filter_size,
            act="tanh",
            pool_type="max")

        # full connect layer
        fc_1 = fluid.layers.fc(input=[conv], size=hid_dim)
        # softmax layer
        prediction = fluid.layers.fc(input=[fc_1], size=class_dim, act="softmax")
T
tangwei 已提交
51

X
xujiaqi01 已提交
52 53 54 55 56 57 58 59 60 61 62 63 64 65
        cost = fluid.layers.cross_entropy(input=prediction, label=label)
        avg_cost = fluid.layers.mean(x=cost)
        acc = fluid.layers.accuracy(input=prediction, label=label) 

        self.cost = avg_cost
        self.metrics["acc"] = cos_pos

    def get_cost_op(self):
        return self.cost

    def get_metrics(self):
        return self.metrics

    def optimizer(self):
T
tangwei 已提交
66
        learning_rate = 0.01
X
xujiaqi01 已提交
67
        sgd_optimizer = fluid.optimizer.Adagrad(learning_rate=learning_rate)
T
tangwei 已提交
68

X
xujiaqi01 已提交
69 70 71 72 73
        return sgd_optimizer


    def infer_net(self, parameter_list):
        self.train_net()