senta_finetune.py 2.0 KB
Newer Older
S
Steffy-zxf 已提交
1
#coding:utf-8
W
wuzewu 已提交
2 3 4 5 6 7 8 9 10
import argparse
import ast

import paddle.fluid as fluid
import paddlehub as hub

# yapf: disable
parser = argparse.ArgumentParser(__doc__)
parser.add_argument("--num_epoch", type=int, default=3, help="Number of epoches for fine-tuning.")
S
Steffy-zxf 已提交
11
parser.add_argument("--use_gpu", type=ast.literal_eval, default=True, help="Whether use GPU for finetuning, input should be True or False")
W
wuzewu 已提交
12 13 14 15 16 17 18
parser.add_argument("--checkpoint_dir", type=str, default=None, help="Directory to model checkpoint")
parser.add_argument("--batch_size", type=int, default=32, help="Total examples' number in batch for training.")
args = parser.parse_args()
# yapf: enable.

if __name__ == '__main__':
    # Step1: load Paddlehub senta pretrained model
Z
Zeyu Chen 已提交
19
    module = hub.Module(name="senta_bilstm")
W
wuzewu 已提交
20 21
    inputs, outputs, program = module.context(trainable=True)

S
Steffy-zxf 已提交
22
    # Step2: Download dataset and use LACClassifyReader to read dataset
W
wuzewu 已提交
23 24
    dataset = hub.dataset.ChnSentiCorp()

Z
Zeyu Chen 已提交
25
    reader = hub.reader.LACClassifyReader(
W
wuzewu 已提交
26 27
        dataset=dataset, vocab_path=module.get_vocab_path())

Z
Zeyu Chen 已提交
28
    sent_feature = outputs["sentence_feature"]
W
wuzewu 已提交
29 30 31

    # Setup feed list for data feeder
    # Must feed all the tensor of senta's module need
S
Steffy-zxf 已提交
32
    feed_list = [inputs["words"].name]
W
wuzewu 已提交
33

Z
Zeyu Chen 已提交
34
    strategy = hub.finetune.strategy.AdamWeightDecayStrategy(
Z
Zeyu Chen 已提交
35
        learning_rate=1e-4, weight_decay=0.01, warmup_proportion=0.05)
Z
Zeyu Chen 已提交
36

W
wuzewu 已提交
37 38 39 40 41
    config = hub.RunConfig(
        use_cuda=args.use_gpu,
        num_epoch=args.num_epoch,
        batch_size=args.batch_size,
        checkpoint_dir=args.checkpoint_dir,
Z
zhangxuefei 已提交
42
        use_pyreader=False,
Z
Zeyu Chen 已提交
43
        strategy=strategy)
W
wuzewu 已提交
44

S
Steffy-zxf 已提交
45 46 47 48 49 50 51 52
    # Define a classfication finetune task by PaddleHub's API
    cls_task = hub.TextClassifierTask(
        data_reader=reader,
        feature=sent_feature,
        feed_list=feed_list,
        num_classes=dataset.num_labels,
        config=config)

W
wuzewu 已提交
53 54
    # Finetune and evaluate by PaddleHub's API
    # will finish training, evaluation, testing, save model automatically
S
Steffy-zxf 已提交
55
    cls_task.finetune_and_eval()