model.py 2.0 KB
Newer Older
X
xujiaqi01 已提交
1 2 3
import paddle.fluid as fluid
import math

4 5
from paddlerec.core.utils import envs
from paddlerec.core.model import Model as ModelBase
X
xujiaqi01 已提交
6 7 8 9 10 11 12 13 14

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)
X
fix  
xujiaqi01 已提交
15 16 17 18 19 20 21
        self.dict_dim = 100
        self.max_len = 10
        self.cnn_dim = 32
        self.cnn_filter_size = 128
        self.emb_dim = 8
        self.hid_dim = 128
        self.class_dim = 2
X
xujiaqi01 已提交
22 23 24 25

    def train_net(self):
        """ network definition """
       
X
fix  
xujiaqi01 已提交
26
        data = fluid.data(name="input", shape=[None, self.max_len], dtype='int64')
X
xujiaqi01 已提交
27 28 29
        label = fluid.data(name="label", shape=[None, 1], dtype='int64')
        seq_len = fluid.data(name="seq_len", shape=[None], dtype='int64')
        # embedding layer
X
fix  
xujiaqi01 已提交
30 31
        emb = fluid.embedding(input=data, size=[self.dict_dim, self.emb_dim])
        emb = fluid.layers.sequence_unpad(emb, length=self.seq_len)
X
xujiaqi01 已提交
32 33 34
        # convolution layer
        conv = fluid.nets.sequence_conv_pool(
            input=emb,
X
fix  
xujiaqi01 已提交
35 36
            num_filters=self.cnn_dim,
            filter_size=self.cnn_filter_size,
X
xujiaqi01 已提交
37 38 39 40 41 42
            act="tanh",
            pool_type="max")

        # full connect layer
        fc_1 = fluid.layers.fc(input=[conv], size=hid_dim)
        # softmax layer
X
fix  
xujiaqi01 已提交
43
        prediction = fluid.layers.fc(input=[fc_1], size=self.class_dim, act="softmax")
X
xujiaqi01 已提交
44 45 46 47 48 49 50 51 52 53 54 55 56 57
        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):
X
fix  
xujiaqi01 已提交
58
        learning_rate = 0.01
X
xujiaqi01 已提交
59 60 61 62 63
        sgd_optimizer = fluid.optimizer.Adagrad(learning_rate=learning_rate)
        return sgd_optimizer

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