sentiment_classifier.py 5.0 KB
Newer Older
W
wangxiao1021 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# 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.
"""Sentiment Classification in Paddle Dygraph Mode. """

from __future__ import print_function
import numpy as np
import paddle.fluid as fluid
L
LielinJiang 已提交
19 20 21 22
from paddle.incubate.hapi.model import set_device, Model, CrossEntropy, Input
from paddle.incubate.hapi.configure import Config
from paddle.incubate.hapi.text.senta import SentaProcessor
from paddle.incubate.hapi.metrics import Accuracy
W
wangxiao1021 已提交
23 24 25 26 27 28 29 30 31 32 33
from models import CNN, BOW, GRU, BiGRU
import json
import os

args = Config(yaml_file='./senta.yaml')
args.build()
args.Print()

device = set_device("gpu" if args.use_cuda else "cpu")
dev_count = fluid.core.get_cuda_device_count() if args.use_cuda else 1

L
LielinJiang 已提交
34

W
wangxiao1021 已提交
35 36 37 38 39 40
def main():
    if args.do_train:
        train()
    elif args.do_infer:
        infer()

L
LielinJiang 已提交
41

W
wangxiao1021 已提交
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
def train():
    fluid.enable_dygraph(device)
    processor = SentaProcessor(
        data_dir=args.data_dir,
        vocab_path=args.vocab_path,
        random_seed=args.random_seed)
    num_labels = len(processor.get_labels())

    num_train_examples = processor.get_num_examples(phase="train")

    max_train_steps = args.epoch * num_train_examples // args.batch_size // dev_count

    train_data_generator = processor.data_generator(
        batch_size=args.batch_size,
        padding_size=args.padding_size,
        places=device,
        phase='train',
        epoch=args.epoch,
        shuffle=False)

    eval_data_generator = processor.data_generator(
        batch_size=args.batch_size,
        padding_size=args.padding_size,
        places=device,
        phase='dev',
        epoch=args.epoch,
        shuffle=False)
    if args.model_type == 'cnn_net':
L
LielinJiang 已提交
70
        model = CNN(args.vocab_size, args.batch_size, args.padding_size)
W
wangxiao1021 已提交
71
    elif args.model_type == 'bow_net':
L
LielinJiang 已提交
72
        model = BOW(args.vocab_size, args.batch_size, args.padding_size)
W
wangxiao1021 已提交
73
    elif args.model_type == 'gru_net':
L
LielinJiang 已提交
74
        model = GRU(args.vocab_size, args.batch_size, args.padding_size)
W
wangxiao1021 已提交
75
    elif args.model_type == 'bigru_net':
L
LielinJiang 已提交
76 77 78 79 80
        model = BiGRU(args.vocab_size, args.batch_size, args.padding_size)

    optimizer = fluid.optimizer.Adagrad(
        learning_rate=args.lr, parameter_list=model.parameters())

W
wangxiao1021 已提交
81 82
    inputs = [Input([None, None], 'int64', name='doc')]
    labels = [Input([None, 1], 'int64', name='label')]
L
LielinJiang 已提交
83

W
wangxiao1021 已提交
84 85 86
    model.prepare(
        optimizer,
        CrossEntropy(),
L
LielinJiang 已提交
87
        Accuracy(topk=(1, )),
W
wangxiao1021 已提交
88 89 90
        inputs,
        labels,
        device=device)
L
LielinJiang 已提交
91

W
wangxiao1021 已提交
92 93 94 95 96 97 98 99
    model.fit(train_data=train_data_generator,
              eval_data=eval_data_generator,
              batch_size=args.batch_size,
              epochs=args.epoch,
              save_dir=args.checkpoints,
              eval_freq=args.eval_freq,
              save_freq=args.save_freq)

L
LielinJiang 已提交
100

W
wangxiao1021 已提交
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
def infer():
    fluid.enable_dygraph(device)
    processor = SentaProcessor(
        data_dir=args.data_dir,
        vocab_path=args.vocab_path,
        random_seed=args.random_seed)

    infer_data_generator = processor.data_generator(
        batch_size=args.batch_size,
        padding_size=args.padding_size,
        places=device,
        phase='infer',
        epoch=1,
        shuffle=False)
    if args.model_type == 'cnn_net':
L
LielinJiang 已提交
116
        model_infer = CNN(args.vocab_size, args.batch_size, args.padding_size)
W
wangxiao1021 已提交
117
    elif args.model_type == 'bow_net':
L
LielinJiang 已提交
118
        model_infer = BOW(args.vocab_size, args.batch_size, args.padding_size)
W
wangxiao1021 已提交
119
    elif args.model_type == 'gru_net':
L
LielinJiang 已提交
120
        model_infer = GRU(args.vocab_size, args.batch_size, args.padding_size)
W
wangxiao1021 已提交
121
    elif args.model_type == 'bigru_net':
L
LielinJiang 已提交
122 123 124
        model_infer = BiGRU(args.vocab_size, args.batch_size,
                            args.padding_size)

W
wangxiao1021 已提交
125 126 127
    print('Do inferring ...... ')
    inputs = [Input([None, None], 'int64', name='doc')]
    model_infer.prepare(
L
LielinJiang 已提交
128
        None, CrossEntropy(), Accuracy(topk=(1, )), inputs, device=device)
W
wangxiao1021 已提交
129 130 131 132 133 134
    model_infer.load(args.checkpoints, reset_optimizer=True)
    preds = model_infer.predict(test_data=infer_data_generator)
    preds = np.array(preds[0]).reshape((-1, 2))

    if args.output_dir:
        with open(os.path.join(args.output_dir, 'predictions.json'), 'w') as w:
L
LielinJiang 已提交
135

W
wangxiao1021 已提交
136 137
            for p in range(len(preds)):
                label = np.argmax(preds[p])
L
LielinJiang 已提交
138 139 140 141 142 143 144 145 146
                result = json.dumps({
                    'index': p,
                    'label': label,
                    'probs': preds[p].tolist()
                })
                w.write(result + '\n')
        print('Predictions saved at ' + os.path.join(args.output_dir,
                                                     'predictions.json'))

W
wangxiao1021 已提交
147 148 149

if __name__ == '__main__':
    main()